cwtools-mcp 0.2.9 → 0.5.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.
@@ -61,7 +61,7 @@ var require_config = __commonJS({
61
61
  http: false,
62
62
  host: "127.0.0.1",
63
63
  port: 3e3,
64
- enableWrites: false,
64
+ enableWrites: true,
65
65
  allowedTools: [],
66
66
  forceStart: false,
67
67
  standalone: false,
@@ -213,12 +213,21 @@ ${helpText()}`);
213
213
  " --rules <dir> Explicit CWT rules directory (a .zip is rejected). When omitted, the",
214
214
  " rules the installed VS Code extension pulled into globalStorage are used.",
215
215
  "",
216
+ "Domain writes:",
217
+ " (default) Six whitelisted domain-write tools are enabled in bridge and standalone modes.",
218
+ " --enable-writes Compatibility alias; writes are already enabled by default.",
219
+ " --allow-domain-writes Equivalent compatibility alias. No CLI read-only switch is provided.",
220
+ " --allow-tool <name> Restrict standalone write tools to an explicit allowlist.",
221
+ "",
216
222
  "Project gate:",
217
- " (default) Tools are always listed. The language server starts only when the",
218
- " workspace is (or sits in/above) a Paradox mod (descriptor.mod, common/,",
219
- " events/, localisation/, .cwtools/). On other workspaces tool calls are",
220
- " rejected with a reason and no server spawns.",
221
- " --force-start Treat the workspace as supported even without mod markers."
223
+ " (default) Reliable evidence is required: descriptor.mod, a valid CWTools profile,",
224
+ " distinctive game directories, Workshop App ID, or multiple PDX content",
225
+ " directories with real payload files. Unsupported/ambiguous workspaces",
226
+ " disclose no tools/resources and never spawn the language server.",
227
+ " A unique child mod is used as the effective root; multiple child projects",
228
+ " require --workspace. Unknown games use generic paradox mode, never an",
229
+ " implicit Stellaris model. CWT-only workspaces expose seven CWT tools.",
230
+ " --force-start Use generic mode without project evidence; does not invent a game id"
222
231
  ].join("\n");
223
232
  }
224
233
  }
@@ -266,7 +275,8 @@ var require_mcpTools = __commonJS({
266
275
  "isReadOnly": true,
267
276
  "effect": "workspace_read",
268
277
  "riskLevel": 0,
269
- "concurrencyClass": "parallel"
278
+ "concurrencyClass": "parallel",
279
+ "mcpSupportsCwtOnly": false
270
280
  }
271
281
  },
272
282
  {
@@ -306,7 +316,8 @@ var require_mcpTools = __commonJS({
306
316
  "isReadOnly": true,
307
317
  "effect": "workspace_read",
308
318
  "riskLevel": 0,
309
- "concurrencyClass": "parallel"
319
+ "concurrencyClass": "parallel",
320
+ "mcpSupportsCwtOnly": false
310
321
  }
311
322
  },
312
323
  {
@@ -350,7 +361,8 @@ var require_mcpTools = __commonJS({
350
361
  "isReadOnly": true,
351
362
  "effect": "workspace_read",
352
363
  "riskLevel": 0,
353
- "concurrencyClass": "parallel"
364
+ "concurrencyClass": "parallel",
365
+ "mcpSupportsCwtOnly": false
354
366
  }
355
367
  },
356
368
  {
@@ -397,7 +409,8 @@ var require_mcpTools = __commonJS({
397
409
  "isReadOnly": true,
398
410
  "effect": "workspace_read",
399
411
  "riskLevel": 0,
400
- "concurrencyClass": "parallel"
412
+ "concurrencyClass": "parallel",
413
+ "mcpSupportsCwtOnly": false
401
414
  }
402
415
  },
403
416
  {
@@ -423,7 +436,8 @@ var require_mcpTools = __commonJS({
423
436
  "isReadOnly": true,
424
437
  "effect": "workspace_read",
425
438
  "riskLevel": 0,
426
- "concurrencyClass": "parallel"
439
+ "concurrencyClass": "parallel",
440
+ "mcpSupportsCwtOnly": false
427
441
  }
428
442
  },
429
443
  {
@@ -449,7 +463,8 @@ var require_mcpTools = __commonJS({
449
463
  "isReadOnly": true,
450
464
  "effect": "workspace_read",
451
465
  "riskLevel": 0,
452
- "concurrencyClass": "parallel"
466
+ "concurrencyClass": "parallel",
467
+ "mcpSupportsCwtOnly": false
453
468
  }
454
469
  },
455
470
  {
@@ -488,19 +503,20 @@ var require_mcpTools = __commonJS({
488
503
  "isReadOnly": true,
489
504
  "effect": "workspace_read",
490
505
  "riskLevel": 0,
491
- "concurrencyClass": "parallel"
506
+ "concurrencyClass": "parallel",
507
+ "mcpSupportsCwtOnly": false
492
508
  }
493
509
  },
494
510
  {
495
511
  "tool": {
496
512
  "name": "get_diagnostics",
497
- "description": "Get errors, warnings, information, and hints from the VS Code Problems diagnostics snapshot, optionally filtered by file and severity. Returns totals and truncation metadata; check truncated before treating the returned list as complete.",
513
+ "description": "Get errors, warnings, information, and hints from the VS Code Problems diagnostics snapshot, optionally filtered by file and severity. Counts are workspace-wide; diagnostics hidden by the workspace ignore list are reported through suppressedCount and still count in totalCount. Check truncated before treating the returned list as complete.",
498
514
  "inputSchema": {
499
515
  "type": "object",
500
516
  "properties": {
501
517
  "file": {
502
518
  "type": "string",
503
- "description": "Optional: restrict to a specific file path (absolute) or a path substring to match. Leave empty to get all workspace diagnostics."
519
+ "description": "Optional: restrict to one file, as an absolute path or a workspace-relative path. Leave empty to get all workspace diagnostics."
504
520
  },
505
521
  "severity": {
506
522
  "type": "string",
@@ -511,7 +527,7 @@ var require_mcpTools = __commonJS({
511
527
  "hint",
512
528
  "all"
513
529
  ],
514
- "description": 'Filter by severity. Default: "all"'
530
+ "description": 'Exact severity filter: "error" returns only errors. Default: "all"'
515
531
  },
516
532
  "limit": {
517
533
  "type": "number",
@@ -527,7 +543,8 @@ var require_mcpTools = __commonJS({
527
543
  "isReadOnly": true,
528
544
  "effect": "workspace_read",
529
545
  "riskLevel": 0,
530
- "concurrencyClass": "lsp-limited"
546
+ "concurrencyClass": "lsp-limited",
547
+ "mcpSupportsCwtOnly": true
531
548
  }
532
549
  },
533
550
  {
@@ -575,7 +592,8 @@ var require_mcpTools = __commonJS({
575
592
  "isReadOnly": true,
576
593
  "effect": "none",
577
594
  "riskLevel": 2,
578
- "concurrencyClass": "global-exclusive"
595
+ "concurrencyClass": "global-exclusive",
596
+ "mcpSupportsCwtOnly": true
579
597
  }
580
598
  },
581
599
  {
@@ -625,7 +643,8 @@ var require_mcpTools = __commonJS({
625
643
  "isReadOnly": true,
626
644
  "effect": "workspace_read",
627
645
  "riskLevel": 0,
628
- "concurrencyClass": "parallel"
646
+ "concurrencyClass": "parallel",
647
+ "mcpSupportsCwtOnly": false
629
648
  }
630
649
  },
631
650
  {
@@ -696,7 +715,8 @@ var require_mcpTools = __commonJS({
696
715
  "isReadOnly": true,
697
716
  "effect": "workspace_read",
698
717
  "riskLevel": 0,
699
- "concurrencyClass": "parallel"
718
+ "concurrencyClass": "parallel",
719
+ "mcpSupportsCwtOnly": false
700
720
  }
701
721
  },
702
722
  {
@@ -770,7 +790,8 @@ var require_mcpTools = __commonJS({
770
790
  "isReadOnly": true,
771
791
  "effect": "workspace_read",
772
792
  "riskLevel": 0,
773
- "concurrencyClass": "parallel"
793
+ "concurrencyClass": "parallel",
794
+ "mcpSupportsCwtOnly": false
774
795
  }
775
796
  },
776
797
  {
@@ -794,7 +815,7 @@ var require_mcpTools = __commonJS({
794
815
  },
795
816
  "exact": {
796
817
  "type": "boolean",
797
- "description": "Require query to exactly match an entity ID. Default false."
818
+ "description": "Require query to exactly match an entity ID; needs a non-empty query. Default false."
798
819
  },
799
820
  "depth": {
800
821
  "type": "number",
@@ -839,7 +860,8 @@ var require_mcpTools = __commonJS({
839
860
  "isReadOnly": true,
840
861
  "effect": "workspace_read",
841
862
  "riskLevel": 0,
842
- "concurrencyClass": "lsp-limited"
863
+ "concurrencyClass": "lsp-limited",
864
+ "mcpSupportsCwtOnly": false
843
865
  }
844
866
  },
845
867
  {
@@ -875,7 +897,8 @@ var require_mcpTools = __commonJS({
875
897
  "isReadOnly": true,
876
898
  "effect": "workspace_read",
877
899
  "riskLevel": 0,
878
- "concurrencyClass": "lsp-limited"
900
+ "concurrencyClass": "lsp-limited",
901
+ "mcpSupportsCwtOnly": false
879
902
  }
880
903
  },
881
904
  {
@@ -911,7 +934,8 @@ var require_mcpTools = __commonJS({
911
934
  "isReadOnly": true,
912
935
  "effect": "workspace_read",
913
936
  "riskLevel": 0,
914
- "concurrencyClass": "lsp-limited"
937
+ "concurrencyClass": "lsp-limited",
938
+ "mcpSupportsCwtOnly": false
915
939
  }
916
940
  },
917
941
  {
@@ -942,7 +966,8 @@ var require_mcpTools = __commonJS({
942
966
  "isReadOnly": true,
943
967
  "effect": "workspace_read",
944
968
  "riskLevel": 0,
945
- "concurrencyClass": "lsp-limited"
969
+ "concurrencyClass": "lsp-limited",
970
+ "mcpSupportsCwtOnly": false
946
971
  }
947
972
  },
948
973
  {
@@ -1152,7 +1177,8 @@ var require_mcpTools = __commonJS({
1152
1177
  "isReadOnly": true,
1153
1178
  "effect": "workspace_read",
1154
1179
  "riskLevel": 0,
1155
- "concurrencyClass": "parallel"
1180
+ "concurrencyClass": "parallel",
1181
+ "mcpSupportsCwtOnly": false
1156
1182
  }
1157
1183
  },
1158
1184
  {
@@ -1216,7 +1242,8 @@ var require_mcpTools = __commonJS({
1216
1242
  "isReadOnly": true,
1217
1243
  "effect": "workspace_read",
1218
1244
  "riskLevel": 0,
1219
- "concurrencyClass": "parallel"
1245
+ "concurrencyClass": "parallel",
1246
+ "mcpSupportsCwtOnly": false
1220
1247
  }
1221
1248
  },
1222
1249
  {
@@ -1247,7 +1274,8 @@ var require_mcpTools = __commonJS({
1247
1274
  "isReadOnly": true,
1248
1275
  "effect": "workspace_read",
1249
1276
  "riskLevel": 0,
1250
- "concurrencyClass": "parallel"
1277
+ "concurrencyClass": "parallel",
1278
+ "mcpSupportsCwtOnly": false
1251
1279
  }
1252
1280
  },
1253
1281
  {
@@ -1287,7 +1315,8 @@ var require_mcpTools = __commonJS({
1287
1315
  "isReadOnly": true,
1288
1316
  "effect": "workspace_read",
1289
1317
  "riskLevel": 0,
1290
- "concurrencyClass": "parallel"
1318
+ "concurrencyClass": "parallel",
1319
+ "mcpSupportsCwtOnly": true
1291
1320
  }
1292
1321
  },
1293
1322
  {
@@ -1313,7 +1342,8 @@ var require_mcpTools = __commonJS({
1313
1342
  "isReadOnly": true,
1314
1343
  "effect": "workspace_read",
1315
1344
  "riskLevel": 0,
1316
- "concurrencyClass": "lsp-limited"
1345
+ "concurrencyClass": "lsp-limited",
1346
+ "mcpSupportsCwtOnly": true
1317
1347
  }
1318
1348
  },
1319
1349
  {
@@ -1343,7 +1373,8 @@ var require_mcpTools = __commonJS({
1343
1373
  "isReadOnly": true,
1344
1374
  "effect": "workspace_read",
1345
1375
  "riskLevel": 0,
1346
- "concurrencyClass": "lsp-limited"
1376
+ "concurrencyClass": "lsp-limited",
1377
+ "mcpSupportsCwtOnly": true
1347
1378
  }
1348
1379
  },
1349
1380
  {
@@ -1380,7 +1411,8 @@ var require_mcpTools = __commonJS({
1380
1411
  "isReadOnly": true,
1381
1412
  "effect": "workspace_read",
1382
1413
  "riskLevel": 0,
1383
- "concurrencyClass": "lsp-limited"
1414
+ "concurrencyClass": "lsp-limited",
1415
+ "mcpSupportsCwtOnly": true
1384
1416
  }
1385
1417
  },
1386
1418
  {
@@ -1421,7 +1453,8 @@ var require_mcpTools = __commonJS({
1421
1453
  "isReadOnly": true,
1422
1454
  "effect": "workspace_read",
1423
1455
  "riskLevel": 0,
1424
- "concurrencyClass": "lsp-limited"
1456
+ "concurrencyClass": "lsp-limited",
1457
+ "mcpSupportsCwtOnly": true
1425
1458
  }
1426
1459
  },
1427
1460
  {
@@ -1449,7 +1482,8 @@ var require_mcpTools = __commonJS({
1449
1482
  "isReadOnly": true,
1450
1483
  "effect": "workspace_read",
1451
1484
  "riskLevel": 0,
1452
- "concurrencyClass": "parallel"
1485
+ "concurrencyClass": "parallel",
1486
+ "mcpSupportsCwtOnly": false
1453
1487
  }
1454
1488
  },
1455
1489
  {
@@ -1477,7 +1511,8 @@ var require_mcpTools = __commonJS({
1477
1511
  "isReadOnly": true,
1478
1512
  "effect": "workspace_read",
1479
1513
  "riskLevel": 0,
1480
- "concurrencyClass": "parallel"
1514
+ "concurrencyClass": "parallel",
1515
+ "mcpSupportsCwtOnly": false
1481
1516
  }
1482
1517
  },
1483
1518
  {
@@ -1505,7 +1540,8 @@ var require_mcpTools = __commonJS({
1505
1540
  "isReadOnly": true,
1506
1541
  "effect": "workspace_read",
1507
1542
  "riskLevel": 0,
1508
- "concurrencyClass": "parallel"
1543
+ "concurrencyClass": "parallel",
1544
+ "mcpSupportsCwtOnly": false
1509
1545
  }
1510
1546
  },
1511
1547
  {
@@ -1533,7 +1569,8 @@ var require_mcpTools = __commonJS({
1533
1569
  "isReadOnly": true,
1534
1570
  "effect": "workspace_read",
1535
1571
  "riskLevel": 0,
1536
- "concurrencyClass": "parallel"
1572
+ "concurrencyClass": "parallel",
1573
+ "mcpSupportsCwtOnly": false
1537
1574
  }
1538
1575
  },
1539
1576
  {
@@ -1557,7 +1594,8 @@ var require_mcpTools = __commonJS({
1557
1594
  "isReadOnly": true,
1558
1595
  "effect": "workspace_read",
1559
1596
  "riskLevel": 0,
1560
- "concurrencyClass": "parallel"
1597
+ "concurrencyClass": "parallel",
1598
+ "mcpSupportsCwtOnly": false
1561
1599
  }
1562
1600
  },
1563
1601
  {
@@ -1583,7 +1621,8 @@ var require_mcpTools = __commonJS({
1583
1621
  "isReadOnly": true,
1584
1622
  "effect": "workspace_read",
1585
1623
  "riskLevel": 0,
1586
- "concurrencyClass": "parallel"
1624
+ "concurrencyClass": "parallel",
1625
+ "mcpSupportsCwtOnly": false
1587
1626
  }
1588
1627
  },
1589
1628
  {
@@ -1626,7 +1665,8 @@ var require_mcpTools = __commonJS({
1626
1665
  "isReadOnly": true,
1627
1666
  "effect": "workspace_read",
1628
1667
  "riskLevel": 0,
1629
- "concurrencyClass": "lsp-limited"
1668
+ "concurrencyClass": "lsp-limited",
1669
+ "mcpSupportsCwtOnly": false
1630
1670
  }
1631
1671
  },
1632
1672
  {
@@ -1652,7 +1692,8 @@ var require_mcpTools = __commonJS({
1652
1692
  "isReadOnly": true,
1653
1693
  "effect": "workspace_read",
1654
1694
  "riskLevel": 0,
1655
- "concurrencyClass": "lsp-limited"
1695
+ "concurrencyClass": "lsp-limited",
1696
+ "mcpSupportsCwtOnly": false
1656
1697
  }
1657
1698
  },
1658
1699
  {
@@ -1678,7 +1719,8 @@ var require_mcpTools = __commonJS({
1678
1719
  "isReadOnly": true,
1679
1720
  "effect": "workspace_read",
1680
1721
  "riskLevel": 0,
1681
- "concurrencyClass": "lsp-limited"
1722
+ "concurrencyClass": "lsp-limited",
1723
+ "mcpSupportsCwtOnly": false
1682
1724
  }
1683
1725
  },
1684
1726
  {
@@ -1708,7 +1750,8 @@ var require_mcpTools = __commonJS({
1708
1750
  "isReadOnly": true,
1709
1751
  "effect": "workspace_read",
1710
1752
  "riskLevel": 0,
1711
- "concurrencyClass": "lsp-limited"
1753
+ "concurrencyClass": "lsp-limited",
1754
+ "mcpSupportsCwtOnly": false
1712
1755
  }
1713
1756
  },
1714
1757
  {
@@ -1744,7 +1787,8 @@ var require_mcpTools = __commonJS({
1744
1787
  "isReadOnly": true,
1745
1788
  "effect": "workspace_read",
1746
1789
  "riskLevel": 0,
1747
- "concurrencyClass": "lsp-limited"
1790
+ "concurrencyClass": "lsp-limited",
1791
+ "mcpSupportsCwtOnly": false
1748
1792
  }
1749
1793
  },
1750
1794
  {
@@ -1770,7 +1814,8 @@ var require_mcpTools = __commonJS({
1770
1814
  "isReadOnly": true,
1771
1815
  "effect": "workspace_read",
1772
1816
  "riskLevel": 0,
1773
- "concurrencyClass": "lsp-limited"
1817
+ "concurrencyClass": "lsp-limited",
1818
+ "mcpSupportsCwtOnly": false
1774
1819
  }
1775
1820
  },
1776
1821
  {
@@ -1798,7 +1843,8 @@ var require_mcpTools = __commonJS({
1798
1843
  "isReadOnly": true,
1799
1844
  "effect": "workspace_read",
1800
1845
  "riskLevel": 0,
1801
- "concurrencyClass": "lsp-limited"
1846
+ "concurrencyClass": "lsp-limited",
1847
+ "mcpSupportsCwtOnly": false
1802
1848
  }
1803
1849
  },
1804
1850
  {
@@ -1826,7 +1872,8 @@ var require_mcpTools = __commonJS({
1826
1872
  "isReadOnly": true,
1827
1873
  "effect": "workspace_read",
1828
1874
  "riskLevel": 0,
1829
- "concurrencyClass": "parallel"
1875
+ "concurrencyClass": "parallel",
1876
+ "mcpSupportsCwtOnly": false
1830
1877
  }
1831
1878
  },
1832
1879
  {
@@ -1869,7 +1916,8 @@ var require_mcpTools = __commonJS({
1869
1916
  "isReadOnly": true,
1870
1917
  "effect": "workspace_read",
1871
1918
  "riskLevel": 0,
1872
- "concurrencyClass": "parallel"
1919
+ "concurrencyClass": "parallel",
1920
+ "mcpSupportsCwtOnly": false
1873
1921
  }
1874
1922
  },
1875
1923
  {
@@ -1937,7 +1985,8 @@ var require_mcpTools = __commonJS({
1937
1985
  "isReadOnly": false,
1938
1986
  "effect": "workspace_write",
1939
1987
  "riskLevel": 2,
1940
- "concurrencyClass": "per-file-write"
1988
+ "concurrencyClass": "per-file-write",
1989
+ "mcpSupportsCwtOnly": false
1941
1990
  }
1942
1991
  },
1943
1992
  {
@@ -4425,7 +4474,8 @@ var require_mcpTools = __commonJS({
4425
4474
  "isReadOnly": false,
4426
4475
  "effect": "workspace_write",
4427
4476
  "riskLevel": 2,
4428
- "concurrencyClass": "per-file-write"
4477
+ "concurrencyClass": "per-file-write",
4478
+ "mcpSupportsCwtOnly": false
4429
4479
  }
4430
4480
  },
4431
4481
  {
@@ -4465,7 +4515,8 @@ var require_mcpTools = __commonJS({
4465
4515
  "isReadOnly": false,
4466
4516
  "effect": "workspace_write",
4467
4517
  "riskLevel": 2,
4468
- "concurrencyClass": "per-file-write"
4518
+ "concurrencyClass": "per-file-write",
4519
+ "mcpSupportsCwtOnly": false
4469
4520
  }
4470
4521
  },
4471
4522
  {
@@ -4509,7 +4560,8 @@ var require_mcpTools = __commonJS({
4509
4560
  "isReadOnly": false,
4510
4561
  "effect": "media",
4511
4562
  "riskLevel": 2,
4512
- "concurrencyClass": "interactive"
4563
+ "concurrencyClass": "interactive",
4564
+ "mcpSupportsCwtOnly": false
4513
4565
  }
4514
4566
  },
4515
4567
  {
@@ -4556,7 +4608,8 @@ var require_mcpTools = __commonJS({
4556
4608
  "isReadOnly": false,
4557
4609
  "effect": "media",
4558
4610
  "riskLevel": 2,
4559
- "concurrencyClass": "interactive"
4611
+ "concurrencyClass": "interactive",
4612
+ "mcpSupportsCwtOnly": false
4560
4613
  }
4561
4614
  },
4562
4615
  {
@@ -4591,10 +4644,655 @@ var require_mcpTools = __commonJS({
4591
4644
  "isReadOnly": false,
4592
4645
  "effect": "media",
4593
4646
  "riskLevel": 2,
4594
- "concurrencyClass": "interactive"
4647
+ "concurrencyClass": "interactive",
4648
+ "mcpSupportsCwtOnly": false
4649
+ }
4650
+ }
4651
+ ];
4652
+ }
4653
+ });
4654
+
4655
+ // ../cwtools-shared/dist/generated/workspaceDetectionProfiles.js
4656
+ var require_workspaceDetectionProfiles = __commonJS({
4657
+ "../cwtools-shared/dist/generated/workspaceDetectionProfiles.js"(exports2) {
4658
+ "use strict";
4659
+ Object.defineProperty(exports2, "__esModule", { value: true });
4660
+ exports2.getWorkspaceDetectionProfiles = getWorkspaceDetectionProfiles;
4661
+ var PROFILES = [
4662
+ {
4663
+ "id": "stellaris",
4664
+ "displayName": "Stellaris",
4665
+ "steamFolderName": "Stellaris",
4666
+ "exeName": "stellaris",
4667
+ "alternativeFolderNames": [],
4668
+ "steamAppId": "281990"
4669
+ },
4670
+ {
4671
+ "id": "hoi4",
4672
+ "displayName": "Hearts of Iron IV",
4673
+ "steamFolderName": "Hearts of Iron IV",
4674
+ "exeName": "hoi4",
4675
+ "alternativeFolderNames": [],
4676
+ "steamAppId": "394360"
4677
+ },
4678
+ {
4679
+ "id": "eu4",
4680
+ "displayName": "Europa Universalis IV",
4681
+ "steamFolderName": "Europa Universalis IV",
4682
+ "exeName": "eu4",
4683
+ "alternativeFolderNames": [],
4684
+ "steamAppId": "236850"
4685
+ },
4686
+ {
4687
+ "id": "ck2",
4688
+ "displayName": "Crusader Kings II",
4689
+ "steamFolderName": "Crusader Kings II",
4690
+ "exeName": "CK2",
4691
+ "alternativeFolderNames": [],
4692
+ "steamAppId": "203770"
4693
+ },
4694
+ {
4695
+ "id": "ck3",
4696
+ "displayName": "Crusader Kings III",
4697
+ "steamFolderName": "Crusader Kings III",
4698
+ "exeName": "ck3",
4699
+ "alternativeFolderNames": [],
4700
+ "steamAppId": "1158310"
4701
+ },
4702
+ {
4703
+ "id": "vic2",
4704
+ "displayName": "Victoria II",
4705
+ "steamFolderName": "Victoria 2",
4706
+ "exeName": "v2game",
4707
+ "alternativeFolderNames": [
4708
+ "Victoria II"
4709
+ ],
4710
+ "steamAppId": "42960"
4711
+ },
4712
+ {
4713
+ "id": "vic3",
4714
+ "displayName": "Victoria 3",
4715
+ "steamFolderName": "Victoria 3",
4716
+ "exeName": "victoria3",
4717
+ "alternativeFolderNames": [],
4718
+ "steamAppId": "529340"
4719
+ },
4720
+ {
4721
+ "id": "imperator",
4722
+ "displayName": "Imperator: Rome",
4723
+ "steamFolderName": "ImperatorRome",
4724
+ "exeName": "imperator",
4725
+ "alternativeFolderNames": [
4726
+ "Imperator"
4727
+ ],
4728
+ "steamAppId": "859580"
4729
+ },
4730
+ {
4731
+ "id": "eu5",
4732
+ "displayName": "Europa Universalis V",
4733
+ "steamFolderName": "Europa Universalis V",
4734
+ "exeName": "eu5",
4735
+ "alternativeFolderNames": [],
4736
+ "steamAppId": "0"
4737
+ }
4738
+ ];
4739
+ function getWorkspaceDetectionProfiles() {
4740
+ return PROFILES.map((profile) => ({ ...profile, alternativeFolderNames: [...profile.alternativeFolderNames] }));
4741
+ }
4742
+ }
4743
+ });
4744
+
4745
+ // ../cwtools-shared/dist/generated/workshopDetection.js
4746
+ var require_workshopDetection = __commonJS({
4747
+ "../cwtools-shared/dist/generated/workshopDetection.js"(exports2) {
4748
+ "use strict";
4749
+ Object.defineProperty(exports2, "__esModule", { value: true });
4750
+ exports2.parseWorkshopContentAppId = parseWorkshopContentAppId;
4751
+ exports2.getGameIdForWorkshopAppId = getGameIdForWorkshopAppId;
4752
+ var workspaceDetectionProfiles_1 = require_workspaceDetectionProfiles();
4753
+ function parseWorkshopContentAppId(rootPath) {
4754
+ const segments = rootPath.split(/[\\/]+/).filter(Boolean);
4755
+ for (let i = 0; i < segments.length - 2; i++) {
4756
+ if (segments[i].toLowerCase() === "workshop" && segments[i + 1].toLowerCase() === "content") {
4757
+ const appId = segments[i + 2];
4758
+ if (/^\d+$/.test(appId)) {
4759
+ return appId;
4760
+ }
4761
+ }
4762
+ }
4763
+ return void 0;
4764
+ }
4765
+ function getGameIdForWorkshopAppId(appId) {
4766
+ if (!/^\d+$/.test(appId) || appId === "0") {
4767
+ return void 0;
4768
+ }
4769
+ for (const profile of (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)()) {
4770
+ if (profile.steamAppId === appId) {
4771
+ return profile.id;
4772
+ }
4773
+ }
4774
+ return void 0;
4775
+ }
4776
+ }
4777
+ });
4778
+
4779
+ // ../cwtools-shared/dist/generated/workspaceGameDetection.js
4780
+ var require_workspaceGameDetection = __commonJS({
4781
+ "../cwtools-shared/dist/generated/workspaceGameDetection.js"(exports2) {
4782
+ "use strict";
4783
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
4784
+ if (k2 === void 0) k2 = k;
4785
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4786
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4787
+ desc = { enumerable: true, get: function() {
4788
+ return m[k];
4789
+ } };
4790
+ }
4791
+ Object.defineProperty(o, k2, desc);
4792
+ }) : (function(o, m, k, k2) {
4793
+ if (k2 === void 0) k2 = k;
4794
+ o[k2] = m[k];
4795
+ }));
4796
+ var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
4797
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4798
+ }) : function(o, v) {
4799
+ o["default"] = v;
4800
+ });
4801
+ var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
4802
+ var ownKeys = function(o) {
4803
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4804
+ var ar = [];
4805
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4806
+ return ar;
4807
+ };
4808
+ return ownKeys(o);
4809
+ };
4810
+ return function(mod) {
4811
+ if (mod && mod.__esModule) return mod;
4812
+ var result = {};
4813
+ if (mod != null) {
4814
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4595
4815
  }
4816
+ __setModuleDefault(result, mod);
4817
+ return result;
4818
+ };
4819
+ })();
4820
+ Object.defineProperty(exports2, "__esModule", { value: true });
4821
+ exports2.hasWorkspaceModDescriptor = hasWorkspaceModDescriptor;
4822
+ exports2.classifyWorkspaceRoot = classifyWorkspaceRoot;
4823
+ exports2.detectWorkspaceProject = detectWorkspaceProject;
4824
+ exports2.workspaceHasParadoxStructure = workspaceHasParadoxStructure;
4825
+ exports2.inferGameIdFromWorkspace = inferGameIdFromWorkspace;
4826
+ var fs = __importStar(require("fs"));
4827
+ var os = __importStar(require("os"));
4828
+ var path = __importStar(require("path"));
4829
+ var workshopDetection_1 = require_workshopDetection();
4830
+ var workspaceDetectionProfiles_1 = require_workspaceDetectionProfiles();
4831
+ var WORKSPACE_GAME_MARKERS = {
4832
+ stellaris: [
4833
+ "common/solar_system_initializers",
4834
+ "common/megastructures",
4835
+ "common/pop_faction_types",
4836
+ "common/starbase_buildings",
4837
+ "common/ship_sizes",
4838
+ "common/planet_classes",
4839
+ "map/star_classes"
4840
+ ],
4841
+ hoi4: ["common/national_focus", "common/ideas", "common/units", "history/states", "map/strategicregions"],
4842
+ eu4: ["common/countries", "common/country_tags", "common/governments", "common/religions", "history/provinces", "missions"],
4843
+ ck2: ["common/dynasties", "common/landed_titles", "common/religions", "history/characters", "history/titles"],
4844
+ ck3: ["common/dynasties", "common/landed_titles", "common/culture", "common/religion", "history/characters", "history/titles"],
4845
+ vic2: ["common/countries", "history/countries", "history/provinces", "poptypes", "units"],
4846
+ vic3: ["common/country_definitions", "common/interest_groups", "common/laws", "common/production_methods", "common/pop_types"],
4847
+ imperator: ["common/cultures", "common/religions", "common/governments", "common/countries", "setup/main"],
4848
+ eu5: ["common/countries", "common/country_tags", "common/governments", "common/laws", "common/situations"]
4849
+ };
4850
+ var WORKSPACE_GAME_TEXT_HINTS = {
4851
+ stellaris: ["stellaris", "solar system", "megastructure", "pop faction", "starbase"],
4852
+ hoi4: ["hoi4", "hearts of iron", "national focus", "strategic region"],
4853
+ eu4: ["eu4", "europa universalis iv", "europa universalis 4"],
4854
+ ck2: ["ck2", "crusader kings ii", "crusader kings 2"],
4855
+ ck3: ["ck3", "crusader kings iii", "crusader kings 3"],
4856
+ vic2: ["vic2", "victoria ii", "victoria 2"],
4857
+ vic3: ["vic3", "victoria 3", "victoria iii"],
4858
+ imperator: ["imperator", "imperator rome", "imperator: rome"],
4859
+ eu5: ["eu5", "europa universalis v", "europa universalis 5"]
4860
+ };
4861
+ var PARADOX_CONTENT_DIRS = /* @__PURE__ */ new Set([
4862
+ "common",
4863
+ "events",
4864
+ "history",
4865
+ "map",
4866
+ "map_data",
4867
+ "prescripted_countries",
4868
+ "localisation",
4869
+ "localisation_synced",
4870
+ "localization",
4871
+ "interface",
4872
+ "gfx"
4873
+ ]);
4874
+ var PDX_PAYLOAD_EXTENSIONS = /* @__PURE__ */ new Set([".txt", ".yml", ".yaml", ".csv", ".gui", ".gfx", ".asset"]);
4875
+ var SCAN_IGNORED_DIRS = /* @__PURE__ */ new Set([
4876
+ ".git",
4877
+ ".vscode",
4878
+ ".vscode-test",
4879
+ ".cwtools",
4880
+ ".cwtools-ai",
4881
+ "node_modules",
4882
+ "bin",
4883
+ "obj",
4884
+ "out",
4885
+ "output",
4886
+ "release",
4887
+ "runs",
4888
+ "artifacts",
4889
+ ".tmp-test"
4890
+ ]);
4891
+ var MAX_ANCESTORS = 6;
4892
+ var MAX_CHILDREN = 64;
4893
+ var MAX_PAYLOAD_ENTRIES = 64;
4894
+ var MAX_DESCRIPTOR_CHARS = 12e3;
4895
+ var MAX_PROFILE_BYTES = 2 * 1024 * 1024;
4896
+ var MAX_RULE_SCAN_ENTRIES = 5e3;
4897
+ function normalizeDetectionText(value) {
4898
+ return value.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
4899
+ }
4900
+ function normalizedPath(value) {
4901
+ const fold = (s) => os.platform() === "win32" ? s.toLowerCase() : s;
4902
+ try {
4903
+ return fold(path.resolve(value));
4904
+ } catch {
4905
+ return fold(value);
4906
+ }
4907
+ }
4908
+ function sameOrInside(candidate, parent) {
4909
+ const resolved = normalizedPath(candidate);
4910
+ const root = normalizedPath(parent);
4911
+ return resolved === root || resolved.startsWith(root + path.sep);
4912
+ }
4913
+ function isFile(filePath) {
4914
+ try {
4915
+ return fs.statSync(filePath).isFile();
4916
+ } catch {
4917
+ return false;
4918
+ }
4919
+ }
4920
+ function isDirectory(dirPath) {
4921
+ try {
4922
+ return fs.statSync(dirPath).isDirectory();
4923
+ } catch {
4924
+ return false;
4925
+ }
4926
+ }
4927
+ function hasRelativeDirectory(rootPath, relativePath) {
4928
+ return isDirectory(path.join(rootPath, ...relativePath.split("/")));
4929
+ }
4930
+ function readEntries(dirPath) {
4931
+ try {
4932
+ return fs.readdirSync(dirPath, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
4933
+ } catch {
4934
+ return [];
4935
+ }
4936
+ }
4937
+ function unsupported(rootPath, reason = `No reliable Paradox/CWT evidence at '${rootPath}'.`) {
4938
+ return { kind: "unsupported", evidence: [], strength: "none", reason };
4939
+ }
4940
+ function supported(kind, rootPath, evidence, strength, gameId) {
4941
+ return {
4942
+ kind,
4943
+ matchedAt: rootPath,
4944
+ evidence,
4945
+ strength,
4946
+ reason: evidence.join("; "),
4947
+ ...gameId ? { gameId } : {}
4948
+ };
4949
+ }
4950
+ function descriptorEvidence(rootPath) {
4951
+ const canonical = path.join(rootPath, "descriptor.mod");
4952
+ if (isFile(canonical))
4953
+ return "descriptor.mod";
4954
+ for (const entry of readEntries(rootPath)) {
4955
+ if (!entry.isFile() || entry.name === "descriptor.mod" || !entry.name.toLowerCase().endsWith(".mod"))
4956
+ continue;
4957
+ try {
4958
+ const content = fs.readFileSync(path.join(rootPath, entry.name), "utf8").slice(0, MAX_DESCRIPTOR_CHARS);
4959
+ const hasName = /^name\s*=/m.test(content);
4960
+ const hasRootOrVersion = /^(path|supported_version)\s*=/m.test(content);
4961
+ if (hasName && hasRootOrVersion)
4962
+ return `${entry.name} (parsed descriptor fields)`;
4963
+ } catch {
4964
+ }
4965
+ }
4966
+ return void 0;
4967
+ }
4968
+ function hasWorkspaceModDescriptor(rootPath) {
4969
+ return descriptorEvidence(rootPath) !== void 0;
4970
+ }
4971
+ function readWorkspaceGameDescriptor(rootPath) {
4972
+ const chunks = [];
4973
+ const candidates = [path.join(rootPath, "descriptor.mod"), path.join(rootPath, ".metadata", "metadata.json")];
4974
+ for (const entry of readEntries(rootPath)) {
4975
+ if (entry.isFile() && entry.name.toLowerCase().endsWith(".mod"))
4976
+ candidates.push(path.join(rootPath, entry.name));
4977
+ }
4978
+ for (const filePath of candidates) {
4979
+ try {
4980
+ if (isFile(filePath))
4981
+ chunks.push(fs.readFileSync(filePath, "utf8").slice(0, MAX_DESCRIPTOR_CHARS));
4982
+ } catch {
4983
+ }
4984
+ }
4985
+ return normalizeDetectionText(chunks.join("\n"));
4986
+ }
4987
+ function validProjectProfileGame(rootPath) {
4988
+ const profilePath = path.join(rootPath, ".cwtools", "project", "profile.json");
4989
+ try {
4990
+ if (!isFile(profilePath) || fs.statSync(profilePath).size > MAX_PROFILE_BYTES)
4991
+ return void 0;
4992
+ const raw = JSON.parse(fs.readFileSync(profilePath, "utf8"));
4993
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
4994
+ return void 0;
4995
+ const profile = raw;
4996
+ const game = typeof profile.game === "object" && profile.game !== null && !Array.isArray(profile.game) ? profile.game : void 0;
4997
+ const gameId = typeof game?.id === "string" ? game.id : "";
4998
+ const known = gameId === "paradox" || (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)().some((profileEntry) => profileEntry.id === gameId);
4999
+ const workspaceKind = profile.workspaceKind;
5000
+ if (profile.schemaVersion !== 4 || workspaceKind !== "paradox_mod" && workspaceKind !== "mixed" || typeof profile.workspaceRoot !== "string" || normalizedPath(profile.workspaceRoot) !== normalizedPath(rootPath) || !known)
5001
+ return void 0;
5002
+ return gameId;
5003
+ } catch {
5004
+ return void 0;
5005
+ }
5006
+ }
5007
+ function hasUsableNestedMetadata(rootPath) {
5008
+ try {
5009
+ const raw = JSON.parse(fs.readFileSync(path.join(rootPath, ".metadata", "metadata.json"), "utf8"));
5010
+ return typeof raw === "object" && raw !== null && !Array.isArray(raw);
5011
+ } catch {
5012
+ return false;
5013
+ }
5014
+ }
5015
+ function contentEvidence(rootPath) {
5016
+ const directories = readEntries(rootPath).filter((entry) => entry.isDirectory() && PARADOX_CONTENT_DIRS.has(entry.name.toLowerCase())).map((entry) => entry.name);
5017
+ let payload;
5018
+ for (const directory of directories) {
5019
+ const result = findPdxPayload(path.join(rootPath, directory), directory, 0);
5020
+ if (result) {
5021
+ payload = result;
5022
+ break;
5023
+ }
5024
+ }
5025
+ return { directories, ...payload ? { payload } : {} };
5026
+ }
5027
+ function findPdxPayload(dirPath, relative, depth) {
5028
+ let visited = 0;
5029
+ for (const entry of readEntries(dirPath)) {
5030
+ if (visited++ >= MAX_PAYLOAD_ENTRIES)
5031
+ break;
5032
+ if (entry.isDirectory()) {
5033
+ if (depth < 2 && !SCAN_IGNORED_DIRS.has(entry.name)) {
5034
+ const found = findPdxPayload(path.join(dirPath, entry.name), `${relative}/${entry.name}`, depth + 1);
5035
+ if (found)
5036
+ return found;
5037
+ }
5038
+ } else if (entry.isFile() && PDX_PAYLOAD_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {
5039
+ return `${relative}/${entry.name}`;
5040
+ }
5041
+ }
5042
+ return void 0;
5043
+ }
5044
+ function isCwtRuleWorkspace(rootPath) {
5045
+ if (descriptorEvidence(rootPath))
5046
+ return false;
5047
+ let count = 0;
5048
+ let cwtCount = 0;
5049
+ let visited = 0;
5050
+ const visit = (dirPath) => {
5051
+ for (const entry of readEntries(dirPath)) {
5052
+ if (visited++ >= MAX_RULE_SCAN_ENTRIES)
5053
+ return false;
5054
+ if (entry.isDirectory()) {
5055
+ if (!SCAN_IGNORED_DIRS.has(entry.name) && visit(path.join(dirPath, entry.name)))
5056
+ return true;
5057
+ } else if (entry.isFile()) {
5058
+ const extension = path.extname(entry.name).toLowerCase();
5059
+ if (extension === ".cwt")
5060
+ cwtCount++;
5061
+ if (extension === ".cwt" || extension === ".log")
5062
+ count++;
5063
+ if (count >= 6 && cwtCount >= 1)
5064
+ return true;
5065
+ }
5066
+ }
5067
+ return false;
5068
+ };
5069
+ return visit(rootPath);
5070
+ }
5071
+ function vanillaEvidence(rootPath, configuredGamePath) {
5072
+ const matches = (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)().map((profile) => ({ profile, configured: configuredGamePath(profile.id) })).filter((item) => item.configured && isDirectory(path.join(item.configured, "common")) && sameOrInside(rootPath, item.configured)).map((item) => ({ id: item.profile.id, configured: item.configured }));
5073
+ if (matches.length === 0)
5074
+ return {};
5075
+ return {
5076
+ gameId: matches.length === 1 ? matches[0].id : void 0,
5077
+ evidence: `workspace is equal to or inside configured game data path: ${matches.map((item) => item.configured).join(", ")}`
5078
+ };
5079
+ }
5080
+ function markerEvidence(rootPath) {
5081
+ const found = [];
5082
+ for (const profile of (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)()) {
5083
+ for (const marker of WORKSPACE_GAME_MARKERS[profile.id] ?? []) {
5084
+ if (hasRelativeDirectory(rootPath, marker))
5085
+ found.push(`${profile.id}:${marker}`);
5086
+ }
5087
+ }
5088
+ return found;
5089
+ }
5090
+ function scoreWorkspaceForGame(rootPath, descriptorText, profile, configuredPath) {
5091
+ let score = 0;
5092
+ const rootText = normalizeDetectionText(rootPath);
5093
+ const profileTexts = [
5094
+ profile.id,
5095
+ profile.displayName,
5096
+ profile.steamFolderName,
5097
+ profile.exeName,
5098
+ ...profile.alternativeFolderNames,
5099
+ ...WORKSPACE_GAME_TEXT_HINTS[profile.id] ?? []
5100
+ ].map(normalizeDetectionText).filter(Boolean);
5101
+ if (profileTexts.some((hint) => rootText.includes(hint)))
5102
+ score += 70;
5103
+ if (profileTexts.some((hint) => descriptorText.includes(hint)))
5104
+ score += 90;
5105
+ if (configuredPath && sameOrInside(rootPath, configuredPath))
5106
+ score += 80;
5107
+ for (const marker of WORKSPACE_GAME_MARKERS[profile.id] ?? []) {
5108
+ if (hasRelativeDirectory(rootPath, marker))
5109
+ score += 25;
5110
+ }
5111
+ return score;
5112
+ }
5113
+ function inferSupportedGame(rootPath, configuredGamePath) {
5114
+ const descriptorText = readWorkspaceGameDescriptor(rootPath);
5115
+ const scores = (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)().map((profile) => ({
5116
+ id: profile.id,
5117
+ score: scoreWorkspaceForGame(rootPath, descriptorText, profile, configuredGamePath(profile.id))
5118
+ })).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
5119
+ const best = scores[0];
5120
+ const next = scores[1];
5121
+ return best && best.score >= 40 && best.score > (next?.score ?? 0) ? best.id : void 0;
5122
+ }
5123
+ function classifyWorkspaceRoot(rootPath, configuredGamePath, options) {
5124
+ const profiles = (0, workspaceDetectionProfiles_1.getWorkspaceDetectionProfiles)();
5125
+ const workshopAppId = (0, workshopDetection_1.parseWorkshopContentAppId)(rootPath);
5126
+ if (workshopAppId) {
5127
+ const game = profiles.find((profile) => profile.steamAppId === workshopAppId);
5128
+ if (game && workshopAppId !== "0") {
5129
+ return supported("mod", rootPath, [`Steam Workshop App ID ${workshopAppId}`], "strong", game.id);
5130
+ }
5131
+ }
5132
+ const vanilla = vanillaEvidence(rootPath, configuredGamePath);
5133
+ if (vanilla.evidence)
5134
+ return supported("vanilla", rootPath, [vanilla.evidence], "strong", vanilla.gameId);
5135
+ const profileGame = validProjectProfileGame(rootPath);
5136
+ if (profileGame)
5137
+ return supported("mod", rootPath, ["valid .cwtools/project/profile.json"], "strong", profileGame);
5138
+ const descriptor = descriptorEvidence(rootPath);
5139
+ if (descriptor)
5140
+ return supported("mod", rootPath, [descriptor], "strong", inferSupportedGame(rootPath, configuredGamePath));
5141
+ if (options?.allowCwt !== false && isCwtRuleWorkspace(rootPath)) {
5142
+ return supported("cwt-only", rootPath, ["bounded CWT rule cluster (at least six rule/log files and one .cwt)"], "strong");
5143
+ }
5144
+ const markers = markerEvidence(rootPath);
5145
+ if (markers.length > 0)
5146
+ return supported("mod", rootPath, markers, "strong", inferSupportedGame(rootPath, configuredGamePath));
5147
+ const content = contentEvidence(rootPath);
5148
+ if (content.payload && content.directories.length >= 2) {
5149
+ return supported("mod", rootPath, [`content directories: ${content.directories.join(", ")}`, `PDX payload: ${content.payload}`], "composite", inferSupportedGame(rootPath, configuredGamePath));
5150
+ }
5151
+ if (content.payload && content.directories.length === 1 && hasUsableNestedMetadata(rootPath)) {
5152
+ return supported("mod", rootPath, [`.metadata/metadata.json plus ${content.directories[0]}`, `PDX payload: ${content.payload}`], "composite", inferSupportedGame(rootPath, configuredGamePath));
5153
+ }
5154
+ return unsupported(rootPath);
5155
+ }
5156
+ function detectWorkspaceProject(rootPath, configuredGamePath) {
5157
+ const atRoot = classifyWorkspaceRoot(rootPath, configuredGamePath);
5158
+ if (atRoot.kind !== "unsupported")
5159
+ return atRoot;
5160
+ let ancestor = rootPath;
5161
+ for (let depth = 0; depth < MAX_ANCESTORS; depth++) {
5162
+ const parent = path.dirname(ancestor);
5163
+ if (!parent || parent === ancestor)
5164
+ break;
5165
+ ancestor = parent;
5166
+ const match = classifyWorkspaceRoot(ancestor, configuredGamePath, { allowCwt: false });
5167
+ if ((match.kind === "mod" || match.kind === "vanilla") && match.strength === "strong")
5168
+ return match;
5169
+ }
5170
+ const children = readEntries(rootPath).filter((entry) => entry.isDirectory() && entry.name !== "node_modules").slice(0, MAX_CHILDREN).map((entry) => classifyWorkspaceRoot(path.join(rootPath, entry.name), configuredGamePath)).filter((result) => result.kind !== "unsupported");
5171
+ if (children.length === 1)
5172
+ return children[0];
5173
+ if (children.length > 1) {
5174
+ const candidates = children.map((result) => result.matchedAt).sort((a, b) => a.localeCompare(b));
5175
+ return {
5176
+ kind: "ambiguous",
5177
+ evidence: children.flatMap((result) => result.evidence),
5178
+ candidates,
5179
+ strength: "none",
5180
+ reason: `Multiple Paradox/CWT projects found; pass --workspace explicitly: ${candidates.join(", ")}`
5181
+ };
5182
+ }
5183
+ return unsupported(rootPath, `No reliable Paradox/CWT evidence at, above, or directly under '${rootPath}'.`);
5184
+ }
5185
+ function workspaceHasParadoxStructure(rootPath, configuredGamePath) {
5186
+ const result = classifyWorkspaceRoot(rootPath, configuredGamePath);
5187
+ return result.kind === "mod" || result.kind === "vanilla";
5188
+ }
5189
+ function inferGameIdFromWorkspace(rootPath, configuredGamePath) {
5190
+ const result = classifyWorkspaceRoot(rootPath, configuredGamePath);
5191
+ return result.kind === "mod" || result.kind === "vanilla" ? result.gameId : void 0;
5192
+ }
5193
+ }
5194
+ });
5195
+
5196
+ // ../cwtools-shared/dist/host/capabilities.js
5197
+ var require_capabilities = __commonJS({
5198
+ "../cwtools-shared/dist/host/capabilities.js"(exports2) {
5199
+ "use strict";
5200
+ Object.defineProperty(exports2, "__esModule", { value: true });
5201
+ exports2.REQUIRED_BACKEND_COMMANDS = exports2.BACKEND_INCOMPATIBLE_CODE = exports2.HOST_CAPABILITIES_PROTOCOL_VERSION = void 0;
5202
+ exports2.parseHostCapabilities = parseHostCapabilities;
5203
+ exports2.checkRequiredCommands = checkRequiredCommands;
5204
+ exports2.HOST_CAPABILITIES_PROTOCOL_VERSION = 1;
5205
+ exports2.BACKEND_INCOMPATIBLE_CODE = "backend_incompatible";
5206
+ function isRecord(value) {
5207
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5208
+ }
5209
+ function parseHostCapabilities(raw) {
5210
+ if (!isRecord(raw)) {
5211
+ return { ok: false, reason: "legacy", message: "Backend did not answer cwtools.ai.getHostCapabilities." };
5212
+ }
5213
+ if (raw.status === "unavailable" || isRecord(raw.error)) {
5214
+ return {
5215
+ ok: false,
5216
+ reason: "legacy",
5217
+ message: `Backend rejected the capability handshake: ${String((isRecord(raw.error) ? raw.error.message : void 0) ?? "unavailable")}.`
5218
+ };
5219
+ }
5220
+ const protocolVersion = raw.protocolVersion;
5221
+ const serverVersion = raw.serverVersion;
5222
+ const commands = raw.commands;
5223
+ if (typeof protocolVersion !== "number" || !Number.isInteger(protocolVersion)) {
5224
+ return { ok: false, reason: "malformed", message: "Backend handshake is missing an integer protocolVersion." };
5225
+ }
5226
+ if (typeof serverVersion !== "string" || serverVersion.trim().length === 0) {
5227
+ return { ok: false, reason: "malformed", message: "Backend handshake is missing a serverVersion string." };
5228
+ }
5229
+ if (!Array.isArray(commands) || commands.some((command) => typeof command !== "string")) {
5230
+ return { ok: false, reason: "malformed", message: "Backend handshake is missing a string[] commands table." };
5231
+ }
5232
+ if (protocolVersion !== exports2.HOST_CAPABILITIES_PROTOCOL_VERSION) {
5233
+ return {
5234
+ ok: false,
5235
+ reason: "protocol",
5236
+ message: `Backend speaks capability protocol ${protocolVersion}; this client requires ${exports2.HOST_CAPABILITIES_PROTOCOL_VERSION}.`
5237
+ };
5238
+ }
5239
+ if (commands.length === 0) {
5240
+ return { ok: false, reason: "incomplete", message: "Backend handshake reported an empty command table." };
4596
5241
  }
5242
+ return {
5243
+ ok: true,
5244
+ capabilities: { protocolVersion, serverVersion: serverVersion.trim(), commands: [...commands] }
5245
+ };
5246
+ }
5247
+ exports2.REQUIRED_BACKEND_COMMANDS = [
5248
+ // Readiness, diagnostics and manual revalidation.
5249
+ "cwtools.ai.getValidationStatus",
5250
+ "cwtools.ai.getDiagnosticsFresh",
5251
+ "cwtools.ai.getAllDiagnostics",
5252
+ "cwtools.ai.revalidateFiles",
5253
+ // Completion, symbols and navigation.
5254
+ "cwtools.ai.getCompletionContext",
5255
+ "cwtools.ai.getScopeAtPosition",
5256
+ "cwtools.ai.queryDefinition",
5257
+ "cwtools.ai.queryDefinitionByName",
5258
+ "cwtools.ai.getEntityInfo",
5259
+ // Semantic model and project graph.
5260
+ "cwtools.ai.queryTypes",
5261
+ "cwtools.ai.exploreProject",
5262
+ "cwtools.ai.exploreInlineGraph",
5263
+ "cwtools.ai.analyzePdxFlow",
5264
+ "cwtools.ai.compareDefinitionWithVanilla",
5265
+ "cwtools.ai.parseFragment",
5266
+ "cwtools.ai.queryProjectKnowledgeDb",
5267
+ // Localisation.
5268
+ "cwtools.ai.queryLocalisationAudit",
5269
+ // Scripted types and enums.
5270
+ "cwtools.ai.queryScriptedEffects",
5271
+ "cwtools.ai.queryScriptedTriggers",
5272
+ "cwtools.ai.queryEnums",
5273
+ "cwtools.ai.queryStaticModifiers",
5274
+ "cwtools.ai.queryVariables",
5275
+ // Shader surface: all seven commands are individually exposed as tools.
5276
+ "cwtools.ai.shader.symbols",
5277
+ "cwtools.ai.shader.compileUnit",
5278
+ "cwtools.ai.shader.variants",
5279
+ "cwtools.ai.shader.callers",
5280
+ "cwtools.ai.shader.reachability",
5281
+ "cwtools.ai.shader.validate",
5282
+ "cwtools.ai.shader.compareVanilla"
4597
5283
  ];
5284
+ function checkRequiredCommands(capabilities, required = exports2.REQUIRED_BACKEND_COMMANDS) {
5285
+ const present = new Set(capabilities.commands);
5286
+ const missing = required.filter((command) => !present.has(command));
5287
+ if (missing.length > 0) {
5288
+ return {
5289
+ ok: false,
5290
+ reason: "incomplete",
5291
+ message: `Backend is missing required commands: ${missing.join(", ")}.`
5292
+ };
5293
+ }
5294
+ return { ok: true, capabilities };
5295
+ }
4598
5296
  }
4599
5297
  });
4600
5298
 
@@ -4651,7 +5349,30 @@ var require_lsp = __commonJS({
4651
5349
  "../cwtools-shared/dist/host/lsp.js"(exports2) {
4652
5350
  "use strict";
4653
5351
  Object.defineProperty(exports2, "__esModule", { value: true });
5352
+ exports2.isAbortError = isAbortError;
5353
+ exports2.createAbortError = createAbortError;
5354
+ exports2.rethrowIfAborted = rethrowIfAborted;
5355
+ exports2.throwIfAborted = throwIfAborted;
4654
5356
  exports2.createUnavailableLspHost = createUnavailableLspHost;
5357
+ function isAbortError(error) {
5358
+ if (!error || typeof error !== "object")
5359
+ return false;
5360
+ const record = error;
5361
+ return record.name === "AbortError" || record.code === "ABORT_ERR";
5362
+ }
5363
+ function createAbortError(message = "Operation was aborted.") {
5364
+ const error = new Error(message);
5365
+ error.name = "AbortError";
5366
+ return error;
5367
+ }
5368
+ function rethrowIfAborted(error) {
5369
+ if (isAbortError(error))
5370
+ throw error;
5371
+ }
5372
+ function throwIfAborted(signal) {
5373
+ if (signal?.aborted)
5374
+ throw createAbortError(signal.reason instanceof Error ? signal.reason.message : void 0);
5375
+ }
4655
5376
  function createUnavailableLspHost(message = "CWTools LSP is not connected.") {
4656
5377
  return {
4657
5378
  async executeCommand() {
@@ -4731,6 +5452,13 @@ var require_readiness = __commonJS({
4731
5452
  if (readiness.ready) {
4732
5453
  return { ...result, readiness };
4733
5454
  }
5455
+ if (readiness.reason === "lsp_unavailable") {
5456
+ return {
5457
+ ...result,
5458
+ readiness,
5459
+ warnings: [...result.warnings ?? [], "CWTools backend is unavailable; this result carries no semantic model evidence."]
5460
+ };
5461
+ }
4734
5462
  return {
4735
5463
  ...result,
4736
5464
  ok: true,
@@ -4766,7 +5494,7 @@ var require_vanillaCache = __commonJS({
4766
5494
  vic3: "vic3"
4767
5495
  };
4768
5496
  function vanillaCacheFileName(game) {
4769
- const prefix = GAME_CACHE_PREFIX[(game ?? "stellaris").toLowerCase()];
5497
+ const prefix = game ? GAME_CACHE_PREFIX[game.toLowerCase()] : void 0;
4770
5498
  return prefix ? `${prefix}.cwb` : void 0;
4771
5499
  }
4772
5500
  exports2.VANILLA_DEPENDENT_TOOLS = /* @__PURE__ */ new Set([
@@ -7047,7 +7775,7 @@ var require_names = __commonJS({
7047
7775
  function isMcpToolName(value, options) {
7048
7776
  if (exports2.MCP_READONLY_TOOL_NAMES.includes(value))
7049
7777
  return true;
7050
- if (options?.includeWrites && exports2.MCP_WRITE_TOOL_NAMES.includes(value))
7778
+ if (options?.includeWrites !== false && exports2.MCP_WRITE_TOOL_NAMES.includes(value))
7051
7779
  return true;
7052
7780
  return false;
7053
7781
  }
@@ -7191,8 +7919,12 @@ var require_mcpSchema = __commonJS({
7191
7919
  "../cwtools-shared/dist/tools/mcpSchema.js"(exports2) {
7192
7920
  "use strict";
7193
7921
  Object.defineProperty(exports2, "__esModule", { value: true });
7922
+ exports2.listCwtoolsToolSchemas = void 0;
7194
7923
  exports2.getGeneratedMcpTools = getGeneratedMcpTools;
7195
7924
  exports2.listMcpToolSchemas = listMcpToolSchemas;
7925
+ exports2.isMcpToolAvailable = isMcpToolAvailable;
7926
+ exports2.isCwtoolsToolAvailable = isCwtoolsToolAvailable;
7927
+ exports2.getCwtoolsToolSchema = getCwtoolsToolSchema;
7196
7928
  exports2.getMcpToolSchema = getMcpToolSchema;
7197
7929
  exports2.getMcpToolRegistryMetadata = getMcpToolRegistryMetadata;
7198
7930
  var mcpTools_1 = require_mcpTools();
@@ -7201,8 +7933,23 @@ var require_mcpSchema = __commonJS({
7201
7933
  return mcpTools_1.GENERATED_MCP_TOOLS;
7202
7934
  }
7203
7935
  function listMcpToolSchemas(options) {
7204
- const includeWrites = options?.includeWrites === true;
7205
- return mcpTools_1.GENERATED_MCP_TOOLS.filter((entry) => includeWrites || !(0, names_1.isMcpWriteToolName)(entry.tool.name)).map((entry) => ({ ...entry.tool }));
7936
+ const includeWrites = options?.includeWrites !== false;
7937
+ const cwtOnly = options?.cwtOnly === true;
7938
+ return mcpTools_1.GENERATED_MCP_TOOLS.filter((entry) => (includeWrites || !(0, names_1.isMcpWriteToolName)(entry.tool.name)) && (!cwtOnly || entry.registry.mcpSupportsCwtOnly)).map((entry) => ({ ...entry.tool }));
7939
+ }
7940
+ function isMcpToolAvailable(value, options) {
7941
+ if (!(0, names_1.isMcpToolName)(value, options))
7942
+ return false;
7943
+ if (!options?.cwtOnly)
7944
+ return true;
7945
+ return mcpTools_1.GENERATED_MCP_TOOLS.find((entry) => entry.tool.name === value)?.registry.mcpSupportsCwtOnly === true;
7946
+ }
7947
+ exports2.listCwtoolsToolSchemas = listMcpToolSchemas;
7948
+ function isCwtoolsToolAvailable(value, options) {
7949
+ return isMcpToolAvailable(value, options);
7950
+ }
7951
+ function getCwtoolsToolSchema(name) {
7952
+ return getMcpToolSchema(name);
7206
7953
  }
7207
7954
  function getMcpToolSchema(name) {
7208
7955
  return mcpTools_1.GENERATED_MCP_TOOLS.find((entry) => entry.tool.name === name)?.tool;
@@ -7449,6 +8196,17 @@ var require_symbols = __commonJS({
7449
8196
  return (0, schema_1.toolDenied)("invalid_arguments", "go_to_definition requires symbolName or a file position.");
7450
8197
  const commandResult = await host.lsp.executeCommand("cwtools.ai.queryDefinitionByName", [symbolName], { timeoutMs: 1e4 });
7451
8198
  if (!isUnavailable(commandResult)) {
8199
+ const record = commandResult && typeof commandResult === "object" && !Array.isArray(commandResult) ? commandResult : {};
8200
+ if (record.ok === false) {
8201
+ const message = typeof record.error === "string" && record.error.trim() ? record.error : `Symbol '${symbolName}' was not found.`;
8202
+ return {
8203
+ ok: false,
8204
+ status: "error",
8205
+ source: "cwtools-lsp-definition",
8206
+ data: commandResult,
8207
+ error: { code: "definition_not_found", message }
8208
+ };
8209
+ }
7452
8210
  return {
7453
8211
  ok: true,
7454
8212
  status: "ready",
@@ -7516,13 +8274,14 @@ var require_symbols = __commonJS({
7516
8274
  const references = await textSearchReferences(host, identifier, args.file, limit);
7517
8275
  return {
7518
8276
  ok: true,
7519
- status: "ready",
8277
+ status: "partial",
7520
8278
  source: "cwtools-text-references",
8279
+ warnings: ["Fallback text references are lexical evidence, not semantic CWTools reference resolution."],
7521
8280
  data: {
7522
8281
  identifier,
7523
8282
  references,
7524
8283
  total: references.length,
7525
- _warning: "Fallback text references are lexical evidence, not semantic CWTools reference resolution."
8284
+ evidence: "lexical"
7526
8285
  }
7527
8286
  };
7528
8287
  }
@@ -7978,11 +8737,322 @@ var require_pdxBlock = __commonJS({
7978
8737
  }
7979
8738
  });
7980
8739
 
7981
- // ../cwtools-shared/dist/tools/registry.js
7982
- var require_registry = __commonJS({
7983
- "../cwtools-shared/dist/tools/registry.js"(exports2) {
7984
- "use strict";
7985
- Object.defineProperty(exports2, "__esModule", { value: true });
8740
+ // ../cwtools-shared/dist/tools/targetingWeights.js
8741
+ var require_targetingWeights = __commonJS({
8742
+ "../cwtools-shared/dist/tools/targetingWeights.js"(exports2) {
8743
+ "use strict";
8744
+ Object.defineProperty(exports2, "__esModule", { value: true });
8745
+ exports2.VANILLA_TARGETING_DEFINES = void 0;
8746
+ exports2.computeTargetingChain = computeTargetingChain;
8747
+ exports2.executeTargetingWeightQuery = executeTargetingWeightQuery;
8748
+ exports2.parseTargetingChainInput = parseTargetingChainInput;
8749
+ exports2.VANILLA_TARGETING_DEFINES = {
8750
+ sizeSlope: 0.03,
8751
+ sizeMax: 10,
8752
+ trackingMult: 2,
8753
+ evasionWeight: 2,
8754
+ lowHealthThreshold: 0.5,
8755
+ lowHealthWeight: 1.5,
8756
+ distanceWeight: 2e-3,
8757
+ distanceWeightMin: 0.1,
8758
+ unarmedWeight: 5e-3,
8759
+ starbaseWeight: 0.75,
8760
+ avoidMinShipSize: 8,
8761
+ avoidThreshold: 0.7,
8762
+ randomWeight: 3,
8763
+ currentTargetMultiplier: 1.1,
8764
+ recentTargetPenalizer: 0.3
8765
+ };
8766
+ var MAX_DAMAGE_SCALING = 100;
8767
+ function clamp(value, min, max) {
8768
+ return value < min ? min : value > max ? max : value;
8769
+ }
8770
+ function resolveDefines(partial) {
8771
+ const merged = { ...exports2.VANILLA_TARGETING_DEFINES };
8772
+ if (!partial) {
8773
+ return merged;
8774
+ }
8775
+ for (const key of Object.keys(exports2.VANILLA_TARGETING_DEFINES)) {
8776
+ const value = partial[key];
8777
+ if (typeof value === "number" && Number.isFinite(value)) {
8778
+ merged[key] = value;
8779
+ }
8780
+ }
8781
+ return merged;
8782
+ }
8783
+ function computeTargetingChain(input) {
8784
+ const defs = resolveDefines(input.defines);
8785
+ const attacker = input.attacker;
8786
+ const weapon = input.weapon;
8787
+ const target = input.target;
8788
+ const sizeCapped = Math.min(target.sizeMultiplier, defs.sizeMax);
8789
+ const W1 = 1 / (1 + sizeCapped * defs.sizeSlope);
8790
+ const shipTracking = attacker.tracking * defs.trackingMult;
8791
+ const evasionDelta = target.evasion - shipTracking;
8792
+ const vetoCheck = {
8793
+ evasionDeltaPositive: evasionDelta > 0,
8794
+ attackerSizeLargeEnough: attacker.sizeMultiplier >= defs.avoidMinShipSize,
8795
+ deltaAboveThreshold: evasionDelta >= defs.avoidThreshold,
8796
+ fleetHasHittable: input.fleetHasHittable === true
8797
+ };
8798
+ const veto = vetoCheck.evasionDeltaPositive && vetoCheck.attackerSizeLargeEnough && vetoCheck.deltaAboveThreshold && vetoCheck.fleetHasHittable;
8799
+ const evasionFactor = evasionDelta > 0 ? 1 / (1 + evasionDelta * defs.evasionWeight) : 1;
8800
+ const distanceFactor = Math.max(1 - target.distance * defs.distanceWeight, defs.distanceWeightMin);
8801
+ const targetWeight = 1 + (input.rho ?? 0) + (input.targetWeightMultModifier ?? 0);
8802
+ const maxHull = target.maxHull;
8803
+ const hasHealthRatio = typeof maxHull === "number" && Number.isFinite(maxHull) && maxHull > 0;
8804
+ const healthRatio = hasHealthRatio ? clamp(target.hull / maxHull, 0, 1) : null;
8805
+ const lowHealthFactor = healthRatio !== null && healthRatio < defs.lowHealthThreshold ? defs.lowHealthWeight : 1;
8806
+ const unarmedFactor = target.armed ? 1 : defs.unarmedWeight;
8807
+ const starbaseFactor = target.isStarbase === true && target.isCurrentMainTarget !== true ? defs.starbaseWeight : 1;
8808
+ const randomRoll = clamp(input.randomRoll ?? 0, 0, 1);
8809
+ const randomFactor = input.useRandom === true ? 1 + randomRoll * defs.randomWeight : 1;
8810
+ const W2 = veto ? 0 : W1 * evasionFactor;
8811
+ const W3 = veto ? 0 : W2 * distanceFactor;
8812
+ const W4 = veto ? 0 : W3 * targetWeight;
8813
+ const W5 = veto ? 0 : W4 * lowHealthFactor * unarmedFactor * starbaseFactor;
8814
+ const W6 = veto ? 0 : W5 * randomFactor;
8815
+ const shipChain = {
8816
+ veto,
8817
+ vetoCheck,
8818
+ sizeCapped,
8819
+ W1,
8820
+ shipTracking,
8821
+ evasionDelta,
8822
+ evasionFactor,
8823
+ W2,
8824
+ distanceFactor,
8825
+ W3,
8826
+ targetWeight,
8827
+ W4,
8828
+ lowHealthFactor,
8829
+ unarmedFactor,
8830
+ starbaseFactor,
8831
+ W5,
8832
+ randomFactor,
8833
+ W6,
8834
+ weight: W6
8835
+ };
8836
+ const baseDamage = (weapon.minDamage + weapon.maxDamage) / 2;
8837
+ const sizeFactor = weapon.sizeDamageFactor ?? 0;
8838
+ const scaledDamage = sizeFactor > 0 ? baseDamage * (1 + clamp(target.sizeMultiplier, 1, MAX_DAMAGE_SCALING) * sizeFactor) : baseDamage;
8839
+ let remaining = scaledDamage;
8840
+ let Ds = 0;
8841
+ let Da = 0;
8842
+ if (target.shield > 0) {
8843
+ const s = clamp((weapon.shieldPenetration ?? 0) - (target.shieldHardening ?? 0), 0, 1);
8844
+ const Cs = (1 - s) * remaining;
8845
+ remaining -= Math.min(Cs, target.shield);
8846
+ Ds = weapon.shieldDamage * Cs;
8847
+ }
8848
+ if (target.armor > 0) {
8849
+ const a = clamp((weapon.armorPenetration ?? 0) - (target.armorHardening ?? 0), 0, 1);
8850
+ const Ca = (1 - a) * remaining;
8851
+ remaining -= Math.min(Ca, target.armor);
8852
+ Da = weapon.armorDamage * Ca;
8853
+ }
8854
+ const Dh = weapon.hullDamage * remaining;
8855
+ const p = clamp(weapon.accuracy - clamp(target.evasion - weapon.tracking, 0, 1), 0, 1);
8856
+ const sumD = Ds + Da + Dh;
8857
+ const S0 = sumD * p * targetWeight;
8858
+ const killBonus = Dh >= target.hull ? 1.5 : 1;
8859
+ const S1 = S0 * killBonus;
8860
+ const unarmedPenalty = target.armed ? 1 : defs.unarmedWeight;
8861
+ const S2 = S1 * unarmedPenalty;
8862
+ const wk = target.shipSizeId !== void 0 ? weapon.targetWeights?.[target.shipSizeId] ?? 0 : 0;
8863
+ const score = S2 + wk;
8864
+ const currentTargetMultiplier = target.isCurrentMainTarget === true && input.targetFocus !== true ? defs.currentTargetMultiplier : 1;
8865
+ const recentTargetPenalizer = target.isRecentNonLatest === true ? defs.recentTargetPenalizer : 1;
8866
+ const weaponLayer = {
8867
+ p,
8868
+ baseDamage,
8869
+ damageSplit: { Ds, Da, Dh },
8870
+ sumD,
8871
+ S0,
8872
+ killBonus,
8873
+ S1,
8874
+ unarmedPenalty,
8875
+ S2,
8876
+ wk,
8877
+ score,
8878
+ currentTargetMultiplier,
8879
+ recentTargetPenalizer,
8880
+ final: score * currentTargetMultiplier * recentTargetPenalizer
8881
+ };
8882
+ const notes = buildNotes(input, defs, shipChain, weaponLayer, healthRatio !== null);
8883
+ return { veto, shipChain, weapon: weaponLayer, defines: defs, notes };
8884
+ }
8885
+ function buildNotes(input, defs, shipChain, weaponLayer, hasHealthRatio) {
8886
+ const notes = [];
8887
+ notes.push("\u4E24\u5C42\u4E92\u4E0D\u76F8\u4E58\uFF1A\u8230\u8239\u5C42\u4E0E\u6B66\u5668\u5C42\u5404\u81EA argmax\uFF1B\u6B66\u5668\u6A21\u677F\u5199 use_ship_main_target = yes \u65F6\u6B66\u5668\u76F4\u63A5\u6CBF\u7528\u8230\u8239\u4E3B\u76EE\u6807\uFF0C\u6B66\u5668\u5C42\u5206\u6570\u4E0D\u53C2\u4E0E\uFF08\u8BEF\u533A 8\uFF09\u3002");
8888
+ notes.push("\u7D22\u654C\u4E0D\u662F\u6BCF tick \u91CD\u7B97\uFF1A\u5DF2\u6709\u6709\u6548\u4E3B\u76EE\u6807\u65F6\u53EA\u5728 (TotalTicks + shipID) mod fp == 0 \u7684 tick \u91CD\u7B97\uFF0Cfp = 50\uFF08targetFocus = 1\uFF09\u6216 10\u3002");
8889
+ if (shipChain.veto) {
8890
+ notes.push("\u89E6\u53D1\u6574\u76EE\u6807\u5426\u51B3\uFF1A\u76F4\u63A5 return 0\uFF0C\u8BE5\u5019\u9009\u4ECE\u5019\u9009\u96C6\u4E2D\u5254\u9664\uFF0C\u4E0D\u53C2\u4E0E argmax\uFF08\u8BEF\u533A 6\uFF09\u3002\u5224\u636E\u4E3A \u0394>0 \u4E14 \u03C3att \u2265 \u03C3avoidmin \u4E14 \u0394 \u2265 Tavoid \u4E14\u76EE\u6807\u8230\u961F\u5B58\u5728\u53EF\u547D\u4E2D\u76EE\u6807\u3002");
8891
+ }
8892
+ if (shipChain.evasionDelta <= 0) {
8893
+ notes.push("\u0394 \u2264 0\uFF08\u8FFD\u8E2A\u76D6\u8FC7\u95EA\u907F\uFF09\uFF0C\u8230\u8239\u5C42\u4E0D\u65BD\u52A0\u95EA\u907F\u60E9\u7F5A\u3002");
8894
+ }
8895
+ if (shipChain.distanceFactor === defs.distanceWeightMin) {
8896
+ notes.push(`\u8DDD\u79BB\u56E0\u5B50\u5DF2\u89E6\u4E0B\u9650 ${defs.distanceWeightMin}\uFF08d \u2265 ${(1 - defs.distanceWeightMin) / defs.distanceWeight}\uFF09\uFF0C\u66F4\u8FDC\u4E0D\u518D\u8870\u51CF\u3002`);
8897
+ }
8898
+ if (input.randomRoll === void 0 && input.useRandom !== true) {
8899
+ notes.push(`\u672C\u6B21\u672A\u542F\u7528\u968F\u673A\u6270\u52A8\uFF08useRandom \u9ED8\u8BA4 false\uFF09\u3002\u5F15\u64CE\u9ED8\u8BA4\u5F00\u542F\uFF0C\u672B\u9879\u4E58\u6570 \u2208 [1, 1+\u03BAr) = [1, ${1 + defs.randomWeight})\uFF0C\u662F\u7D22\u654C\u4E0D\u7A33\u5B9A\u7684\u4E3B\u56E0\u4E4B\u4E00\uFF08\u8BEF\u533A 10\uFF09\u3002`);
8900
+ }
8901
+ if (!hasHealthRatio) {
8902
+ notes.push("\u672A\u63D0\u4F9B target.maxHull\uFF0C\u8230\u8239\u5C42\u4E0D\u505A\u6B8B\u8840\u5224\u5B9A\uFF08h < \u03B8h \u6536\u4EBA\u5934\u52A0\u6210\u672A\u751F\u6548\uFF09\u3002");
8903
+ }
8904
+ if (weaponLayer.damageSplit.Ds > 0 || weaponLayer.damageSplit.Da > 0) {
8905
+ notes.push("\u76EE\u6807\u5E26\u76FE/\u7532\uFF1A\u5C42\u5206\u91CF\u4E0D\u88AB\u8BE5\u5C42\u5B58\u91CF\u5939\u4F4F\uFF0C\u53EA\u6709\u4ECE\u5269\u4F59\u4F24\u5BB3\u91CC\u6263\u51CF\u7684\u91CF\u624D\u88AB min \u5939\u4F4F\uFF0C\u6240\u4EE5 \u03A3D \u53CD\u800C\u66F4\u5927\u3002\u6709\u6548\u53CD\u5236\u53EA\u6709\u9AD8\u95EA\u907F\uFF08\u538B\u4F4E p\uFF09\uFF08\u8BEF\u533A 1\uFF09\u3002");
8906
+ }
8907
+ if (weaponLayer.killBonus > 1) {
8908
+ notes.push("\u65A9\u6740\u52A0\u6210\u89E6\u53D1\uFF1A\u5224\u636E\u662F\u8239\u4F53\u5206\u91CF Dh \u2265 \u76EE\u6807\u5F53\u524D\u8239\u4F53\uFF0C\u4E0D\u662F\u603B\u4F24\uFF08\u8BEF\u533A 7\uFF09\u3002");
8909
+ }
8910
+ if (weaponLayer.wk > 0) {
8911
+ notes.push("\u547D\u4E2D weapon.target_weights\uFF1Awk \u662F**\u52A0\u6CD5\u9879**\u800C\u975E\u500D\u7387\uFF0C\u53EF\u4EE5\u76D6\u8FC7\u6574\u6761\u4E58\u6CD5\u94FE\uFF0C\u7528\u6CD5\u4E0E\u76F4\u89C9\u76F8\u53CD\uFF08\u8BEF\u533A 4\uFF09\u3002");
8912
+ }
8913
+ if (input.rho !== void 0 && input.rho > 0) {
8914
+ notes.push("\u03C1 \u662F\u5F00\u6218\u77AC\u95F4\u6BCF\u8258\u8239\u5404\u63B7\u4E00\u6B21\u3001\u6574\u573A\u4E0D\u53D8\u7684\u968F\u673A\u91CF\uFF0C\u6240\u4EE5\u4E24\u6761\u8BBE\u8BA1\u5B8C\u5168\u76F8\u540C\u7684\u8239\u6BCF\u573A\u6218\u6597\u7684 \u0175tgt \u4E5F\u4E0D\u540C\uFF08\u8BEF\u533A 5\uFF09\u3002");
8915
+ }
8916
+ notes.push("ai_weight \u662F AI \u5EFA\u9020/\u51B3\u7B56\u6743\u91CD\uFF0C\u4E0E\u6218\u6597\u7D22\u654C\u65E0\u5173\uFF08\u8BEF\u533A 2\uFF09\u3002");
8917
+ return notes;
8918
+ }
8919
+ function executeTargetingWeightQuery(args) {
8920
+ let input;
8921
+ try {
8922
+ input = parseTargetingChainInput(args);
8923
+ } catch (error) {
8924
+ return {
8925
+ error: `query_targeting_weight: ${error instanceof Error ? error.message : String(error)}`,
8926
+ hint: "Pass numeric attacker/weapon/target fields; every field must be a finite number."
8927
+ };
8928
+ }
8929
+ return computeTargetingChain(input);
8930
+ }
8931
+ function isRecord(value) {
8932
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8933
+ }
8934
+ function requireNumber(source, key, path) {
8935
+ const value = source[key];
8936
+ if (typeof value !== "number" || !Number.isFinite(value)) {
8937
+ throw new Error(`${path}.${key} must be a finite number.`);
8938
+ }
8939
+ return value;
8940
+ }
8941
+ function optionalNumber(source, key, path) {
8942
+ const value = source[key];
8943
+ if (value === void 0 || value === null) {
8944
+ return void 0;
8945
+ }
8946
+ if (typeof value !== "number" || !Number.isFinite(value)) {
8947
+ throw new Error(`${path}.${key} must be a finite number when provided.`);
8948
+ }
8949
+ return value;
8950
+ }
8951
+ function requireBoolean(source, key, path) {
8952
+ const value = source[key];
8953
+ if (typeof value !== "boolean") {
8954
+ throw new Error(`${path}.${key} must be a boolean.`);
8955
+ }
8956
+ return value;
8957
+ }
8958
+ function optionalBoolean(source, key, path) {
8959
+ const value = source[key];
8960
+ if (value === void 0 || value === null) {
8961
+ return void 0;
8962
+ }
8963
+ if (typeof value !== "boolean") {
8964
+ throw new Error(`${path}.${key} must be a boolean when provided.`);
8965
+ }
8966
+ return value;
8967
+ }
8968
+ function optionalNumberRecord(source, key, path) {
8969
+ const value = source[key];
8970
+ if (value === void 0 || value === null) {
8971
+ return void 0;
8972
+ }
8973
+ if (!isRecord(value)) {
8974
+ throw new Error(`${path}.${key} must be an object mapping ship_size id to number.`);
8975
+ }
8976
+ const out = {};
8977
+ for (const [entryKey, entryValue] of Object.entries(value)) {
8978
+ if (typeof entryValue !== "number" || !Number.isFinite(entryValue)) {
8979
+ throw new Error(`${path}.${key}.${entryKey} must be a finite number.`);
8980
+ }
8981
+ out[entryKey] = entryValue;
8982
+ }
8983
+ return out;
8984
+ }
8985
+ function parseTargetingChainInput(args) {
8986
+ if (!isRecord(args)) {
8987
+ throw new Error("arguments must be an object.");
8988
+ }
8989
+ const attackerRaw = args.attacker;
8990
+ const weaponRaw = args.weapon;
8991
+ const targetRaw = args.target;
8992
+ if (!isRecord(attackerRaw) || !isRecord(weaponRaw) || !isRecord(targetRaw)) {
8993
+ throw new Error("attacker, weapon and target must all be objects.");
8994
+ }
8995
+ const definesRaw = args.defines;
8996
+ let defines;
8997
+ if (definesRaw !== void 0 && definesRaw !== null) {
8998
+ if (!isRecord(definesRaw)) {
8999
+ throw new Error("defines must be an object when provided.");
9000
+ }
9001
+ defines = {};
9002
+ for (const key of Object.keys(exports2.VANILLA_TARGETING_DEFINES)) {
9003
+ const value = optionalNumber(definesRaw, key, "defines");
9004
+ if (value !== void 0) {
9005
+ defines[key] = value;
9006
+ }
9007
+ }
9008
+ }
9009
+ const shipSizeIdRaw = targetRaw.shipSizeId;
9010
+ if (shipSizeIdRaw !== void 0 && shipSizeIdRaw !== null && typeof shipSizeIdRaw !== "string") {
9011
+ throw new Error("target.shipSizeId must be a string when provided.");
9012
+ }
9013
+ return {
9014
+ attacker: {
9015
+ tracking: requireNumber(attackerRaw, "tracking", "attacker"),
9016
+ sizeMultiplier: requireNumber(attackerRaw, "sizeMultiplier", "attacker")
9017
+ },
9018
+ weapon: {
9019
+ minDamage: requireNumber(weaponRaw, "minDamage", "weapon"),
9020
+ maxDamage: requireNumber(weaponRaw, "maxDamage", "weapon"),
9021
+ accuracy: requireNumber(weaponRaw, "accuracy", "weapon"),
9022
+ tracking: requireNumber(weaponRaw, "tracking", "weapon"),
9023
+ shieldDamage: requireNumber(weaponRaw, "shieldDamage", "weapon"),
9024
+ armorDamage: requireNumber(weaponRaw, "armorDamage", "weapon"),
9025
+ hullDamage: requireNumber(weaponRaw, "hullDamage", "weapon"),
9026
+ shieldPenetration: optionalNumber(weaponRaw, "shieldPenetration", "weapon"),
9027
+ armorPenetration: optionalNumber(weaponRaw, "armorPenetration", "weapon"),
9028
+ sizeDamageFactor: optionalNumber(weaponRaw, "sizeDamageFactor", "weapon"),
9029
+ targetWeights: optionalNumberRecord(weaponRaw, "targetWeights", "weapon")
9030
+ },
9031
+ target: {
9032
+ shipSizeId: shipSizeIdRaw === null ? void 0 : shipSizeIdRaw,
9033
+ sizeMultiplier: requireNumber(targetRaw, "sizeMultiplier", "target"),
9034
+ evasion: requireNumber(targetRaw, "evasion", "target"),
9035
+ distance: requireNumber(targetRaw, "distance", "target"),
9036
+ hull: requireNumber(targetRaw, "hull", "target"),
9037
+ maxHull: optionalNumber(targetRaw, "maxHull", "target"),
9038
+ shield: requireNumber(targetRaw, "shield", "target"),
9039
+ armor: requireNumber(targetRaw, "armor", "target"),
9040
+ shieldHardening: optionalNumber(targetRaw, "shieldHardening", "target"),
9041
+ armorHardening: optionalNumber(targetRaw, "armorHardening", "target"),
9042
+ armed: requireBoolean(targetRaw, "armed", "target"),
9043
+ isStarbase: optionalBoolean(targetRaw, "isStarbase", "target"),
9044
+ isCurrentMainTarget: optionalBoolean(targetRaw, "isCurrentMainTarget", "target"),
9045
+ isRecentNonLatest: optionalBoolean(targetRaw, "isRecentNonLatest", "target")
9046
+ },
9047
+ defines,
9048
+ rho: optionalNumber(args, "rho", "root"),
9049
+ targetWeightMultModifier: optionalNumber(args, "targetWeightMultModifier", "root"),
9050
+ randomRoll: optionalNumber(args, "randomRoll", "root"),
9051
+ useRandom: optionalBoolean(args, "useRandom", "root"),
9052
+ fleetHasHittable: optionalBoolean(args, "fleetHasHittable", "root"),
9053
+ targetFocus: optionalBoolean(args, "targetFocus", "root")
9054
+ };
9055
+ }
7986
9056
  }
7987
9057
  });
7988
9058
 
@@ -8030,36 +9100,65 @@ var require_toolHandlers = __commonJS({
8030
9100
  Object.defineProperty(exports2, "__esModule", { value: true });
8031
9101
  exports2.defaultSharedToolDispatcher = void 0;
8032
9102
  var path = __importStar(require("path"));
9103
+ var lsp_1 = require_lsp();
8033
9104
  var diagnosticRouting_1 = require_diagnosticRouting();
8034
9105
  var rules_1 = require_rules();
8035
9106
  var profile_1 = require_profile();
8036
9107
  var knowledge_1 = require_knowledge();
8037
9108
  var localisation_1 = require_localisation();
8038
9109
  var pdxBlock_1 = require_pdxBlock();
9110
+ var targetingWeights_1 = require_targetingWeights();
8039
9111
  var schema_1 = require_schema();
8040
9112
  var symbols_1 = require_symbols();
9113
+ function invalidArguments(message) {
9114
+ return {
9115
+ ok: false,
9116
+ status: "error",
9117
+ source: "cwtools-shared",
9118
+ error: { code: "invalid_arguments", message }
9119
+ };
9120
+ }
9121
+ function errorMessageOf(record) {
9122
+ const error = record.error;
9123
+ if (typeof error === "string" && error.trim())
9124
+ return error;
9125
+ const nested = asRecord(error);
9126
+ if (typeof nested.message === "string" && nested.message.trim())
9127
+ return nested.message;
9128
+ if (typeof record.message === "string" && record.message.trim())
9129
+ return record.message;
9130
+ return "CWTools LSP command reported a failure.";
9131
+ }
8041
9132
  function asRecord(value) {
8042
9133
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
8043
9134
  }
8044
- async function executeLspTool(host, command, args, unavailableNextStep) {
8045
- const result = await host.lsp.executeCommand(command, args);
9135
+ async function executeLspTool(host, command, args, unavailableNextStep, signal) {
9136
+ (0, lsp_1.throwIfAborted)(signal);
9137
+ const result = await host.lsp.executeCommand(command, args, signal ? { signal } : void 0);
8046
9138
  const record = asRecord(result);
8047
9139
  const errorRecord = asRecord(record.error);
8048
9140
  const unavailable = record.status === "unavailable" || errorRecord.code === "lsp_unavailable";
9141
+ const failed = !unavailable && record.ok === false;
8049
9142
  return {
8050
- ok: !unavailable,
8051
- status: unavailable ? "unavailable" : "ready",
9143
+ ok: !unavailable && !failed,
9144
+ status: unavailable ? "unavailable" : failed ? "error" : "ready",
8052
9145
  source: "cwtools-lsp",
8053
9146
  data: result,
8054
9147
  error: unavailable ? {
8055
9148
  code: String(errorRecord.code ?? "lsp_unavailable"),
8056
9149
  message: String(errorRecord.message ?? "LSP command is unavailable.")
9150
+ } : failed ? {
9151
+ code: String(errorRecord.code ?? "lsp_command_failed"),
9152
+ message: errorMessageOf(record)
8057
9153
  } : void 0,
8058
9154
  nextSteps: unavailable ? [unavailableNextStep] : void 0
8059
9155
  };
8060
9156
  }
8061
- var defaultSharedToolDispatcher = async (host, name, rawArgs) => {
9157
+ var defaultSharedToolDispatcher = async (host, name, rawArgs, context) => {
8062
9158
  const args = asRecord(rawArgs);
9159
+ const signal = context?.signal;
9160
+ const lspTool = (command, args2, unavailableNextStep) => executeLspTool(host, command, args2, unavailableNextStep, signal);
9161
+ (0, lsp_1.throwIfAborted)(signal);
8063
9162
  switch (name) {
8064
9163
  case "query_project_profile":
8065
9164
  return (0, profile_1.queryProjectProfileWithHost)(host, args);
@@ -8080,8 +9179,14 @@ var require_toolHandlers = __commonJS({
8080
9179
  data
8081
9180
  };
8082
9181
  }
8083
- case "explore_pdx_project":
8084
- return executeLspTool(host, "cwtools.ai.exploreProject", [
9182
+ case "explore_pdx_project": {
9183
+ if (args.exact !== void 0 && typeof args.exact !== "boolean") {
9184
+ return invalidArguments("exact must be a boolean; pass the identifier in query.");
9185
+ }
9186
+ if (args.exact === true && (typeof args.query !== "string" || args.query.trim() === "")) {
9187
+ return invalidArguments("exact requires a non-empty query; omit exact to browse by typeName or file.");
9188
+ }
9189
+ return lspTool("cwtools.ai.exploreProject", [
8085
9190
  typeof args.query === "string" ? args.query : "",
8086
9191
  typeof args.file === "string" && args.file ? toFileUri(args.file, host.workspaceRoot) : "",
8087
9192
  typeof args.typeName === "string" ? args.typeName : "",
@@ -8091,6 +9196,7 @@ var require_toolHandlers = __commonJS({
8091
9196
  args.maxEdges ?? 80,
8092
9197
  args.includeMetadata !== false
8093
9198
  ], "Start the CWTools LSP process and wait for the game model to load before exploring the semantic graph.");
9199
+ }
8094
9200
  case "analyze_pdx_flow": {
8095
9201
  const file = typeof args.file === "string" ? args.file.trim() : "";
8096
9202
  const definitionId = typeof args.definitionId === "string" ? args.definitionId.trim() : "";
@@ -8105,7 +9211,7 @@ var require_toolHandlers = __commonJS({
8105
9211
  }
8106
9212
  };
8107
9213
  }
8108
- return executeLspTool(host, "cwtools.ai.analyzePdxFlow", [{
9214
+ return lspTool("cwtools.ai.analyzePdxFlow", [{
8109
9215
  ...file ? { file } : {},
8110
9216
  ...definitionId ? { definitionId } : {},
8111
9217
  ...typeof args.entityType === "string" && args.entityType.trim() ? { entityType: args.entityType.trim() } : {},
@@ -8124,7 +9230,7 @@ var require_toolHandlers = __commonJS({
8124
9230
  }
8125
9231
  };
8126
9232
  }
8127
- return executeLspTool(host, "cwtools.ai.compareDefinitionWithVanilla", [args.entityType.trim(), args.symbolId.trim()], "Start the CWTools LSP process and wait for the game model to load before comparing the definition with vanilla.");
9233
+ return lspTool("cwtools.ai.compareDefinitionWithVanilla", [args.entityType.trim(), args.symbolId.trim()], "Start the CWTools LSP process and wait for the game model to load before comparing the definition with vanilla.");
8128
9234
  }
8129
9235
  case "query_inline_instantiation": {
8130
9236
  const template = typeof args.template === "string" ? args.template.trim() : "";
@@ -8140,13 +9246,24 @@ var require_toolHandlers = __commonJS({
8140
9246
  }
8141
9247
  };
8142
9248
  }
8143
- return executeLspTool(host, "cwtools.ai.exploreInlineGraph", [{
9249
+ return lspTool("cwtools.ai.exploreInlineGraph", [{
8144
9250
  ...template ? { template } : {},
8145
9251
  ...file ? { file } : {},
8146
9252
  ...Number.isInteger(args.line) ? { line: Number(args.line) } : {},
8147
9253
  limit: Math.max(1, Math.min(Number(args.limit ?? 50) || 50, 200))
8148
9254
  }], "Start the CWTools LSP process and wait for the game model to load before resolving the inline template instantiation.");
8149
9255
  }
9256
+ case "query_targeting_weight": {
9257
+ const data = (0, targetingWeights_1.executeTargetingWeightQuery)(args);
9258
+ const failure = typeof data.error === "string" ? data.error : void 0;
9259
+ return {
9260
+ ok: failure === void 0,
9261
+ status: failure === void 0 ? "ready" : "error",
9262
+ source: "cwtools-shared",
9263
+ data,
9264
+ error: failure === void 0 ? void 0 : { code: "invalid_arguments", message: failure }
9265
+ };
9266
+ }
8150
9267
  case "query_localisation_index": {
8151
9268
  if (!host.indexing) {
8152
9269
  return (0, schema_1.toolUnavailable)(name, "Localisation index is not available in this host.", [
@@ -8154,7 +9271,7 @@ var require_toolHandlers = __commonJS({
8154
9271
  ]);
8155
9272
  }
8156
9273
  const data = await host.indexing.queryLocalisation(args);
8157
- const semanticAudit = args.auditMode === true ? await executeLspTool(host, "cwtools.ai.queryLocalisationAudit", [{
9274
+ const semanticAudit = args.auditMode === true ? await lspTool("cwtools.ai.queryLocalisationAudit", [{
8158
9275
  ...typeof args.key === "string" ? { key: args.key } : {},
8159
9276
  prefix: args.prefix === true,
8160
9277
  contains: args.contains === true,
@@ -8169,13 +9286,19 @@ var require_toolHandlers = __commonJS({
8169
9286
  };
8170
9287
  }
8171
9288
  case "get_diagnostics": {
8172
- const diagnostics = await host.diagnostics.getDiagnostics(args);
9289
+ const diagnostics = await host.diagnostics.getDiagnostics(args, signal ? { signal } : void 0);
9290
+ const suppressed = diagnostics.suppressedCount ?? 0;
8173
9291
  return {
8174
9292
  ok: diagnostics.ok,
8175
9293
  status: diagnostics.status === "unavailable" ? "unavailable" : diagnostics.status === "stale" ? "stale" : diagnostics.status === "pending" ? "loading" : "ready",
8176
9294
  source: "cwtools-diagnostics",
8177
9295
  data: diagnostics,
8178
- error: diagnostics.error
9296
+ error: diagnostics.error,
9297
+ // An empty page is not an empty project: say so when the workspace ignore
9298
+ // list removed entries, and point at the missing backend when it answered
9299
+ // "unavailable" instead of leaving a bare error behind.
9300
+ warnings: suppressed > 0 ? [`${suppressed} diagnostic(s) on this page were hidden by the workspace ignore list (stellarisLanguageServices.ai.ignoredDiagnostics); they still count in totalCount.`] : void 0,
9301
+ nextSteps: diagnostics.ok ? void 0 : ["Check that the CWTools backend is running (extension active, or a standalone server), then retry get_diagnostics."]
8179
9302
  };
8180
9303
  }
8181
9304
  case "analyze_diagnostic_error":
@@ -8225,9 +9348,9 @@ var require_toolHandlers = __commonJS({
8225
9348
  limit: typeof args.limit === "number" ? args.limit : void 0
8226
9349
  });
8227
9350
  case "query_scope":
8228
- return executeLspTool(host, "cwtools.ai.getScopeAtPosition", [toFileUri(String(args.file ?? ""), host.workspaceRoot), args.line, args.column], "Start the CWTools LSP process or connect this host to an existing language server.");
9351
+ return lspTool("cwtools.ai.getScopeAtPosition", [toFileUri(String(args.file ?? ""), host.workspaceRoot), args.line, args.column], "Start the CWTools LSP process or connect this host to an existing language server.");
8229
9352
  case "query_types":
8230
- return executeLspTool(host, "cwtools.ai.queryTypes", [args.typeName, args.filter ?? "", args.limit ?? 30, args.vanilla === true], "Start the CWTools LSP process or connect this host to an existing language server.");
9353
+ return lspTool("cwtools.ai.queryTypes", [args.typeName, args.filter ?? "", args.limit ?? 30, args.vanilla === true], "Start the CWTools LSP process or connect this host to an existing language server.");
8231
9354
  case "query_rules":
8232
9355
  return (0, rules_1.queryRulesWithHost)(host, {
8233
9356
  category: String(args.category ?? "trigger"),
@@ -8256,19 +9379,19 @@ var require_toolHandlers = __commonJS({
8256
9379
  scope: String(args.scope ?? "")
8257
9380
  });
8258
9381
  case "parse_pdx_fragment":
8259
- return executeLspTool(host, "cwtools.ai.parseFragment", [String(args.code ?? "")], "Start the CWTools LSP process or connect this host to an existing language server.");
9382
+ return lspTool("cwtools.ai.parseFragment", [String(args.code ?? "")], "Start the CWTools LSP process or connect this host to an existing language server.");
8260
9383
  case "query_scripted_effects":
8261
- return executeLspTool(host, "cwtools.ai.queryScriptedEffects", [args.filter ?? "", args.limit ?? 50], "Start the CWTools LSP process or connect this host to an existing language server.");
9384
+ return lspTool("cwtools.ai.queryScriptedEffects", [args.filter ?? "", args.limit ?? 50], "Start the CWTools LSP process or connect this host to an existing language server.");
8262
9385
  case "query_scripted_triggers":
8263
- return executeLspTool(host, "cwtools.ai.queryScriptedTriggers", [args.filter ?? "", args.limit ?? 50], "Start the CWTools LSP process or connect this host to an existing language server.");
9386
+ return lspTool("cwtools.ai.queryScriptedTriggers", [args.filter ?? "", args.limit ?? 50], "Start the CWTools LSP process or connect this host to an existing language server.");
8264
9387
  case "query_enums":
8265
- return executeLspTool(host, "cwtools.ai.queryEnums", [args.enumName ?? "", args.limit ?? 500], "Start the CWTools LSP process or connect this host to an existing language server.");
9388
+ return lspTool("cwtools.ai.queryEnums", [args.enumName ?? "", args.limit ?? 500], "Start the CWTools LSP process or connect this host to an existing language server.");
8266
9389
  case "query_static_modifiers":
8267
- return executeLspTool(host, "cwtools.ai.queryStaticModifiers", [args.filter ?? "", args.limit ?? 300], "Start the CWTools LSP process or connect this host to an existing language server.");
9390
+ return lspTool("cwtools.ai.queryStaticModifiers", [args.filter ?? "", args.limit ?? 300], "Start the CWTools LSP process or connect this host to an existing language server.");
8268
9391
  case "query_variables":
8269
- return executeLspTool(host, "cwtools.ai.queryVariables", [args.filter ?? ""], "Start the CWTools LSP process or connect this host to an existing language server.");
9392
+ return lspTool("cwtools.ai.queryVariables", [args.filter ?? ""], "Start the CWTools LSP process or connect this host to an existing language server.");
8270
9393
  case "get_entity_info":
8271
- return executeLspTool(host, "cwtools.ai.getEntityInfo", [toFileUri(String(args.file ?? ""), host.workspaceRoot)], "Start the CWTools LSP process or connect this host to an existing language server.");
9394
+ return lspTool("cwtools.ai.getEntityInfo", [toFileUri(String(args.file ?? ""), host.workspaceRoot)], "Start the CWTools LSP process or connect this host to an existing language server.");
8272
9395
  case "get_pdx_block":
8273
9396
  return (0, pdxBlock_1.getPdxBlockWithHost)(host, {
8274
9397
  file: String(args.file ?? ""),
@@ -8277,31 +9400,31 @@ var require_toolHandlers = __commonJS({
8277
9400
  // Shader knowledge tools: each LSP command takes a single JSON record
8278
9401
  // argument and returns { ok, ... } / { ok: false, status: 'error', ... }.
8279
9402
  case "query_shader_symbol":
8280
- return executeLspTool(host, "cwtools.ai.shader.symbols", [shaderRecord({
9403
+ return lspTool("cwtools.ai.shader.symbols", [shaderRecord({
8281
9404
  filter: typeof args.filter === "string" ? args.filter : void 0,
8282
9405
  kind: typeof args.kind === "string" ? args.kind : void 0,
8283
9406
  limit: typeof args.limit === "number" ? args.limit : void 0,
8284
9407
  cursor: typeof args.cursor === "number" ? args.cursor : void 0
8285
9408
  })], "Start the CWTools LSP process and wait for the shader model to load before querying shader symbols.");
8286
9409
  case "query_shader_compile_unit":
8287
- return executeLspTool(host, "cwtools.ai.shader.compileUnit", [{ uri: toFileUri(String(args.file ?? ""), host.workspaceRoot) }], "Start the CWTools LSP process and wait for the shader model to load before resolving compile units.");
9410
+ return lspTool("cwtools.ai.shader.compileUnit", [{ uri: toFileUri(String(args.file ?? ""), host.workspaceRoot) }], "Start the CWTools LSP process and wait for the shader model to load before resolving compile units.");
8288
9411
  case "query_shader_platform_variants":
8289
- return executeLspTool(host, "cwtools.ai.shader.variants", [{ uri: toFileUri(String(args.file ?? ""), host.workspaceRoot) }], "Start the CWTools LSP process and wait for the shader model to load before comparing shader platform variants.");
9412
+ return lspTool("cwtools.ai.shader.variants", [{ uri: toFileUri(String(args.file ?? ""), host.workspaceRoot) }], "Start the CWTools LSP process and wait for the shader model to load before comparing shader platform variants.");
8290
9413
  case "query_shader_callers":
8291
- return executeLspTool(host, "cwtools.ai.shader.callers", [shaderRecord({
9414
+ return lspTool("cwtools.ai.shader.callers", [shaderRecord({
8292
9415
  effectName: String(args.effectName ?? ""),
8293
9416
  limit: typeof args.limit === "number" ? args.limit : void 0
8294
9417
  })], "Start the CWTools LSP process and wait for the shader model to load before querying Effect callers.");
8295
9418
  case "explain_shader_reachability":
8296
- return executeLspTool(host, "cwtools.ai.shader.reachability", [typeof args.effectName === "string" && args.effectName ? { effectName: args.effectName } : shaderRecord({
9419
+ return lspTool("cwtools.ai.shader.reachability", [typeof args.effectName === "string" && args.effectName ? { effectName: args.effectName } : shaderRecord({
8297
9420
  uri: toFileUri(String(args.file ?? ""), host.workspaceRoot),
8298
9421
  limit: typeof args.limit === "number" ? args.limit : void 0,
8299
9422
  cursor: typeof args.cursor === "number" ? args.cursor : void 0
8300
9423
  })], "Start the CWTools LSP process and wait for the shader model to load before explaining Effect reachability.");
8301
9424
  case "validate_shader":
8302
- return executeLspTool(host, "cwtools.ai.shader.validate", [{ uri: toFileUri(String(args.file ?? ""), host.workspaceRoot) }], "Start the CWTools LSP process and wait for the shader model to load before validating shader files.");
9425
+ return lspTool("cwtools.ai.shader.validate", [{ uri: toFileUri(String(args.file ?? ""), host.workspaceRoot) }], "Start the CWTools LSP process and wait for the shader model to load before validating shader files.");
8303
9426
  case "compare_shader_with_vanilla":
8304
- return executeLspTool(host, "cwtools.ai.shader.compareVanilla", [typeof args.effectName === "string" && args.effectName ? { effectName: args.effectName } : { uri: toFileUri(String(args.file ?? ""), host.workspaceRoot) }], "Start the CWTools LSP process and wait for the shader model to load before comparing with vanilla.");
9427
+ return lspTool("cwtools.ai.shader.compareVanilla", [typeof args.effectName === "string" && args.effectName ? { effectName: args.effectName } : { uri: toFileUri(String(args.file ?? ""), host.workspaceRoot) }], "Start the CWTools LSP process and wait for the shader model to load before comparing with vanilla.");
8305
9428
  case "get_ide_context":
8306
9429
  case "open_in_visual_editor":
8307
9430
  return (0, schema_1.toolUnavailable)(name, `${name} requires the active VS Code extension bridge (default mode without --standalone).`, ["Open the project in VS Code / Cursor / Antigravity with the CWTools extension active and connect via bridge mode."]);
@@ -8340,6 +9463,79 @@ var require_toolHandlers = __commonJS({
8340
9463
  }
8341
9464
  });
8342
9465
 
9466
+ // ../cwtools-shared/dist/tools/callHandler.js
9467
+ var require_callHandler = __commonJS({
9468
+ "../cwtools-shared/dist/tools/callHandler.js"(exports2) {
9469
+ "use strict";
9470
+ Object.defineProperty(exports2, "__esModule", { value: true });
9471
+ exports2.GENERIC_PARADOX_WARNING = void 0;
9472
+ exports2.createToolCallHandler = createToolCallHandler;
9473
+ exports2.bindToolCallHandler = bindToolCallHandler;
9474
+ var lsp_1 = require_lsp();
9475
+ var readiness_1 = require_readiness();
9476
+ var vanillaCache_1 = require_vanillaCache();
9477
+ var mcpSchema_1 = require_mcpSchema();
9478
+ var toolHandlers_1 = require_toolHandlers();
9479
+ exports2.GENERIC_PARADOX_WARNING = "Generic Paradox mode: the exact game is unknown; no game-specific rules or vanilla data are assumed. Pass --game to select a game.";
9480
+ function createToolCallHandler(host, dispatcher = toolHandlers_1.defaultSharedToolDispatcher) {
9481
+ let ready = false;
9482
+ const probeReadiness = async (context, force = false) => {
9483
+ if (ready && !force)
9484
+ return { ready: true };
9485
+ try {
9486
+ const status = await host.lsp.executeCommand("cwtools.ai.getValidationStatus", [], {
9487
+ timeoutMs: 8e3,
9488
+ ...context?.signal ? { signal: context.signal } : {}
9489
+ });
9490
+ const verdict = (0, readiness_1.parseReadiness)(status);
9491
+ ready = verdict.ready;
9492
+ return verdict;
9493
+ } catch (error) {
9494
+ (0, lsp_1.throwIfAborted)(context?.signal);
9495
+ throw error;
9496
+ }
9497
+ };
9498
+ return async (name, args = {}, context) => {
9499
+ (0, lsp_1.throwIfAborted)(context?.signal);
9500
+ const writesEnabled = host.writesEnabled === true && host.readonlyMode === false;
9501
+ const cwtOnly = host.projectKind === "cwt-only";
9502
+ if (!(0, mcpSchema_1.isMcpToolAvailable)(name, { includeWrites: writesEnabled, cwtOnly })) {
9503
+ return {
9504
+ ok: false,
9505
+ status: "denied",
9506
+ source: "cwtools-shared",
9507
+ error: {
9508
+ code: cwtOnly ? "tool_not_available_in_cwt_only" : "tool_not_available",
9509
+ message: cwtOnly ? `Tool '${name}' requires a full Paradox game model and is not available in a CWT-only workspace.` : `Tool '${name}' is not available under the current host write policy.`
9510
+ }
9511
+ };
9512
+ }
9513
+ const result = await dispatcher(host, name, args, context);
9514
+ const withGenericWarning = host.projectGameId === "paradox" ? {
9515
+ ...result,
9516
+ warnings: [...result.warnings ?? [], exports2.GENERIC_PARADOX_WARNING]
9517
+ } : result;
9518
+ const withVanilla = (0, vanillaCache_1.annotateVanillaCache)(name, withGenericWarning, host.vanillaCache);
9519
+ if (!readiness_1.LOAD_DEPENDENT_TOOLS.has(name))
9520
+ return withVanilla;
9521
+ const lostBackend = result.ok === false && result.status === "unavailable";
9522
+ return (0, readiness_1.annotateReadiness)(name, withVanilla, await probeReadiness(context, lostBackend));
9523
+ };
9524
+ }
9525
+ function bindToolCallHandler(host, dispatcher = toolHandlers_1.defaultSharedToolDispatcher) {
9526
+ return createToolCallHandler(host, dispatcher);
9527
+ }
9528
+ }
9529
+ });
9530
+
9531
+ // ../cwtools-shared/dist/tools/registry.js
9532
+ var require_registry = __commonJS({
9533
+ "../cwtools-shared/dist/tools/registry.js"(exports2) {
9534
+ "use strict";
9535
+ Object.defineProperty(exports2, "__esModule", { value: true });
9536
+ }
9537
+ });
9538
+
8343
9539
  // ../cwtools-shared/dist/index.js
8344
9540
  var require_dist = __commonJS({
8345
9541
  "../cwtools-shared/dist/index.js"(exports2) {
@@ -8362,6 +9558,8 @@ var require_dist = __commonJS({
8362
9558
  };
8363
9559
  Object.defineProperty(exports2, "__esModule", { value: true });
8364
9560
  __exportStar(require_mcpTools(), exports2);
9561
+ __exportStar(require_workspaceGameDetection(), exports2);
9562
+ __exportStar(require_capabilities(), exports2);
8365
9563
  __exportStar(require_diagnostics(), exports2);
8366
9564
  __exportStar(require_filesystem(), exports2);
8367
9565
  __exportStar(require_hostServices(), exports2);
@@ -8379,12 +9577,14 @@ var require_dist = __commonJS({
8379
9577
  __exportStar(require_localisation(), exports2);
8380
9578
  __exportStar(require_paths(), exports2);
8381
9579
  __exportStar(require_writes(), exports2);
9580
+ __exportStar(require_callHandler(), exports2);
8382
9581
  __exportStar(require_mcpSchema(), exports2);
8383
9582
  __exportStar(require_names(), exports2);
8384
9583
  __exportStar(require_pdxBlock(), exports2);
8385
9584
  __exportStar(require_registry(), exports2);
8386
9585
  __exportStar(require_schema(), exports2);
8387
9586
  __exportStar(require_symbols(), exports2);
9587
+ __exportStar(require_targetingWeights(), exports2);
8388
9588
  __exportStar(require_toolHandlers(), exports2);
8389
9589
  }
8390
9590
  });
@@ -13374,9 +14574,9 @@ var require_node = __commonJS({
13374
14574
  }
13375
14575
  });
13376
14576
 
13377
- // dist/hosts/vscodeCache.js
14577
+ // ../cwtools-node/dist/hosts/vscodeCache.js
13378
14578
  var require_vscodeCache = __commonJS({
13379
- "dist/hosts/vscodeCache.js"(exports2) {
14579
+ "../cwtools-node/dist/hosts/vscodeCache.js"(exports2) {
13380
14580
  "use strict";
13381
14581
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
13382
14582
  if (k2 === void 0) k2 = k;
@@ -13499,7 +14699,9 @@ var require_vscodeCache = __commonJS({
13499
14699
  }
13500
14700
  }
13501
14701
  function detectExtensionRulesDir(cacheDir, game) {
13502
- const g = (game ?? "stellaris").toLowerCase();
14702
+ if (!game || game === "paradox" || game === "cwt")
14703
+ return void 0;
14704
+ const g = game.toLowerCase();
13503
14705
  const roots = [
13504
14706
  ...cacheDir ? [cacheDir] : [],
13505
14707
  ...globalStorageBases().map((base) => path.join(base, PRIMARY_EXTENSION_DIR, ".cwtools"))
@@ -13517,9 +14719,9 @@ var require_vscodeCache = __commonJS({
13517
14719
  }
13518
14720
  });
13519
14721
 
13520
- // dist/hosts/projectSettings.js
14722
+ // ../cwtools-node/dist/hosts/projectSettings.js
13521
14723
  var require_projectSettings = __commonJS({
13522
- "dist/hosts/projectSettings.js"(exports2) {
14724
+ "../cwtools-node/dist/hosts/projectSettings.js"(exports2) {
13523
14725
  "use strict";
13524
14726
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
13525
14727
  if (k2 === void 0) k2 = k;
@@ -13561,6 +14763,7 @@ var require_projectSettings = __commonJS({
13561
14763
  Object.defineProperty(exports2, "__esModule", { value: true });
13562
14764
  exports2.getExtensionSetting = getExtensionSetting;
13563
14765
  exports2.readIgnoredDiagnostics = readIgnoredDiagnostics;
14766
+ exports2.honouredIgnoredDiagnostics = honouredIgnoredDiagnostics;
13564
14767
  exports2.resolveLocalisationLanguages = resolveLocalisationLanguages;
13565
14768
  exports2.resolveGeneratedStrings = resolveGeneratedStrings;
13566
14769
  exports2.resolveExperimental = resolveExperimental;
@@ -13683,6 +14886,9 @@ var require_projectSettings = __commonJS({
13683
14886
  function readIgnoredDiagnostics(workspaceRoot) {
13684
14887
  return asNonEmptyStringArray(getExtensionSetting(workspaceRoot, "ai.ignoredDiagnostics"));
13685
14888
  }
14889
+ function honouredIgnoredDiagnostics(workspaceRoot, honor) {
14890
+ return honor ? readIgnoredDiagnostics(workspaceRoot) : [];
14891
+ }
13686
14892
  var LANG_TAG_MAP = [
13687
14893
  ["English", "english"],
13688
14894
  ["French", "french"],
@@ -13767,16 +14973,15 @@ var require_projectSettings = __commonJS({
13767
14973
  return {
13768
14974
  ...result,
13769
14975
  diagnostics: kept,
13770
- suppressedCount: (result.suppressedCount ?? 0) + suppressed,
13771
- totalCount: typeof result.totalCount === "number" ? Math.max(0, result.totalCount - suppressed) : result.totalCount
14976
+ suppressedCount: (result.suppressedCount ?? 0) + suppressed
13772
14977
  };
13773
14978
  }
13774
14979
  }
13775
14980
  });
13776
14981
 
13777
- // dist/hosts/lspProcessHost.js
14982
+ // ../cwtools-node/dist/hosts/lspProcessHost.js
13778
14983
  var require_lspProcessHost = __commonJS({
13779
- "dist/hosts/lspProcessHost.js"(exports2) {
14984
+ "../cwtools-node/dist/hosts/lspProcessHost.js"(exports2) {
13780
14985
  "use strict";
13781
14986
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
13782
14987
  if (k2 === void 0) k2 = k;
@@ -13816,10 +15021,12 @@ var require_lspProcessHost = __commonJS({
13816
15021
  };
13817
15022
  })();
13818
15023
  Object.defineProperty(exports2, "__esModule", { value: true });
13819
- exports2.LspProcessHost = void 0;
15024
+ exports2.LspProcessHost = exports2.BackendIncompatibleError = void 0;
13820
15025
  exports2.resolveRulesCacheRoot = resolveRulesCacheRoot;
15026
+ exports2.buildCwtoolsConfiguration = buildCwtoolsConfiguration;
13821
15027
  exports2.createLspProcessHost = createLspProcessHost;
13822
15028
  exports2.resolveDefaultServerPath = resolveDefaultServerPath;
15029
+ exports2.rulesDirectoryCandidates = rulesDirectoryCandidates;
13823
15030
  exports2.pathToFileUri = pathToFileUri;
13824
15031
  exports2.isLspWatchedFile = isLspWatchedFile;
13825
15032
  var fs = __importStar(require("fs"));
@@ -13828,41 +15035,65 @@ var require_lspProcessHost = __commonJS({
13828
15035
  var child_process_1 = require("child_process");
13829
15036
  var chokidar_1 = require_chokidar();
13830
15037
  var node_1 = require_node();
15038
+ var cwtools_shared_1 = require_dist();
13831
15039
  var vscodeCache_1 = require_vscodeCache();
13832
15040
  var projectSettings_1 = require_projectSettings();
13833
15041
  function resolveRulesCacheRoot(options) {
13834
15042
  return options.rulesCache ?? options.cachePath ?? path.join(options.workspaceRoot, ".cwtools", "rules-cache");
13835
15043
  }
15044
+ var DEFAULT_STARTUP_TIMEOUT_MS = 3e4;
15045
+ var BackendIncompatibleError = class extends Error {
15046
+ constructor(reason, message) {
15047
+ super(`CWTools backend is incompatible (${reason}): ${message}`);
15048
+ this.reason = reason;
15049
+ this.code = cwtools_shared_1.BACKEND_INCOMPATIBLE_CODE;
15050
+ this.name = "BackendIncompatibleError";
15051
+ }
15052
+ };
15053
+ exports2.BackendIncompatibleError = BackendIncompatibleError;
13836
15054
  var LspProcessHost = class {
15055
+ get debugEnabled() {
15056
+ return this.options.debug === true || !!process.env.CWTOOLS_MCP_DEBUG;
15057
+ }
13837
15058
  constructor(options) {
13838
15059
  this.options = options;
13839
15060
  this.pendingWatchedChanges = /* @__PURE__ */ new Map();
15061
+ this.generation = 0;
13840
15062
  }
13841
15063
  get readyAtMs() {
13842
15064
  return this.startedAtMs;
13843
15065
  }
15066
+ /** Capability record answered by the backend, once the handshake succeeded. */
15067
+ get backendCapabilities() {
15068
+ return this.capabilities;
15069
+ }
13844
15070
  async executeCommand(command, args = [], options) {
13845
15071
  try {
13846
- await this.ensureStarted(options?.timeoutMs);
13847
- const result = await this.withTimeout(this.connection.sendRequest("workspace/executeCommand", {
13848
- command,
13849
- arguments: args
13850
- }), options?.timeoutMs ?? 2e4, `LSP command ${command} timed out`);
15072
+ await this.ensureStarted(options?.signal);
15073
+ const result = await this.raceRequest("workspace/executeCommand", { command, arguments: args }, options?.timeoutMs ?? this.options.requestTimeoutMs ?? 2e4, `LSP command ${command} timed out`, options?.signal);
13851
15074
  return result;
13852
15075
  } catch (error) {
15076
+ if ((0, cwtools_shared_1.isAbortError)(error))
15077
+ throw error;
15078
+ if (error instanceof BackendIncompatibleError)
15079
+ return this.incompatibleResult(error);
13853
15080
  return this.unavailable(error instanceof Error ? error.message : String(error));
13854
15081
  }
13855
15082
  }
13856
- async sendRequest(method, params, timeoutMs = 2e4) {
15083
+ async sendRequest(method, params, timeoutMs = this.options.requestTimeoutMs ?? 2e4, signal) {
13857
15084
  try {
13858
- await this.ensureStarted(timeoutMs);
13859
- return await this.withTimeout(this.connection.sendRequest(method, params), timeoutMs, `LSP request ${method} timed out`);
15085
+ await this.ensureStarted(signal);
15086
+ return await this.raceRequest(method, params, timeoutMs, `LSP request ${method} timed out`, signal);
13860
15087
  } catch (error) {
15088
+ if ((0, cwtools_shared_1.isAbortError)(error))
15089
+ throw error;
15090
+ if (error instanceof BackendIncompatibleError)
15091
+ return this.incompatibleResult(error);
13861
15092
  return this.unavailable(error instanceof Error ? error.message : String(error));
13862
15093
  }
13863
15094
  }
13864
15095
  async request(method, params, options) {
13865
- return this.sendRequest(method, params, options?.timeoutMs);
15096
+ return this.sendRequest(method, params, options?.timeoutMs, options?.signal);
13866
15097
  }
13867
15098
  dispose() {
13868
15099
  const proc = this.process;
@@ -13870,6 +15101,7 @@ var require_lspProcessHost = __commonJS({
13870
15101
  this.connection = void 0;
13871
15102
  this.process = void 0;
13872
15103
  this.startPromise = void 0;
15104
+ this.generation += 1;
13873
15105
  this.stopFileWatcher();
13874
15106
  try {
13875
15107
  connection?.dispose();
@@ -13880,23 +15112,42 @@ var require_lspProcessHost = __commonJS({
13880
15112
  } catch {
13881
15113
  }
13882
15114
  }
13883
- async ensureStarted(timeoutMs = 3e4) {
15115
+ async ensureStarted(signal) {
15116
+ if (this.incompatible)
15117
+ throw this.incompatible;
13884
15118
  if (this.connection && !this.startError)
13885
15119
  return;
13886
15120
  if (!this.startPromise) {
13887
- this.startPromise = this.start();
15121
+ const generation = this.generation;
15122
+ this.startPromise = this.start(generation, signal).catch((error) => {
15123
+ if (this.generation === generation)
15124
+ this.startPromise = void 0;
15125
+ throw error;
15126
+ });
13888
15127
  }
13889
- await this.withTimeout(this.startPromise, timeoutMs, "CWTools LSP startup timed out");
15128
+ await this.startPromise;
13890
15129
  if (this.startError)
13891
15130
  throw new Error(this.startError);
13892
15131
  }
13893
- async start() {
15132
+ async start(generation, signal) {
15133
+ try {
15134
+ await this.startInternal(generation, signal);
15135
+ } catch (error) {
15136
+ if (this.generation === generation)
15137
+ this.dispose();
15138
+ throw error;
15139
+ }
15140
+ }
15141
+ async startInternal(generation, signal) {
15142
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15143
+ const startupTimeoutMs = this.options.startupTimeoutMs ?? DEFAULT_STARTUP_TIMEOUT_MS;
15144
+ const stale = () => this.generation !== generation;
13894
15145
  const serverPath = this.options.serverPath ?? resolveDefaultServerPath();
13895
15146
  if (!serverPath || !fs.existsSync(serverPath)) {
13896
15147
  this.startError = `CWTools server binary was not found. Checked: ${serverPath ?? "(none)"}`;
13897
15148
  throw new Error(this.startError);
13898
15149
  }
13899
- this.process = (0, child_process_1.spawn)(serverPath, [], {
15150
+ this.process = (0, child_process_1.spawn)(serverPath, this.options.serverArgs ?? [], {
13900
15151
  cwd: this.options.workspaceRoot,
13901
15152
  stdio: ["pipe", "pipe", "pipe"],
13902
15153
  windowsHide: true
@@ -13907,14 +15158,16 @@ var require_lspProcessHost = __commonJS({
13907
15158
  process.stderr.write(`[cwtools-lsp] ${text}`);
13908
15159
  }
13909
15160
  });
13910
- this.process.on("exit", (code, signal) => {
13911
- this.startError = `CWTools LSP exited with code ${code ?? "null"} signal ${signal ?? "null"}`;
15161
+ this.process.on("exit", (code, exitSignal) => {
15162
+ if (stale())
15163
+ return;
15164
+ this.startError = `CWTools LSP exited with code ${code ?? "null"} signal ${exitSignal ?? "null"}`;
13912
15165
  this.connection = void 0;
13913
15166
  this.stopFileWatcher();
13914
15167
  });
13915
15168
  this.connection = (0, node_1.createMessageConnection)(new node_1.StreamMessageReader(this.process.stdout), new node_1.StreamMessageWriter(this.process.stdin));
13916
15169
  this.connection.listen();
13917
- if (process.env.CWTOOLS_MCP_DEBUG) {
15170
+ if (this.debugEnabled) {
13918
15171
  this.connection.onNotification("window/logMessage", (p = {}) => {
13919
15172
  if (p.message)
13920
15173
  process.stderr.write(`[cwtools-lsp] ${String(p.message).slice(0, 240)}
@@ -13922,13 +15175,13 @@ var require_lspProcessHost = __commonJS({
13922
15175
  });
13923
15176
  }
13924
15177
  const rootUri = pathToFileUri(this.options.workspaceRoot);
13925
- const game = this.options.game ?? "stellaris";
15178
+ const game = this.options.game ?? "paradox";
13926
15179
  const rulesCacheRoot = resolveRulesCacheRoot(this.options);
13927
- const rulesFolder = this.options.bundledRulesPath ?? resolveBundledRulesPath(game, rulesCacheRoot);
15180
+ const rulesFolder = game === "paradox" || game === "cwt" ? "" : this.options.bundledRulesPath ?? resolveBundledRulesPath(game, rulesCacheRoot, this.options.workspaceRoot);
13928
15181
  if (!rulesFolder) {
13929
- process.stderr.write("[cwtools-mcp] warning: no CWT rules found \u2014 install the VS Code extension or pass --rules <dir>; validation will be limited\n");
15182
+ process.stderr.write("[cwtools-node] warning: no CWT rules found \u2014 install the VS Code extension or pass --rules <dir>; validation will be limited\n");
13930
15183
  }
13931
- await this.connection.sendRequest("initialize", {
15184
+ await this.raceRequest("initialize", {
13932
15185
  processId: process.pid,
13933
15186
  rootPath: this.options.workspaceRoot,
13934
15187
  rootUri,
@@ -13961,23 +15214,54 @@ var require_lspProcessHost = __commonJS({
13961
15214
  diagnosticLogging: false
13962
15215
  },
13963
15216
  trace: "off"
13964
- });
15217
+ }, startupTimeoutMs, "CWTools LSP initialize timed out", signal);
15218
+ await this.handshake(startupTimeoutMs, signal, stale);
15219
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15220
+ if (stale())
15221
+ throw (0, cwtools_shared_1.createAbortError)("Operation was aborted.");
13965
15222
  void this.connection.sendNotification("initialized", {});
13966
15223
  const loc = (0, projectSettings_1.resolveLocalisationLanguages)(this.options.workspaceRoot);
13967
- process.stderr.write(`[cwtools-mcp] info: localisation languages = [${loc.languages.join(", ")}] (${loc.source})
15224
+ process.stderr.write(`[cwtools-node] info: localisation languages = [${loc.languages.join(", ")}] (${loc.source})
13968
15225
  `);
13969
15226
  void this.connection.sendNotification("workspace/didChangeConfiguration", {
13970
15227
  settings: {
13971
15228
  cwtools: buildCwtoolsConfiguration(game, this.options.gamePath, rulesFolder ?? "", {
13972
15229
  languages: loc.languages,
13973
15230
  generatedStrings: (0, projectSettings_1.resolveGeneratedStrings)(this.options.workspaceRoot)
13974
- }, (0, projectSettings_1.resolveExperimental)(this.options.workspaceRoot))
15231
+ }, (0, projectSettings_1.resolveExperimental)(this.options.workspaceRoot), {
15232
+ ignoreCodes: this.options.errorIgnoreCodes ?? [],
15233
+ ignoreFiles: this.options.errorIgnoreFiles ?? [],
15234
+ localisationFilter: this.options.localisationDiagnosticFilter ?? "off"
15235
+ })
13975
15236
  }
13976
15237
  });
13977
- await this.waitForExecuteCommandsReady(2e4);
15238
+ await this.waitForExecuteCommandsReady(Math.min(startupTimeoutMs, 2e4), signal, stale);
15239
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15240
+ if (stale())
15241
+ throw (0, cwtools_shared_1.createAbortError)("Operation was aborted.");
13978
15242
  this.startFileWatcher();
13979
15243
  this.startedAtMs = Date.now();
13980
15244
  }
15245
+ async handshake(timeoutMs, signal, stale = () => false) {
15246
+ const raw = await this.raceRequest("workspace/executeCommand", { command: "cwtools.ai.getHostCapabilities", arguments: [] }, timeoutMs, "CWTools capability handshake timed out", signal).catch((error) => {
15247
+ if ((0, cwtools_shared_1.isAbortError)(error))
15248
+ throw error;
15249
+ return { status: "unavailable", error: { message: String(error) } };
15250
+ });
15251
+ const verdict = (0, cwtools_shared_1.parseHostCapabilities)(raw);
15252
+ const checked = verdict.ok ? (0, cwtools_shared_1.checkRequiredCommands)(verdict.capabilities) : verdict;
15253
+ if (checked.ok) {
15254
+ this.capabilities = checked.capabilities;
15255
+ return;
15256
+ }
15257
+ const incompatibility = new BackendIncompatibleError(checked.reason, checked.message);
15258
+ if (!stale()) {
15259
+ this.dispose();
15260
+ this.incompatible = incompatibility;
15261
+ this.startError = incompatibility.message;
15262
+ }
15263
+ throw incompatibility;
15264
+ }
13981
15265
  startFileWatcher() {
13982
15266
  if (this.fileWatcher)
13983
15267
  return;
@@ -13990,8 +15274,8 @@ var require_lspProcessHost = __commonJS({
13990
15274
  watcher.on("change", (filePath) => this.queueWatchedFileChange(filePath, 2));
13991
15275
  watcher.on("unlink", (filePath) => this.queueWatchedFileChange(filePath, 3));
13992
15276
  watcher.on("error", (error) => {
13993
- if (process.env.CWTOOLS_MCP_DEBUG) {
13994
- process.stderr.write(`[cwtools-mcp] file watcher error: ${String(error)}
15277
+ if (this.debugEnabled) {
15278
+ process.stderr.write(`[cwtools-node] file watcher error: ${String(error)}
13995
15279
  `);
13996
15280
  }
13997
15281
  });
@@ -14029,6 +15313,19 @@ var require_lspProcessHost = __commonJS({
14029
15313
  this.pendingWatchedChanges.clear();
14030
15314
  void connection.sendNotification("workspace/didChangeWatchedFiles", { changes });
14031
15315
  }
15316
+ // A rejected handshake is a distinct failure: the caller must not treat it as a
15317
+ // transient "start the server" condition and retry.
15318
+ incompatibleResult(error) {
15319
+ return {
15320
+ ok: false,
15321
+ status: "unavailable",
15322
+ error: {
15323
+ code: cwtools_shared_1.BACKEND_INCOMPATIBLE_CODE,
15324
+ reason: error.reason,
15325
+ message: error.message
15326
+ }
15327
+ };
15328
+ }
14032
15329
  unavailable(message) {
14033
15330
  return {
14034
15331
  ok: false,
@@ -14039,27 +15336,66 @@ var require_lspProcessHost = __commonJS({
14039
15336
  }
14040
15337
  };
14041
15338
  }
14042
- async withTimeout(promise, timeoutMs, message) {
15339
+ // Issue a JSON-RPC request that is actually cancellable: the AbortSignal is
15340
+ // linked to a vscode-jsonrpc CancellationTokenSource, so aborting sends a
15341
+ // `$/cancelRequest` to the backend and releases its work — racing the promise
15342
+ // alone would leave the server computing a result nobody reads. The deadline and
15343
+ // the abort listener are both released in the finally block.
15344
+ async raceRequest(method, params, timeoutMs, timeoutMessage, signal) {
15345
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15346
+ const connection = this.connection;
15347
+ if (!connection)
15348
+ throw new Error("CWTools LSP connection is not established.");
15349
+ const cancellation = new node_1.CancellationTokenSource();
14043
15350
  let timer;
15351
+ let onAbort;
15352
+ let settled = false;
15353
+ const request = connection.sendRequest(method, params, cancellation.token);
14044
15354
  try {
14045
- return await Promise.race([
14046
- promise,
14047
- new Promise((_, reject) => {
14048
- timer = setTimeout(() => reject(new Error(message)), timeoutMs);
14049
- })
14050
- ]);
15355
+ const timeout = new Promise((_, reject) => {
15356
+ timer = setTimeout(() => {
15357
+ settled = true;
15358
+ cancellation.cancel();
15359
+ reject(new Error(timeoutMessage));
15360
+ }, timeoutMs);
15361
+ });
15362
+ const aborted = new Promise((_, reject) => {
15363
+ if (!signal)
15364
+ return;
15365
+ onAbort = () => {
15366
+ settled = true;
15367
+ cancellation.cancel();
15368
+ reject((0, cwtools_shared_1.createAbortError)(signal.reason instanceof Error ? signal.reason.message : "Operation was aborted."));
15369
+ };
15370
+ signal.addEventListener("abort", onAbort, { once: true });
15371
+ });
15372
+ return await Promise.race([request, timeout, aborted]);
14051
15373
  } finally {
14052
15374
  if (timer)
14053
15375
  clearTimeout(timer);
15376
+ if (onAbort && signal)
15377
+ signal.removeEventListener("abort", onAbort);
15378
+ if (settled) {
15379
+ cancellation.cancel();
15380
+ void request.catch(() => void 0);
15381
+ }
15382
+ cancellation.dispose();
14054
15383
  }
14055
15384
  }
14056
- async waitForExecuteCommandsReady(timeoutMs) {
15385
+ // Poll until the command surface answers. Abort- and generation-aware: a host
15386
+ // disposed (or an AbortSignal fired) mid-poll stops here instead of continuing
15387
+ // to touch a connection that may already be gone.
15388
+ async waitForExecuteCommandsReady(timeoutMs, signal, stale = () => false) {
14057
15389
  const start = Date.now();
14058
15390
  while (Date.now() - start < timeoutMs) {
14059
- const result = await this.connection.sendRequest("workspace/executeCommand", {
14060
- command: "cwtools.ai.getValidationStatus",
14061
- arguments: []
14062
- }).catch(() => null);
15391
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15392
+ if (stale())
15393
+ throw (0, cwtools_shared_1.createAbortError)("Operation was aborted.");
15394
+ const result = await this.raceRequest("workspace/executeCommand", { command: "cwtools.ai.getValidationStatus", arguments: [] }, Math.max(1, Math.min(5e3, timeoutMs)), "CWTools readiness probe timed out", signal).catch((error) => {
15395
+ if ((0, cwtools_shared_1.isAbortError)(error) || error instanceof BackendIncompatibleError)
15396
+ throw error;
15397
+ return null;
15398
+ });
14063
15399
  if (result && typeof result === "object")
14064
15400
  return;
14065
15401
  await new Promise((resolve) => setTimeout(resolve, 500));
@@ -14067,7 +15403,7 @@ var require_lspProcessHost = __commonJS({
14067
15403
  }
14068
15404
  };
14069
15405
  exports2.LspProcessHost = LspProcessHost;
14070
- function buildCwtoolsConfiguration(game, gamePath, rulesFolder, localisation, experimental) {
15406
+ function buildCwtoolsConfiguration(game, gamePath, rulesFolder, localisation, experimental, noise = { ignoreCodes: [], ignoreFiles: [], localisationFilter: "off" }) {
14071
15407
  const vanillaDir = gamePath ?? "";
14072
15408
  return {
14073
15409
  localisation: {
@@ -14076,8 +15412,9 @@ var require_lspProcessHost = __commonJS({
14076
15412
  },
14077
15413
  errors: {
14078
15414
  vanilla: false,
14079
- ignore: [],
14080
- ignorefiles: []
15415
+ ignore: [...noise.ignoreCodes],
15416
+ ignorefiles: [...noise.ignoreFiles],
15417
+ localisationFilter: noise.localisationFilter
14081
15418
  },
14082
15419
  // On by default: enables incremental scripted-type refresh so revalidating a
14083
15420
  // scripted_trigger/effect/value patches the type index fast instead of a full reload.
@@ -14128,20 +15465,20 @@ var require_lspProcessHost = __commonJS({
14128
15465
  ];
14129
15466
  return candidates.find((candidate) => fs.existsSync(candidate)) ?? candidates[0];
14130
15467
  }
14131
- function resolveBundledRulesPath(game, cacheDir) {
15468
+ function resolveBundledRulesPath(game, cacheDir, workspaceRoot) {
14132
15469
  const extracted = (0, vscodeCache_1.detectExtensionRulesDir)(cacheDir, game);
14133
15470
  if (extracted)
14134
15471
  return extracted;
14135
- const repoRoot = path.resolve(__dirname, "..", "..", "..", "..");
14136
- const candidates = [
14137
- path.join(process.cwd(), "release", "rules", game, "config"),
14138
- path.join(process.cwd(), "submodules", `cwtools-${game}-config`, "config"),
14139
- game === "stellaris" ? path.join(process.cwd(), "submodules", "cwtools-stellaris-config", "config") : "",
14140
- path.join(repoRoot, "release", "rules", game, "config"),
14141
- path.join(repoRoot, "submodules", `cwtools-${game}-config`, "config"),
14142
- game === "stellaris" ? path.join(repoRoot, "submodules", "cwtools-stellaris-config", "config") : ""
14143
- ].filter(Boolean);
14144
- return candidates.find((candidate) => fs.existsSync(candidate));
15472
+ return rulesDirectoryCandidates(game, workspaceRoot).find((candidate) => fs.existsSync(candidate));
15473
+ }
15474
+ function rulesDirectoryCandidates(game, workspaceRoot, cwd = process.cwd(), repoRoot = path.resolve(__dirname, "..", "..", "..", "..")) {
15475
+ const layouts = [
15476
+ (root) => path.join(root, "release", "rules", game, "config"),
15477
+ (root) => path.join(root, "submodules", `cwtools-${game}-config`, "config"),
15478
+ (root) => game === "stellaris" ? path.join(root, "submodules", "cwtools-stellaris-config", "config") : ""
15479
+ ];
15480
+ const roots = [workspaceRoot, cwd, repoRoot].filter((root) => !!root);
15481
+ return roots.flatMap((root) => layouts.map((layout) => layout(root))).filter(Boolean);
14145
15482
  }
14146
15483
  function pathToFileUri(filePath) {
14147
15484
  const resolved = path.resolve(filePath).replace(/\\/g, "/");
@@ -14175,154 +15512,136 @@ var require_lspProcessHost = __commonJS({
14175
15512
  }
14176
15513
  });
14177
15514
 
14178
- // dist/hosts/projectDetect.js
14179
- var require_projectDetect = __commonJS({
14180
- "dist/hosts/projectDetect.js"(exports2) {
15515
+ // ../cwtools-node/dist/hosts/gameInstall.js
15516
+ var require_gameInstall = __commonJS({
15517
+ "../cwtools-node/dist/hosts/gameInstall.js"(exports2) {
14181
15518
  "use strict";
14182
- var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
14183
- if (k2 === void 0) k2 = k;
14184
- var desc = Object.getOwnPropertyDescriptor(m, k);
14185
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
14186
- desc = { enumerable: true, get: function() {
14187
- return m[k];
14188
- } };
14189
- }
14190
- Object.defineProperty(o, k2, desc);
14191
- }) : (function(o, m, k, k2) {
14192
- if (k2 === void 0) k2 = k;
14193
- o[k2] = m[k];
14194
- }));
14195
- var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {
14196
- Object.defineProperty(o, "default", { enumerable: true, value: v });
14197
- }) : function(o, v) {
14198
- o["default"] = v;
14199
- });
14200
- var __importStar = exports2 && exports2.__importStar || /* @__PURE__ */ (function() {
14201
- var ownKeys = function(o) {
14202
- ownKeys = Object.getOwnPropertyNames || function(o2) {
14203
- var ar = [];
14204
- for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
14205
- return ar;
14206
- };
14207
- return ownKeys(o);
14208
- };
14209
- return function(mod) {
14210
- if (mod && mod.__esModule) return mod;
14211
- var result = {};
14212
- if (mod != null) {
14213
- for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
14214
- }
14215
- __setModuleDefault(result, mod);
14216
- return result;
14217
- };
14218
- })();
15519
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
15520
+ return mod && mod.__esModule ? mod : { "default": mod };
15521
+ };
14219
15522
  Object.defineProperty(exports2, "__esModule", { value: true });
14220
- exports2.detectProjectSupport = detectProjectSupport;
14221
- var fs = __importStar(require("fs"));
14222
- var path = __importStar(require("path"));
14223
- var ROOT_FILE_MARKERS = ["descriptor.mod"];
14224
- var ROOT_NESTED_FILE_MARKERS = [path.join(".metadata", "metadata.json")];
14225
- var ROOT_DIR_MARKERS = [".cwtools"];
14226
- var CONTENT_DIR_MARKERS = ["common", "events", "localisation", "localization"];
14227
- var MAX_ANCESTORS = 6;
14228
- var MAX_CHILDREN = 64;
14229
- function isFile(p) {
15523
+ exports2.GAME_INSTALL_LAYOUT = void 0;
15524
+ exports2.detectSteamLibraries = detectSteamLibraries;
15525
+ exports2.detectGameInstall = detectGameInstall;
15526
+ var node_child_process_1 = require("node:child_process");
15527
+ var node_fs_1 = __importDefault(require("node:fs"));
15528
+ var node_os_1 = __importDefault(require("node:os"));
15529
+ var node_path_1 = __importDefault(require("node:path"));
15530
+ exports2.GAME_INSTALL_LAYOUT = {
15531
+ stellaris: { folder: "Stellaris", alternatives: [] },
15532
+ hoi4: { folder: "Hearts of Iron IV", alternatives: [] },
15533
+ eu4: { folder: "Europa Universalis IV", alternatives: [] },
15534
+ eu5: { folder: "Europa Universalis V", alternatives: [], subdir: "game" },
15535
+ ck2: { folder: "Crusader Kings II", alternatives: [] },
15536
+ ck3: { folder: "Crusader Kings III", alternatives: [], subdir: "game" },
15537
+ vic2: { folder: "Victoria 2", alternatives: ["Victoria II"] },
15538
+ vic3: { folder: "Victoria 3", alternatives: [], subdir: "game" },
15539
+ imperator: { folder: "ImperatorRome", alternatives: ["Imperator"], subdir: "game" }
15540
+ };
15541
+ function steamRoot(options) {
15542
+ const platform = options.platform ?? node_os_1.default.platform();
15543
+ const home = options.home ?? node_os_1.default.homedir();
15544
+ if (platform === "win32") {
15545
+ for (const key of ["HKLM\\SOFTWARE\\WOW6432Node\\Valve\\Steam", "HKLM\\SOFTWARE\\Valve\\Steam"]) {
15546
+ try {
15547
+ const output = (0, node_child_process_1.execFileSync)("reg", ["query", key, "/v", "InstallPath"], {
15548
+ encoding: "utf8",
15549
+ timeout: 3e3,
15550
+ windowsHide: true
15551
+ });
15552
+ const match = /InstallPath\s+REG_SZ\s+(.+)/.exec(output);
15553
+ if (match?.[1])
15554
+ return match[1].trim();
15555
+ } catch {
15556
+ }
15557
+ }
15558
+ for (const candidate of ["C:\\Program Files (x86)\\Steam", "C:\\Program Files\\Steam", "D:\\Steam", "D:\\SteamLibrary"]) {
15559
+ if (node_fs_1.default.existsSync(node_path_1.default.join(candidate, "steam.exe")) || node_fs_1.default.existsSync(node_path_1.default.join(candidate, "steamapps"))) {
15560
+ return candidate;
15561
+ }
15562
+ }
15563
+ return void 0;
15564
+ }
15565
+ if (platform === "darwin") {
15566
+ const macPath = node_path_1.default.join(home, "Library", "Application Support", "Steam");
15567
+ return node_fs_1.default.existsSync(macPath) ? macPath : void 0;
15568
+ }
15569
+ for (const linuxPath of [node_path_1.default.join(home, ".steam", "steam"), node_path_1.default.join(home, ".local", "share", "Steam")]) {
15570
+ if (node_fs_1.default.existsSync(linuxPath))
15571
+ return linuxPath;
15572
+ }
15573
+ return void 0;
15574
+ }
15575
+ function detectSteamLibraries(options = {}) {
15576
+ const root = steamRoot(options);
15577
+ if (!root)
15578
+ return [];
15579
+ const libraries = [root];
15580
+ const vdfPath = node_path_1.default.join(root, "steamapps", "libraryfolders.vdf");
14230
15581
  try {
14231
- return fs.statSync(p).isFile();
15582
+ const content = node_fs_1.default.readFileSync(vdfPath, "utf8");
15583
+ for (const match of content.matchAll(/"path"\s+"([^"]+)"/g)) {
15584
+ const raw = match[1];
15585
+ if (!raw)
15586
+ continue;
15587
+ const library = raw.replace(/\\\\/g, "\\");
15588
+ if (!libraries.includes(library) && node_fs_1.default.existsSync(library))
15589
+ libraries.push(library);
15590
+ }
14232
15591
  } catch {
14233
- return false;
14234
15592
  }
15593
+ return libraries;
14235
15594
  }
14236
- function isDir(p) {
15595
+ function isGameInstall(dir) {
14237
15596
  try {
14238
- return fs.statSync(p).isDirectory();
15597
+ return node_fs_1.default.statSync(node_path_1.default.join(dir, "common")).isDirectory();
14239
15598
  } catch {
14240
15599
  return false;
14241
15600
  }
14242
15601
  }
14243
- function markersAt(dir, includeContent) {
14244
- const found = [];
14245
- for (const f of ROOT_FILE_MARKERS) {
14246
- if (isFile(path.join(dir, f)))
14247
- found.push(f);
14248
- }
14249
- for (const f of ROOT_NESTED_FILE_MARKERS) {
14250
- if (isFile(path.join(dir, f)))
14251
- found.push(f.replace(/\\/g, "/"));
14252
- }
14253
- for (const d of ROOT_DIR_MARKERS) {
14254
- if (isDir(path.join(dir, d)))
14255
- found.push(`${d}/`);
14256
- }
14257
- if (includeContent) {
14258
- for (const d of CONTENT_DIR_MARKERS) {
14259
- if (isDir(path.join(dir, d)))
14260
- found.push(`${d}/`);
15602
+ function detectGameInstall(gameId, libraries = detectSteamLibraries()) {
15603
+ const layout = gameId === void 0 ? void 0 : exports2.GAME_INSTALL_LAYOUT[gameId];
15604
+ if (!layout)
15605
+ return void 0;
15606
+ for (const folder of [layout.folder, ...layout.alternatives]) {
15607
+ for (const library of libraries) {
15608
+ const root = node_path_1.default.join(library, "steamapps", "common", folder);
15609
+ const data = layout.subdir ? node_path_1.default.join(root, layout.subdir) : root;
15610
+ if (isGameInstall(data))
15611
+ return data;
14261
15612
  }
14262
15613
  }
14263
- return found;
15614
+ return void 0;
14264
15615
  }
14265
- function detectProjectSupport(workspaceRoot) {
14266
- const atRoot = markersAt(workspaceRoot, true);
14267
- if (atRoot.length > 0) {
14268
- return {
14269
- supported: true,
14270
- markers: atRoot,
14271
- matchedAt: workspaceRoot,
14272
- reason: `Detected Paradox mod markers at the workspace root: ${atRoot.join(", ")}.`
14273
- };
14274
- }
14275
- let dir = workspaceRoot;
14276
- for (let i = 0; i < MAX_ANCESTORS; i++) {
14277
- const parent = path.dirname(dir);
14278
- if (!parent || parent === dir)
14279
- break;
14280
- dir = parent;
14281
- const atAncestor = markersAt(dir, false);
14282
- if (atAncestor.length > 0) {
14283
- return {
14284
- supported: true,
14285
- markers: atAncestor,
14286
- matchedAt: dir,
14287
- reason: `Detected a Paradox mod root above the workspace (${dir}): ${atAncestor.join(", ")}.`
14288
- };
14289
- }
14290
- }
14291
- let children = [];
14292
- try {
14293
- children = fs.readdirSync(workspaceRoot, { withFileTypes: true });
14294
- } catch {
14295
- children = [];
14296
- }
14297
- let probed = 0;
14298
- for (const child of children) {
14299
- if (!child.isDirectory() || child.name === "node_modules")
14300
- continue;
14301
- if (probed++ >= MAX_CHILDREN)
14302
- break;
14303
- const childDir = path.join(workspaceRoot, child.name);
14304
- const atChild = markersAt(childDir, true);
14305
- if (atChild.length > 0) {
14306
- return {
14307
- supported: true,
14308
- markers: atChild.map((m) => `${child.name}/${m}`),
14309
- matchedAt: childDir,
14310
- reason: `Detected a Paradox mod in a subfolder (${child.name}/): ${atChild.join(", ")}.`
14311
- };
14312
- }
14313
- }
15616
+ }
15617
+ });
15618
+
15619
+ // ../cwtools-node/dist/hosts/projectDetect.js
15620
+ var require_projectDetect = __commonJS({
15621
+ "../cwtools-node/dist/hosts/projectDetect.js"(exports2) {
15622
+ "use strict";
15623
+ Object.defineProperty(exports2, "__esModule", { value: true });
15624
+ exports2.detectProjectSupport = detectProjectSupport;
15625
+ var cwtools_shared_1 = require_dist();
15626
+ function detectProjectSupport(workspaceRoot, options) {
15627
+ const detection = (0, cwtools_shared_1.detectWorkspaceProject)(workspaceRoot, (gameId) => options?.gamePath && options.game === gameId ? options.gamePath : void 0);
14314
15628
  return {
14315
- supported: false,
14316
- markers: [],
14317
- reason: `No Paradox mod markers (descriptor.mod, common/, events/, localisation/, .cwtools/) at, above, or directly under '${workspaceRoot}'.`
15629
+ supported: detection.kind === "mod" || detection.kind === "vanilla" || detection.kind === "cwt-only",
15630
+ reason: detection.reason,
15631
+ markers: [...detection.evidence],
15632
+ ...detection.matchedAt ? { matchedAt: detection.matchedAt } : {},
15633
+ kind: detection.kind,
15634
+ ...detection.gameId ? { gameId: detection.gameId } : {},
15635
+ ...detection.candidates ? { candidates: [...detection.candidates] } : {},
15636
+ detection
14318
15637
  };
14319
15638
  }
14320
15639
  }
14321
15640
  });
14322
15641
 
14323
- // dist/hosts/revalidation.js
15642
+ // ../cwtools-node/dist/hosts/revalidation.js
14324
15643
  var require_revalidation = __commonJS({
14325
- "dist/hosts/revalidation.js"(exports2) {
15644
+ "../cwtools-node/dist/hosts/revalidation.js"(exports2) {
14326
15645
  "use strict";
14327
15646
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
14328
15647
  if (k2 === void 0) k2 = k;
@@ -14365,6 +15684,7 @@ var require_revalidation = __commonJS({
14365
15684
  exports2.RevalidationCoordinator = void 0;
14366
15685
  var fs = __importStar(require("fs"));
14367
15686
  var path = __importStar(require("path"));
15687
+ var cwtools_shared_1 = require_dist();
14368
15688
  var lspProcessHost_1 = require_lspProcessHost();
14369
15689
  var REVALIDATE_EXTS = /* @__PURE__ */ new Set([".txt", ".yml", ".gui", ".gfx", ".asset", ".shader", ".fxh"]);
14370
15690
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "coverage"]);
@@ -14382,7 +15702,11 @@ var require_revalidation = __commonJS({
14382
15702
  this.lastReval = /* @__PURE__ */ new Map();
14383
15703
  }
14384
15704
  // absFile: absolute path for a single-file query, or undefined for whole-project.
14385
- async ensureFresh(absFile) {
15705
+ // `signal` cancels the revalidation and the drain wait; the abort propagates
15706
+ // instead of being swallowed so a cancelled diagnostics query is not reported
15707
+ // as an empty, fresh result.
15708
+ async ensureFresh(absFile, signal) {
15709
+ (0, cwtools_shared_1.throwIfAborted)(signal);
14386
15710
  const baseline = this.readyAt();
14387
15711
  if (baseline === void 0)
14388
15712
  return;
@@ -14393,16 +15717,17 @@ var require_revalidation = __commonJS({
14393
15717
  const uris = batch.map((c) => (0, lspProcessHost_1.pathToFileUri)(c.path));
14394
15718
  let baselineEpoch = 0;
14395
15719
  try {
14396
- const res = await this.lsp.executeCommand("cwtools.ai.revalidateFiles", [uris], { timeoutMs: 1e4 });
15720
+ const res = await this.lsp.executeCommand("cwtools.ai.revalidateFiles", [uris], { timeoutMs: 1e4, ...signal ? { signal } : {} });
14397
15721
  if (!res || res.ok !== true)
14398
15722
  return;
14399
15723
  baselineEpoch = numberOr(res.baselineEpoch, 0);
14400
- } catch {
15724
+ } catch (error) {
15725
+ (0, cwtools_shared_1.rethrowIfAborted)(error);
14401
15726
  return;
14402
15727
  }
14403
15728
  for (const c of batch)
14404
15729
  this.lastReval.set(c.path, c.mtimeMs);
14405
- await this.waitDrained(baselineEpoch);
15730
+ await this.waitDrained(baselineEpoch, signal);
14406
15731
  }
14407
15732
  changedSingle(absFile, baseline) {
14408
15733
  let mtimeMs;
@@ -14458,13 +15783,17 @@ var require_revalidation = __commonJS({
14458
15783
  }
14459
15784
  // Wait until the lint queue drains and the epoch advanced past the revalidation
14460
15785
  // baseline (so the posted re-lints have completed). Bounded; best-effort.
14461
- async waitDrained(baselineEpoch) {
15786
+ async waitDrained(baselineEpoch, signal) {
14462
15787
  const timeoutMs = 5e3;
14463
15788
  const intervalMs = 50;
14464
15789
  let elapsed = 0;
14465
15790
  await sleep(30);
14466
15791
  while (elapsed < timeoutMs) {
14467
- const s = await this.lsp.executeCommand("cwtools.ai.getValidationStatus", [], { timeoutMs: 5e3 }).catch(() => null);
15792
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15793
+ const s = await this.lsp.executeCommand("cwtools.ai.getValidationStatus", [], { timeoutMs: 5e3, ...signal ? { signal } : {} }).catch((error) => {
15794
+ (0, cwtools_shared_1.rethrowIfAborted)(error);
15795
+ return null;
15796
+ });
14468
15797
  if (!s || typeof s !== "object")
14469
15798
  return;
14470
15799
  const epoch = numberOr(s.epoch, 0);
@@ -14481,9 +15810,9 @@ var require_revalidation = __commonJS({
14481
15810
  }
14482
15811
  });
14483
15812
 
14484
- // dist/hosts/nodeHostServices.js
15813
+ // ../cwtools-node/dist/hosts/nodeHostServices.js
14485
15814
  var require_nodeHostServices = __commonJS({
14486
- "dist/hosts/nodeHostServices.js"(exports2) {
15815
+ "../cwtools-node/dist/hosts/nodeHostServices.js"(exports2) {
14487
15816
  "use strict";
14488
15817
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
14489
15818
  if (k2 === void 0) k2 = k;
@@ -14529,39 +15858,60 @@ var require_nodeHostServices = __commonJS({
14529
15858
  var path = __importStar(require("path"));
14530
15859
  var cwtools_shared_1 = require_dist();
14531
15860
  var lspProcessHost_1 = require_lspProcessHost();
15861
+ var gameInstall_1 = require_gameInstall();
14532
15862
  var projectDetect_1 = require_projectDetect();
14533
15863
  var projectSettings_1 = require_projectSettings();
14534
15864
  var revalidation_1 = require_revalidation();
14535
15865
  var vscodeCache_1 = require_vscodeCache();
14536
15866
  function createNodeHostServices(config) {
14537
- const workspaceRoot = path.resolve(config.workspaceRoot);
15867
+ const requestedWorkspaceRoot = path.resolve(config.workspaceRoot);
15868
+ const support = (0, projectDetect_1.detectProjectSupport)(requestedWorkspaceRoot, { game: config.game, gamePath: config.gamePath });
15869
+ const workspaceRoot = path.resolve(support.supported ? support.matchedAt ?? requestedWorkspaceRoot : requestedWorkspaceRoot);
15870
+ const enabled = support.supported || config.forceStart;
15871
+ const projectKind = support.supported ? support.kind : config.forceStart ? "mod" : support.kind;
15872
+ const game = support.kind === "cwt-only" ? "cwt" : config.game ?? support.gameId ?? "paradox";
15873
+ const gamePath = config.gamePath ?? (game === "paradox" || game === "cwt" ? void 0 : (0, gameInstall_1.detectGameInstall)(game));
14538
15874
  const allowlist = config.allowedTools.length > 0 ? new Set(config.allowedTools) : new Set(cwtools_shared_1.MCP_WRITE_TOOL_NAMES);
14539
15875
  const filesystem = new NodeFilesystemHost(workspaceRoot, config.enableWrites);
14540
- const support = (0, projectDetect_1.detectProjectSupport)(workspaceRoot);
14541
- const enabled = support.supported || config.forceStart;
14542
- const autoCache = config.cachePath ?? (0, vscodeCache_1.detectExtensionCacheDir)(config.game);
14543
- const detectedRulesPath = (0, vscodeCache_1.detectExtensionRulesDir)(autoCache, config.game);
15876
+ const autoCache = config.cachePath ?? (0, vscodeCache_1.detectExtensionCacheDir)(game);
15877
+ const detectedRulesPath = (0, vscodeCache_1.detectExtensionRulesDir)(autoCache, game);
14544
15878
  const rulesConfigDirs = uniqueStrings([config.rulesPath, detectedRulesPath].filter((item) => !!item));
14545
- const lspProcess = enabled ? (0, lspProcessHost_1.createLspProcessHost)({
15879
+ const lspProcess = enabled && !config.lspHost ? (0, lspProcessHost_1.createLspProcessHost)({
14546
15880
  workspaceRoot,
14547
- game: config.game,
15881
+ game,
14548
15882
  serverPath: config.serverPath,
15883
+ ...config.serverArgs === void 0 ? {} : { serverArgs: config.serverArgs },
14549
15884
  cachePath: autoCache,
14550
- gamePath: config.gamePath,
14551
- bundledRulesPath: config.rulesPath
15885
+ gamePath: game === "paradox" || game === "cwt" ? void 0 : gamePath,
15886
+ bundledRulesPath: config.rulesPath,
15887
+ ...config.errorIgnoreCodes === void 0 ? {} : { errorIgnoreCodes: config.errorIgnoreCodes },
15888
+ ...config.errorIgnoreFiles === void 0 ? {} : { errorIgnoreFiles: config.errorIgnoreFiles },
15889
+ ...config.localisationDiagnosticFilter === void 0 ? {} : { localisationDiagnosticFilter: config.localisationDiagnosticFilter },
15890
+ ...config.startupTimeoutMs === void 0 ? {} : { startupTimeoutMs: config.startupTimeoutMs },
15891
+ ...config.requestTimeoutMs === void 0 ? {} : { requestTimeoutMs: config.requestTimeoutMs },
15892
+ ...config.debug === void 0 ? {} : { debug: config.debug }
14552
15893
  }) : void 0;
14553
- const lsp = lspProcess ?? (0, cwtools_shared_1.createUnavailableLspHost)("Workspace is not a recognised Paradox mod; CWTools is disabled here.");
15894
+ const lsp = enabled ? config.lspHost ?? lspProcess ?? (0, cwtools_shared_1.createUnavailableLspHost)("Workspace is not a recognised Paradox mod; CWTools is disabled here.") : (0, cwtools_shared_1.createUnavailableLspHost)("Workspace is not a recognised Paradox mod; CWTools is disabled here.");
15895
+ const report = (message) => {
15896
+ if (config.logger)
15897
+ config.logger("info", message);
15898
+ else
15899
+ console.error(`[cwtools-node] info: ${message}`);
15900
+ };
14554
15901
  if (!enabled) {
14555
- console.error(`[cwtools-mcp] info: tool calls will be rejected (no language server) \u2014 ${support.reason} (pass --force-start to override)`);
15902
+ report(`tool calls will be rejected (no language server) \u2014 ${support.reason} (pass --force-start to override)`);
14556
15903
  } else if (!support.supported) {
14557
- console.error(`[cwtools-mcp] info: --force-start set; starting despite: ${support.reason}`);
14558
- } else if (support.matchedAt && support.matchedAt !== workspaceRoot) {
14559
- console.error(`[cwtools-mcp] info: mod detected at ${support.matchedAt} (workspace = ${workspaceRoot})`);
15904
+ report(`--force-start set; starting despite: ${support.reason}`);
15905
+ } else if (support.matchedAt && support.matchedAt !== requestedWorkspaceRoot) {
15906
+ report(`mod detected at ${support.matchedAt} (workspace = ${workspaceRoot})`);
14560
15907
  }
14561
15908
  if (enabled && !config.cachePath && autoCache) {
14562
- console.error(`[cwtools-mcp] info: auto-detected VS Code extension cache at ${autoCache}`);
15909
+ report(`auto-detected VS Code extension cache at ${autoCache}`);
14563
15910
  }
14564
- console.error(`[cwtools-mcp] info: workspace = ${workspaceRoot}${config.workspaceRoot === process.cwd() ? " (inherited cwd)" : ""}`);
15911
+ if (enabled && !config.gamePath && gamePath) {
15912
+ report(`auto-detected ${game} install at ${gamePath}`);
15913
+ }
15914
+ report(`workspace = ${workspaceRoot}${config.workspaceRoot === process.cwd() ? " (inherited cwd)" : ""}`);
14565
15915
  return {
14566
15916
  workspaceRoot,
14567
15917
  readonlyMode: !config.enableWrites,
@@ -14569,12 +15919,16 @@ var require_nodeHostServices = __commonJS({
14569
15919
  allowedWriteTools: allowlist,
14570
15920
  projectSupported: enabled,
14571
15921
  projectSupportReason: support.reason,
15922
+ projectKind,
15923
+ projectGameId: game,
15924
+ projectEvidence: [...support.markers],
15925
+ projectCandidates: support.candidates ? [...support.candidates] : void 0,
14572
15926
  lsp,
14573
- diagnostics: new LspDiagnosticsHost(lsp, workspaceRoot, lspProcess ? new revalidation_1.RevalidationCoordinator(lsp, workspaceRoot, () => lspProcess.readyAtMs) : void 0),
15927
+ diagnostics: new LspDiagnosticsHost(lsp, workspaceRoot, config.honorWorkspaceIgnoreList !== false, enabled ? new revalidation_1.RevalidationCoordinator(lsp, workspaceRoot, () => config.readyAtMs ?? lspProcess?.readyAtMs) : void 0),
14574
15928
  filesystem,
14575
15929
  indexing: new ThinNodeIndexHost(workspaceRoot),
14576
15930
  rules: {
14577
- gameId: config.game,
15931
+ gameId: game,
14578
15932
  configDirs: rulesConfigDirs,
14579
15933
  async readTextFile(filePath) {
14580
15934
  if (!fssync.existsSync(filePath))
@@ -14594,15 +15948,25 @@ var require_nodeHostServices = __commonJS({
14594
15948
  return results;
14595
15949
  }
14596
15950
  },
14597
- vanillaCache: probeVanillaCache(workspaceRoot, { ...config, cachePath: autoCache }),
15951
+ vanillaCache: game === "cwt" ? void 0 : probeVanillaCache(workspaceRoot, { game, gamePath, cachePath: autoCache, workspaceRoot }),
14598
15952
  now: () => Date.now(),
14599
15953
  log: (level, message, data) => {
14600
- if (level === "debug")
15954
+ if (level === "debug" && !config.debug)
15955
+ return;
15956
+ if (config.logger) {
15957
+ config.logger(level, message, data);
14601
15958
  return;
15959
+ }
14602
15960
  const suffix = data === void 0 ? "" : ` ${JSON.stringify(data)}`;
14603
- console.error(`[cwtools-mcp] ${level}: ${message}${suffix}`);
15961
+ console.error(`[cwtools-node] ${level}: ${message}${suffix}`);
14604
15962
  },
14605
- dispose: () => lspProcess?.dispose()
15963
+ dispose: () => {
15964
+ if (config.lspHost && "dispose" in config.lspHost && typeof config.lspHost.dispose === "function") {
15965
+ config.lspHost.dispose();
15966
+ } else {
15967
+ lspProcess?.dispose();
15968
+ }
15969
+ }
14606
15970
  };
14607
15971
  }
14608
15972
  function uniqueStrings(values) {
@@ -14622,7 +15986,7 @@ var require_nodeHostServices = __commonJS({
14622
15986
  const rulesCacheRoot = (0, lspProcessHost_1.resolveRulesCacheRoot)({ cachePath: config.cachePath, workspaceRoot });
14623
15987
  const cacheFile = cacheFileName ? path.join(rulesCacheRoot, cacheFileName) : void 0;
14624
15988
  const cacheExists = !!cacheFile && fssync.existsSync(cacheFile);
14625
- const gamePathValid = !!config.gamePath && fssync.existsSync(config.gamePath);
15989
+ const gamePathValid = !!cacheFileName && !!config.gamePath && fssync.existsSync(config.gamePath);
14626
15990
  if (cacheExists) {
14627
15991
  return { available: true, source: "mod_plus_vanilla", cacheFile, reason: "Loaded a pre-built vanilla cache." };
14628
15992
  }
@@ -14643,51 +16007,83 @@ var require_nodeHostServices = __commonJS({
14643
16007
  };
14644
16008
  }
14645
16009
  var LspDiagnosticsHost = class {
14646
- constructor(lsp, workspaceRoot, revalidation) {
16010
+ constructor(lsp, workspaceRoot, honorWorkspaceIgnoreList, revalidation) {
14647
16011
  this.lsp = lsp;
14648
16012
  this.workspaceRoot = workspaceRoot;
16013
+ this.honorWorkspaceIgnoreList = honorWorkspaceIgnoreList;
14649
16014
  this.revalidation = revalidation;
14650
16015
  }
14651
- async getDiagnostics(filter = {}) {
16016
+ async getDiagnostics(filter = {}, context) {
16017
+ (0, cwtools_shared_1.throwIfAborted)(context?.signal);
14652
16018
  if (this.revalidation) {
14653
16019
  const absFile = filter.file ? (0, cwtools_shared_1.resolveWorkspacePath)(this.workspaceRoot, filter.file).resolvedPath ?? void 0 : void 0;
14654
- await this.revalidation.ensureFresh(absFile);
16020
+ await this.revalidation.ensureFresh(absFile, context?.signal);
14655
16021
  }
14656
- return this.applyIgnoreList(await this.queryDiagnostics(filter));
16022
+ return this.applyIgnoreList(await this.queryDiagnostics(filter, context?.signal));
14657
16023
  }
14658
16024
  applyIgnoreList(result) {
14659
16025
  if (!result.ok || result.diagnostics.length === 0)
14660
16026
  return result;
14661
- return (0, projectSettings_1.applyDiagnosticIgnoreList)(result, (0, projectSettings_1.readIgnoredDiagnostics)(this.workspaceRoot));
16027
+ return (0, projectSettings_1.applyDiagnosticIgnoreList)(result, (0, projectSettings_1.honouredIgnoredDiagnostics)(this.workspaceRoot, this.honorWorkspaceIgnoreList));
14662
16028
  }
14663
- async queryDiagnostics(filter) {
16029
+ async queryDiagnostics(filter, signal) {
14664
16030
  const file = filter.file;
14665
16031
  if (file) {
14666
16032
  const resolution = (0, cwtools_shared_1.resolveWorkspacePath)(this.workspaceRoot, file);
14667
16033
  const filePath = resolution.resolvedPath ?? file;
14668
- const raw2 = asRecord(await this.lsp.executeCommand("cwtools.ai.getDiagnosticsFresh", [(0, lspProcessHost_1.pathToFileUri)(filePath)], { timeoutMs: 2e4 }));
14669
- return normalizeDiagnosticsFresh(raw2);
16034
+ if (!resolution.ok || !resolution.resolvedPath || !fssync.existsSync(filePath)) {
16035
+ return {
16036
+ ok: false,
16037
+ status: "unavailable",
16038
+ diagnostics: [],
16039
+ error: {
16040
+ code: "file_not_found",
16041
+ message: `No file at '${filePath}'. Pass an absolute path or a workspace-relative path; omit 'file' for whole-workspace diagnostics.`
16042
+ }
16043
+ };
16044
+ }
16045
+ const value2 = await this.lsp.executeCommand("cwtools.ai.getDiagnosticsFresh", [(0, lspProcessHost_1.pathToFileUri)(filePath)], { timeoutMs: 2e4, ...signal ? { signal } : {} });
16046
+ if (value2 === null || value2 === void 0)
16047
+ return pendingDiagnostics();
16048
+ return normalizeDiagnosticsFresh(asRecord(value2));
14670
16049
  }
14671
16050
  const severity = filter.severity === "information" ? "info" : filter.severity ?? "all";
14672
16051
  const limit = typeof filter.limit === "number" ? filter.limit : 1e3;
14673
- const raw = asRecord(await this.lsp.executeCommand("cwtools.ai.getAllDiagnostics", [severity, limit], { timeoutMs: 3e4 }));
16052
+ const value = await this.lsp.executeCommand("cwtools.ai.getAllDiagnostics", [severity, limit], { timeoutMs: 3e4, ...signal ? { signal } : {} });
16053
+ if (value === null || value === void 0)
16054
+ return pendingDiagnostics();
16055
+ const raw = asRecord(value);
14674
16056
  if (raw.ok === false || raw.status === "unavailable") {
14675
16057
  return unavailableDiagnostics(raw);
14676
16058
  }
16059
+ const freshness = normalizeFreshnessValue(raw.freshness);
14677
16060
  return {
14678
16061
  ok: true,
14679
- status: "fresh",
16062
+ status: freshness,
14680
16063
  diagnostics: Array.isArray(raw.diagnostics) ? raw.diagnostics.map(normalizeDiagnosticRecord) : [],
14681
16064
  totalCount: numberOrUndefined(raw.totalCount),
16065
+ errorCount: numberOrUndefined(raw.errorCount),
16066
+ warningCount: numberOrUndefined(raw.warningCount),
14682
16067
  truncated: raw.truncated === true,
14683
16068
  freshness: {
14684
- value: "fresh",
14685
- pendingKinds: [],
16069
+ value: freshness,
16070
+ pendingKinds: asStringArray(raw.pendingGlobalKinds),
14686
16071
  epoch: numberOrUndefined(raw.epoch)
14687
16072
  }
14688
16073
  };
14689
16074
  }
14690
16075
  };
16076
+ function pendingDiagnostics() {
16077
+ return {
16078
+ ok: true,
16079
+ status: "pending",
16080
+ diagnostics: [],
16081
+ freshness: { value: "pending", pendingKinds: ["game_model"] }
16082
+ };
16083
+ }
16084
+ function normalizeFreshnessValue(value) {
16085
+ return value === "fresh" || value === "pending" || value === "stale" || value === "unavailable" ? value : "fresh";
16086
+ }
14691
16087
  function normalizeDiagnosticsFresh(raw) {
14692
16088
  if (raw.ok === false || raw.status === "unavailable") {
14693
16089
  return unavailableDiagnostics(raw);
@@ -14971,6 +16367,31 @@ var require_nodeHostServices = __commonJS({
14971
16367
  }
14972
16368
  });
14973
16369
 
16370
+ // dist/hosts/nodeHostServices.js
16371
+ var require_nodeHostServices2 = __commonJS({
16372
+ "dist/hosts/nodeHostServices.js"(exports2) {
16373
+ "use strict";
16374
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
16375
+ if (k2 === void 0) k2 = k;
16376
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16377
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16378
+ desc = { enumerable: true, get: function() {
16379
+ return m[k];
16380
+ } };
16381
+ }
16382
+ Object.defineProperty(o, k2, desc);
16383
+ }) : (function(o, m, k, k2) {
16384
+ if (k2 === void 0) k2 = k;
16385
+ o[k2] = m[k];
16386
+ }));
16387
+ var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
16388
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
16389
+ };
16390
+ Object.defineProperty(exports2, "__esModule", { value: true });
16391
+ __exportStar(require_nodeHostServices(), exports2);
16392
+ }
16393
+ });
16394
+
14974
16395
  // ../../node_modules/zod/v3/helpers/util.cjs
14975
16396
  var require_util = __commonJS({
14976
16397
  "../../node_modules/zod/v3/helpers/util.cjs"(exports2) {
@@ -49724,6 +51145,31 @@ var require_server2 = __commonJS({
49724
51145
  }
49725
51146
  });
49726
51147
 
51148
+ // dist/hosts/vscodeCache.js
51149
+ var require_vscodeCache2 = __commonJS({
51150
+ "dist/hosts/vscodeCache.js"(exports2) {
51151
+ "use strict";
51152
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
51153
+ if (k2 === void 0) k2 = k;
51154
+ var desc = Object.getOwnPropertyDescriptor(m, k);
51155
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
51156
+ desc = { enumerable: true, get: function() {
51157
+ return m[k];
51158
+ } };
51159
+ }
51160
+ Object.defineProperty(o, k2, desc);
51161
+ }) : (function(o, m, k, k2) {
51162
+ if (k2 === void 0) k2 = k;
51163
+ o[k2] = m[k];
51164
+ }));
51165
+ var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
51166
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
51167
+ };
51168
+ Object.defineProperty(exports2, "__esModule", { value: true });
51169
+ __exportStar(require_vscodeCache(), exports2);
51170
+ }
51171
+ });
51172
+
49727
51173
  // dist/mcp/resources.js
49728
51174
  var require_resources = __commonJS({
49729
51175
  "dist/mcp/resources.js"(exports2) {
@@ -49820,6 +51266,11 @@ var require_resources = __commonJS({
49820
51266
  mimeType: "application/json"
49821
51267
  }
49822
51268
  ];
51269
+ if (host?.projectSupported === false)
51270
+ return [];
51271
+ if (host?.projectKind === "cwt-only") {
51272
+ return base.filter((resource) => resource.uri === "cwtools://knowledge/diagnostic-routing");
51273
+ }
49823
51274
  if (host?.workspaceRoot) {
49824
51275
  for (const skill of discoverSkills(host.workspaceRoot)) {
49825
51276
  base.push({
@@ -49833,6 +51284,17 @@ var require_resources = __commonJS({
49833
51284
  return base;
49834
51285
  }
49835
51286
  async function readResource(host, uri) {
51287
+ if (host.projectSupported === false || host.projectKind === "cwt-only" && uri !== "cwtools://knowledge/diagnostic-routing") {
51288
+ const code = host.projectKind === "ambiguous" ? "project_ambiguous" : host.projectSupported === false ? "project_not_supported" : "resource_not_available_in_cwt_only";
51289
+ return {
51290
+ contents: [{
51291
+ uri,
51292
+ mimeType: "application/json",
51293
+ text: `${JSON.stringify({ status: "error", error: { code, message: host.projectSupportReason ?? "Resource is not available for this workspace." } }, null, 2)}
51294
+ `
51295
+ }]
51296
+ };
51297
+ }
49836
51298
  if (uri.startsWith("cwtools://skills/") && uri !== "cwtools://skills/catalog") {
49837
51299
  const skillName = decodeURIComponent(uri.slice("cwtools://skills/".length));
49838
51300
  const found = discoverSkills(host.workspaceRoot).find((entry) => entry.name === skillName);
@@ -50000,44 +51462,15 @@ var require_toolHandlers2 = __commonJS({
50000
51462
  "dist/mcp/toolHandlers.js"(exports2) {
50001
51463
  "use strict";
50002
51464
  Object.defineProperty(exports2, "__esModule", { value: true });
50003
- exports2.createToolCallHandler = createToolCallHandler;
51465
+ exports2.bindToolCallHandler = exports2.createToolCallHandler = void 0;
50004
51466
  exports2.toMcpCallToolResult = toMcpCallToolResult;
50005
51467
  var cwtools_shared_1 = require_dist();
50006
- function createToolCallHandler(host, dispatcher = cwtools_shared_1.defaultSharedToolDispatcher) {
50007
- let ready = false;
50008
- const probeReadiness = async () => {
50009
- if (ready)
50010
- return { ready: true };
50011
- try {
50012
- const status = await host.lsp.executeCommand("cwtools.ai.getValidationStatus", [], { timeoutMs: 8e3 });
50013
- const verdict = (0, cwtools_shared_1.parseReadiness)(status);
50014
- if (verdict.ready)
50015
- ready = true;
50016
- return verdict;
50017
- } catch {
50018
- return { ready: false, reason: "lsp_unavailable" };
50019
- }
50020
- };
50021
- return async (name, args = {}) => {
50022
- const writesEnabled = host.writesEnabled === true && host.readonlyMode === false;
50023
- if (!(0, cwtools_shared_1.isMcpToolName)(name, { includeWrites: writesEnabled })) {
50024
- return {
50025
- ok: false,
50026
- status: "denied",
50027
- source: "cwtools-mcp",
50028
- error: {
50029
- code: "tool_not_available",
50030
- message: `Tool '${name}' is not available: this MCP server is read-only unless started with --allow-domain-writes (or --enable-writes).`
50031
- }
50032
- };
50033
- }
50034
- const result = await dispatcher(host, name, args);
50035
- const withVanilla = (0, cwtools_shared_1.annotateVanillaCache)(name, result, host.vanillaCache);
50036
- if (!cwtools_shared_1.LOAD_DEPENDENT_TOOLS.has(name))
50037
- return withVanilla;
50038
- return (0, cwtools_shared_1.annotateReadiness)(name, withVanilla, await probeReadiness());
50039
- };
50040
- }
51468
+ Object.defineProperty(exports2, "createToolCallHandler", { enumerable: true, get: function() {
51469
+ return cwtools_shared_1.createToolCallHandler;
51470
+ } });
51471
+ Object.defineProperty(exports2, "bindToolCallHandler", { enumerable: true, get: function() {
51472
+ return cwtools_shared_1.bindToolCallHandler;
51473
+ } });
50041
51474
  function toMcpCallToolResult(result) {
50042
51475
  return {
50043
51476
  content: [
@@ -50095,6 +51528,9 @@ var require_bridgeProxy = __commonJS({
50095
51528
  };
50096
51529
  })();
50097
51530
  Object.defineProperty(exports2, "__esModule", { value: true });
51531
+ exports2.fallbackBridgeTools = fallbackBridgeTools;
51532
+ exports2.fallbackBridgeResources = fallbackBridgeResources;
51533
+ exports2.localBridgeToolDenied = localBridgeToolDenied;
50098
51534
  exports2.createBridgeProxyMcpServer = createBridgeProxyMcpServer;
50099
51535
  exports2.assertBridgeWorkspaceMatches = assertBridgeWorkspaceMatches;
50100
51536
  var fs = __importStar(require("fs"));
@@ -50102,12 +51538,37 @@ var require_bridgeProxy = __commonJS({
50102
51538
  var url_1 = require("url");
50103
51539
  var index_js_1 = require_server2();
50104
51540
  var types_js_1 = require_types2();
50105
- var vscodeCache_1 = require_vscodeCache();
51541
+ var cwtools_shared_1 = require_dist();
51542
+ var vscodeCache_1 = require_vscodeCache2();
50106
51543
  var resources_1 = require_resources();
50107
51544
  var toolRegistrar_1 = require_toolRegistrar();
50108
51545
  var toolHandlers_1 = require_toolHandlers2();
50109
51546
  var BRIDGE_MANIFEST_FILE = "bridge-manifest.json";
50110
51547
  var BRIDGE_PROTOCOL_VERSION = 1;
51548
+ function fallbackBridgeTools(project, includeWrites) {
51549
+ if (project.kind === "unsupported" || project.kind === "ambiguous")
51550
+ return [];
51551
+ return (0, toolRegistrar_1.listRegisteredTools)({ includeWrites, cwtOnly: project.kind === "cwt-only" });
51552
+ }
51553
+ function fallbackBridgeResources(project) {
51554
+ if (project.kind === "unsupported" || project.kind === "ambiguous")
51555
+ return [];
51556
+ const resources = (0, resources_1.listResources)();
51557
+ return project.kind === "cwt-only" ? resources.filter((resource) => resource.uri === "cwtools://knowledge/diagnostic-routing") : resources;
51558
+ }
51559
+ function localBridgeToolDenied(project, name) {
51560
+ if (project.kind !== "unsupported" && project.kind !== "ambiguous" && (project.kind !== "cwt-only" || fallbackBridgeTools(project, true).some((tool) => tool.name === name)))
51561
+ return void 0;
51562
+ return {
51563
+ ok: false,
51564
+ status: "denied",
51565
+ source: "cwtools-mcp-bridge-proxy",
51566
+ error: {
51567
+ code: project.kind === "ambiguous" ? "project_ambiguous" : project.kind === "unsupported" ? "project_not_supported" : "tool_not_available_in_cwt_only",
51568
+ message: project.kind === "cwt-only" ? `Tool '${name}' requires a full Paradox game model and is not available in a CWT-only workspace.` : project.reason
51569
+ }
51570
+ };
51571
+ }
50111
51572
  function createBridgeProxyMcpServer(config) {
50112
51573
  const server = new index_js_1.Server({
50113
51574
  name: "cwtools-mcp",
@@ -50126,25 +51587,65 @@ var require_bridgeProxy = __commonJS({
50126
51587
  });
50127
51588
  server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => {
50128
51589
  try {
51590
+ const manifest = await readBridgeManifest(config, server);
51591
+ if (!manifest.project) {
51592
+ const project = await detectProxyWorkspace(config, server);
51593
+ return { tools: fallbackBridgeTools(project, config.enableWrites) };
51594
+ }
50129
51595
  return await bridgeRpc(config, server, "tools/list", {
50130
51596
  allowDomainWrites: config.enableWrites
50131
- });
51597
+ }, manifest);
50132
51598
  } catch {
50133
- return { tools: (0, toolRegistrar_1.listRegisteredTools)({ includeWrites: config.enableWrites }) };
51599
+ try {
51600
+ const project = await detectProxyWorkspace(config, server);
51601
+ return { tools: fallbackBridgeTools(project, config.enableWrites) };
51602
+ } catch {
51603
+ return { tools: [] };
51604
+ }
50134
51605
  }
50135
51606
  });
50136
51607
  server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => {
50137
51608
  try {
50138
- return await bridgeRpc(config, server, "resources/list", {});
51609
+ const manifest = await readBridgeManifest(config, server);
51610
+ if (!manifest.project) {
51611
+ const project = await detectProxyWorkspace(config, server);
51612
+ return { resources: fallbackBridgeResources(project) };
51613
+ }
51614
+ return await bridgeRpc(config, server, "resources/list", {}, manifest);
50139
51615
  } catch {
50140
- return { resources: (0, resources_1.listResources)() };
51616
+ try {
51617
+ const project = await detectProxyWorkspace(config, server);
51618
+ return { resources: fallbackBridgeResources(project) };
51619
+ } catch {
51620
+ return { resources: [] };
51621
+ }
50141
51622
  }
50142
51623
  });
50143
51624
  server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
50144
51625
  try {
51626
+ const manifest = await readBridgeManifest(config, server);
51627
+ if (!manifest.project) {
51628
+ const project = await detectProxyWorkspace(config, server);
51629
+ if (!fallbackBridgeResources(project).some((resource) => resource.uri === request.params.uri)) {
51630
+ return {
51631
+ contents: [{
51632
+ uri: request.params.uri,
51633
+ mimeType: "application/json",
51634
+ text: `${JSON.stringify({
51635
+ status: "error",
51636
+ error: {
51637
+ code: project.kind === "ambiguous" ? "project_ambiguous" : project.kind === "unsupported" ? "project_not_supported" : "resource_not_available_in_cwt_only",
51638
+ message: project.reason
51639
+ }
51640
+ }, null, 2)}
51641
+ `
51642
+ }]
51643
+ };
51644
+ }
51645
+ }
50145
51646
  return await bridgeRpc(config, server, "resources/read", {
50146
51647
  uri: request.params.uri
50147
- });
51648
+ }, manifest);
50148
51649
  } catch (error) {
50149
51650
  return {
50150
51651
  contents: [
@@ -50161,20 +51662,34 @@ var require_bridgeProxy = __commonJS({
50161
51662
  server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
50162
51663
  try {
50163
51664
  const args = request.params.arguments && typeof request.params.arguments === "object" ? request.params.arguments : {};
51665
+ const manifest = await readBridgeManifest(config, server);
51666
+ if (!manifest.project) {
51667
+ const project = await detectProxyWorkspace(config, server);
51668
+ const denied = localBridgeToolDenied(project, request.params.name);
51669
+ if (denied)
51670
+ return (0, toolHandlers_1.toMcpCallToolResult)(denied);
51671
+ }
50164
51672
  const result = await bridgeRpc(config, server, "tools/call", {
50165
51673
  name: request.params.name,
50166
51674
  arguments: args,
50167
51675
  allowDomainWrites: config.enableWrites
50168
- });
51676
+ }, manifest);
50169
51677
  return normalizeCallToolResult(result);
50170
51678
  } catch (error) {
51679
+ try {
51680
+ const project = await detectProxyWorkspace(config, server);
51681
+ const denied = localBridgeToolDenied(project, request.params.name);
51682
+ if (denied)
51683
+ return (0, toolHandlers_1.toMcpCallToolResult)(denied);
51684
+ } catch {
51685
+ }
50171
51686
  return (0, toolHandlers_1.toMcpCallToolResult)(unavailableResult(error));
50172
51687
  }
50173
51688
  });
50174
51689
  return server;
50175
51690
  }
50176
- async function bridgeRpc(config, server, method, params) {
50177
- const manifest = await readBridgeManifest(config, server);
51691
+ async function bridgeRpc(config, server, method, params, knownManifest) {
51692
+ const manifest = knownManifest ?? await readBridgeManifest(config, server);
50178
51693
  const controller = new AbortController();
50179
51694
  const timer = setTimeout(() => controller.abort(), 3e4);
50180
51695
  try {
@@ -50236,6 +51751,19 @@ var require_bridgeProxy = __commonJS({
50236
51751
  }
50237
51752
  return { roots: [config.workspaceRoot], source: "MCP process cwd" };
50238
51753
  }
51754
+ async function detectProxyWorkspace(config, server) {
51755
+ const expected = await resolveExpectedWorkspace(config, server);
51756
+ if (expected.roots.length > 1) {
51757
+ return {
51758
+ kind: "ambiguous",
51759
+ strength: "none",
51760
+ evidence: [],
51761
+ candidates: [...expected.roots].sort(),
51762
+ reason: `Multiple MCP workspace roots are ambiguous for the CWTools bridge: ${expected.roots.join(", ")}`
51763
+ };
51764
+ }
51765
+ return (0, cwtools_shared_1.detectWorkspaceProject)(expected.roots[0] ?? config.workspaceRoot, () => void 0);
51766
+ }
50239
51767
  async function readClientWorkspaceRoots(server) {
50240
51768
  if (!server.getClientCapabilities()?.roots)
50241
51769
  return [];
@@ -52842,14 +54370,15 @@ var require_server3 = __commonJS({
52842
54370
  "dist/server.js"(exports2) {
52843
54371
  "use strict";
52844
54372
  Object.defineProperty(exports2, "__esModule", { value: true });
54373
+ exports2.listServerTools = listServerTools;
52845
54374
  exports2.createCwtoolsMcpServer = createCwtoolsMcpServer;
52846
54375
  var index_js_1 = require_server2();
52847
54376
  var types_js_1 = require_types2();
52848
54377
  var toolRegistrar_1 = require_toolRegistrar();
52849
54378
  var toolHandlers_1 = require_toolHandlers2();
52850
54379
  var resources_1 = require_resources();
52851
- var SERVER_INSTRUCTIONS = [
52852
- "CWTools is a read-only semantic service for Paradox mods. Ground every",
54380
+ var FULL_SERVER_INSTRUCTIONS = [
54381
+ "CWTools provides semantic and whitelisted domain-write tools for Paradox mods. Ground every",
52853
54382
  "claim about the mod in these tools instead of memory \u2014 PDX identifiers and syntax",
52854
54383
  "are routinely hallucinated.",
52855
54384
  "",
@@ -52872,9 +54401,31 @@ var require_server3 = __commonJS({
52872
54401
  "- Results carry vanillaCache metadata: if available is false, vanilla IDs are missing",
52873
54402
  " and references to them may show as false errors.",
52874
54403
  "",
52875
- "This server never writes files \u2014 perform edits with your own environment, then",
52876
- "re-check with get_diagnostics."
54404
+ "Use only the exposed whitelisted domain-write tools for writes, then re-check",
54405
+ "with get_diagnostics. Non-whitelisted writes remain unavailable."
52877
54406
  ].join("\n");
54407
+ function serverInstructions(host) {
54408
+ if (host.projectSupported === false) {
54409
+ return `CWTools is unavailable for this workspace: ${host.projectSupportReason ?? "not a Paradox/CWT project."}`;
54410
+ }
54411
+ if (host.projectKind === "cwt-only") {
54412
+ return "CWTools is running in CWT-only mode. Use the exposed document, navigation, and diagnostics tools for CWT rules; no game model is loaded.";
54413
+ }
54414
+ if (host.projectGameId === "paradox") {
54415
+ return `${FULL_SERVER_INSTRUCTIONS}
54416
+
54417
+ The exact game is unknown. Generic Paradox mode is active; no game-specific rules or vanilla cache are assumed. Pass --game to enable a specific game model.`;
54418
+ }
54419
+ return FULL_SERVER_INSTRUCTIONS;
54420
+ }
54421
+ function listServerTools(host) {
54422
+ if (host.projectSupported === false || host.projectKind === "unsupported" || host.projectKind === "ambiguous")
54423
+ return [];
54424
+ return (0, toolRegistrar_1.listRegisteredTools)({
54425
+ includeWrites: host.writesEnabled === true && host.readonlyMode === false,
54426
+ cwtOnly: host.projectKind === "cwt-only"
54427
+ });
54428
+ }
52878
54429
  function createCwtoolsMcpServer(host, options = {}) {
52879
54430
  const supported = host.projectSupported !== false;
52880
54431
  const server = new index_js_1.Server({
@@ -52885,12 +54436,10 @@ var require_server3 = __commonJS({
52885
54436
  resources: {},
52886
54437
  tools: {}
52887
54438
  },
52888
- instructions: SERVER_INSTRUCTIONS
54439
+ instructions: serverInstructions(host)
52889
54440
  });
52890
54441
  const callTool = (0, toolHandlers_1.createToolCallHandler)(host, options.dispatcher);
52891
- server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
52892
- tools: (0, toolRegistrar_1.listRegisteredTools)({ includeWrites: host.writesEnabled === true && host.readonlyMode === false })
52893
- }));
54442
+ server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({ tools: listServerTools(host) }));
52894
54443
  server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => ({
52895
54444
  resources: (0, resources_1.listResources)(host)
52896
54445
  }));
@@ -52902,8 +54451,8 @@ var require_server3 = __commonJS({
52902
54451
  status: "denied",
52903
54452
  source: "cwtools-mcp",
52904
54453
  error: {
52905
- code: "project_not_supported",
52906
- message: `CWTools is disabled for this workspace (${host.workspaceRoot}): ${host.projectSupportReason ?? "not a Paradox mod."} If this IS a mod, point the server at the mod root \u2014 set the working directory (or pass --workspace <mod>) \u2014 or pass --force-start to override.`
54454
+ code: host.projectKind === "ambiguous" ? "project_ambiguous" : "project_not_supported",
54455
+ message: `CWTools is disabled for this workspace (${host.workspaceRoot}): ${host.projectSupportReason ?? "not a Paradox/CWT project."} If this IS a mod, point the server at the mod root \u2014 set the working directory (or pass --workspace <mod>) \u2014 or pass --force-start to override.`
52907
54456
  }
52908
54457
  });
52909
54458
  }
@@ -52919,7 +54468,7 @@ var require_server3 = __commonJS({
52919
54468
  // dist/cli.js
52920
54469
  Object.defineProperty(exports, "__esModule", { value: true });
52921
54470
  var config_1 = require_config();
52922
- var nodeHostServices_1 = require_nodeHostServices();
54471
+ var nodeHostServices_1 = require_nodeHostServices2();
52923
54472
  var bridgeProxy_1 = require_bridgeProxy();
52924
54473
  var transportHttp_1 = require_transportHttp();
52925
54474
  var transportStdio_1 = require_transportStdio();