cwtools-mcp 0.2.9 → 0.4.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,7 +503,8 @@ 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
  {
@@ -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
  {
@@ -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]);
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}`);
4595
5086
  }
4596
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." };
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() {
@@ -4766,7 +5487,7 @@ var require_vanillaCache = __commonJS({
4766
5487
  vic3: "vic3"
4767
5488
  };
4768
5489
  function vanillaCacheFileName(game) {
4769
- const prefix = GAME_CACHE_PREFIX[(game ?? "stellaris").toLowerCase()];
5490
+ const prefix = game ? GAME_CACHE_PREFIX[game.toLowerCase()] : void 0;
4770
5491
  return prefix ? `${prefix}.cwb` : void 0;
4771
5492
  }
4772
5493
  exports2.VANILLA_DEPENDENT_TOOLS = /* @__PURE__ */ new Set([
@@ -7047,7 +7768,7 @@ var require_names = __commonJS({
7047
7768
  function isMcpToolName(value, options) {
7048
7769
  if (exports2.MCP_READONLY_TOOL_NAMES.includes(value))
7049
7770
  return true;
7050
- if (options?.includeWrites && exports2.MCP_WRITE_TOOL_NAMES.includes(value))
7771
+ if (options?.includeWrites !== false && exports2.MCP_WRITE_TOOL_NAMES.includes(value))
7051
7772
  return true;
7052
7773
  return false;
7053
7774
  }
@@ -7191,8 +7912,12 @@ var require_mcpSchema = __commonJS({
7191
7912
  "../cwtools-shared/dist/tools/mcpSchema.js"(exports2) {
7192
7913
  "use strict";
7193
7914
  Object.defineProperty(exports2, "__esModule", { value: true });
7915
+ exports2.listCwtoolsToolSchemas = void 0;
7194
7916
  exports2.getGeneratedMcpTools = getGeneratedMcpTools;
7195
7917
  exports2.listMcpToolSchemas = listMcpToolSchemas;
7918
+ exports2.isMcpToolAvailable = isMcpToolAvailable;
7919
+ exports2.isCwtoolsToolAvailable = isCwtoolsToolAvailable;
7920
+ exports2.getCwtoolsToolSchema = getCwtoolsToolSchema;
7196
7921
  exports2.getMcpToolSchema = getMcpToolSchema;
7197
7922
  exports2.getMcpToolRegistryMetadata = getMcpToolRegistryMetadata;
7198
7923
  var mcpTools_1 = require_mcpTools();
@@ -7201,8 +7926,23 @@ var require_mcpSchema = __commonJS({
7201
7926
  return mcpTools_1.GENERATED_MCP_TOOLS;
7202
7927
  }
7203
7928
  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 }));
7929
+ const includeWrites = options?.includeWrites !== false;
7930
+ const cwtOnly = options?.cwtOnly === true;
7931
+ return mcpTools_1.GENERATED_MCP_TOOLS.filter((entry) => (includeWrites || !(0, names_1.isMcpWriteToolName)(entry.tool.name)) && (!cwtOnly || entry.registry.mcpSupportsCwtOnly)).map((entry) => ({ ...entry.tool }));
7932
+ }
7933
+ function isMcpToolAvailable(value, options) {
7934
+ if (!(0, names_1.isMcpToolName)(value, options))
7935
+ return false;
7936
+ if (!options?.cwtOnly)
7937
+ return true;
7938
+ return mcpTools_1.GENERATED_MCP_TOOLS.find((entry) => entry.tool.name === value)?.registry.mcpSupportsCwtOnly === true;
7939
+ }
7940
+ exports2.listCwtoolsToolSchemas = listMcpToolSchemas;
7941
+ function isCwtoolsToolAvailable(value, options) {
7942
+ return isMcpToolAvailable(value, options);
7943
+ }
7944
+ function getCwtoolsToolSchema(name) {
7945
+ return getMcpToolSchema(name);
7206
7946
  }
7207
7947
  function getMcpToolSchema(name) {
7208
7948
  return mcpTools_1.GENERATED_MCP_TOOLS.find((entry) => entry.tool.name === name)?.tool;
@@ -7978,11 +8718,322 @@ var require_pdxBlock = __commonJS({
7978
8718
  }
7979
8719
  });
7980
8720
 
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 });
8721
+ // ../cwtools-shared/dist/tools/targetingWeights.js
8722
+ var require_targetingWeights = __commonJS({
8723
+ "../cwtools-shared/dist/tools/targetingWeights.js"(exports2) {
8724
+ "use strict";
8725
+ Object.defineProperty(exports2, "__esModule", { value: true });
8726
+ exports2.VANILLA_TARGETING_DEFINES = void 0;
8727
+ exports2.computeTargetingChain = computeTargetingChain;
8728
+ exports2.executeTargetingWeightQuery = executeTargetingWeightQuery;
8729
+ exports2.parseTargetingChainInput = parseTargetingChainInput;
8730
+ exports2.VANILLA_TARGETING_DEFINES = {
8731
+ sizeSlope: 0.03,
8732
+ sizeMax: 10,
8733
+ trackingMult: 2,
8734
+ evasionWeight: 2,
8735
+ lowHealthThreshold: 0.5,
8736
+ lowHealthWeight: 1.5,
8737
+ distanceWeight: 2e-3,
8738
+ distanceWeightMin: 0.1,
8739
+ unarmedWeight: 5e-3,
8740
+ starbaseWeight: 0.75,
8741
+ avoidMinShipSize: 8,
8742
+ avoidThreshold: 0.7,
8743
+ randomWeight: 3,
8744
+ currentTargetMultiplier: 1.1,
8745
+ recentTargetPenalizer: 0.3
8746
+ };
8747
+ var MAX_DAMAGE_SCALING = 100;
8748
+ function clamp(value, min, max) {
8749
+ return value < min ? min : value > max ? max : value;
8750
+ }
8751
+ function resolveDefines(partial) {
8752
+ const merged = { ...exports2.VANILLA_TARGETING_DEFINES };
8753
+ if (!partial) {
8754
+ return merged;
8755
+ }
8756
+ for (const key of Object.keys(exports2.VANILLA_TARGETING_DEFINES)) {
8757
+ const value = partial[key];
8758
+ if (typeof value === "number" && Number.isFinite(value)) {
8759
+ merged[key] = value;
8760
+ }
8761
+ }
8762
+ return merged;
8763
+ }
8764
+ function computeTargetingChain(input) {
8765
+ const defs = resolveDefines(input.defines);
8766
+ const attacker = input.attacker;
8767
+ const weapon = input.weapon;
8768
+ const target = input.target;
8769
+ const sizeCapped = Math.min(target.sizeMultiplier, defs.sizeMax);
8770
+ const W1 = 1 / (1 + sizeCapped * defs.sizeSlope);
8771
+ const shipTracking = attacker.tracking * defs.trackingMult;
8772
+ const evasionDelta = target.evasion - shipTracking;
8773
+ const vetoCheck = {
8774
+ evasionDeltaPositive: evasionDelta > 0,
8775
+ attackerSizeLargeEnough: attacker.sizeMultiplier >= defs.avoidMinShipSize,
8776
+ deltaAboveThreshold: evasionDelta >= defs.avoidThreshold,
8777
+ fleetHasHittable: input.fleetHasHittable === true
8778
+ };
8779
+ const veto = vetoCheck.evasionDeltaPositive && vetoCheck.attackerSizeLargeEnough && vetoCheck.deltaAboveThreshold && vetoCheck.fleetHasHittable;
8780
+ const evasionFactor = evasionDelta > 0 ? 1 / (1 + evasionDelta * defs.evasionWeight) : 1;
8781
+ const distanceFactor = Math.max(1 - target.distance * defs.distanceWeight, defs.distanceWeightMin);
8782
+ const targetWeight = 1 + (input.rho ?? 0) + (input.targetWeightMultModifier ?? 0);
8783
+ const maxHull = target.maxHull;
8784
+ const hasHealthRatio = typeof maxHull === "number" && Number.isFinite(maxHull) && maxHull > 0;
8785
+ const healthRatio = hasHealthRatio ? clamp(target.hull / maxHull, 0, 1) : null;
8786
+ const lowHealthFactor = healthRatio !== null && healthRatio < defs.lowHealthThreshold ? defs.lowHealthWeight : 1;
8787
+ const unarmedFactor = target.armed ? 1 : defs.unarmedWeight;
8788
+ const starbaseFactor = target.isStarbase === true && target.isCurrentMainTarget !== true ? defs.starbaseWeight : 1;
8789
+ const randomRoll = clamp(input.randomRoll ?? 0, 0, 1);
8790
+ const randomFactor = input.useRandom === true ? 1 + randomRoll * defs.randomWeight : 1;
8791
+ const W2 = veto ? 0 : W1 * evasionFactor;
8792
+ const W3 = veto ? 0 : W2 * distanceFactor;
8793
+ const W4 = veto ? 0 : W3 * targetWeight;
8794
+ const W5 = veto ? 0 : W4 * lowHealthFactor * unarmedFactor * starbaseFactor;
8795
+ const W6 = veto ? 0 : W5 * randomFactor;
8796
+ const shipChain = {
8797
+ veto,
8798
+ vetoCheck,
8799
+ sizeCapped,
8800
+ W1,
8801
+ shipTracking,
8802
+ evasionDelta,
8803
+ evasionFactor,
8804
+ W2,
8805
+ distanceFactor,
8806
+ W3,
8807
+ targetWeight,
8808
+ W4,
8809
+ lowHealthFactor,
8810
+ unarmedFactor,
8811
+ starbaseFactor,
8812
+ W5,
8813
+ randomFactor,
8814
+ W6,
8815
+ weight: W6
8816
+ };
8817
+ const baseDamage = (weapon.minDamage + weapon.maxDamage) / 2;
8818
+ const sizeFactor = weapon.sizeDamageFactor ?? 0;
8819
+ const scaledDamage = sizeFactor > 0 ? baseDamage * (1 + clamp(target.sizeMultiplier, 1, MAX_DAMAGE_SCALING) * sizeFactor) : baseDamage;
8820
+ let remaining = scaledDamage;
8821
+ let Ds = 0;
8822
+ let Da = 0;
8823
+ if (target.shield > 0) {
8824
+ const s = clamp((weapon.shieldPenetration ?? 0) - (target.shieldHardening ?? 0), 0, 1);
8825
+ const Cs = (1 - s) * remaining;
8826
+ remaining -= Math.min(Cs, target.shield);
8827
+ Ds = weapon.shieldDamage * Cs;
8828
+ }
8829
+ if (target.armor > 0) {
8830
+ const a = clamp((weapon.armorPenetration ?? 0) - (target.armorHardening ?? 0), 0, 1);
8831
+ const Ca = (1 - a) * remaining;
8832
+ remaining -= Math.min(Ca, target.armor);
8833
+ Da = weapon.armorDamage * Ca;
8834
+ }
8835
+ const Dh = weapon.hullDamage * remaining;
8836
+ const p = clamp(weapon.accuracy - clamp(target.evasion - weapon.tracking, 0, 1), 0, 1);
8837
+ const sumD = Ds + Da + Dh;
8838
+ const S0 = sumD * p * targetWeight;
8839
+ const killBonus = Dh >= target.hull ? 1.5 : 1;
8840
+ const S1 = S0 * killBonus;
8841
+ const unarmedPenalty = target.armed ? 1 : defs.unarmedWeight;
8842
+ const S2 = S1 * unarmedPenalty;
8843
+ const wk = target.shipSizeId !== void 0 ? weapon.targetWeights?.[target.shipSizeId] ?? 0 : 0;
8844
+ const score = S2 + wk;
8845
+ const currentTargetMultiplier = target.isCurrentMainTarget === true && input.targetFocus !== true ? defs.currentTargetMultiplier : 1;
8846
+ const recentTargetPenalizer = target.isRecentNonLatest === true ? defs.recentTargetPenalizer : 1;
8847
+ const weaponLayer = {
8848
+ p,
8849
+ baseDamage,
8850
+ damageSplit: { Ds, Da, Dh },
8851
+ sumD,
8852
+ S0,
8853
+ killBonus,
8854
+ S1,
8855
+ unarmedPenalty,
8856
+ S2,
8857
+ wk,
8858
+ score,
8859
+ currentTargetMultiplier,
8860
+ recentTargetPenalizer,
8861
+ final: score * currentTargetMultiplier * recentTargetPenalizer
8862
+ };
8863
+ const notes = buildNotes(input, defs, shipChain, weaponLayer, healthRatio !== null);
8864
+ return { veto, shipChain, weapon: weaponLayer, defines: defs, notes };
8865
+ }
8866
+ function buildNotes(input, defs, shipChain, weaponLayer, hasHealthRatio) {
8867
+ const notes = [];
8868
+ 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");
8869
+ 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");
8870
+ if (shipChain.veto) {
8871
+ 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");
8872
+ }
8873
+ if (shipChain.evasionDelta <= 0) {
8874
+ 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");
8875
+ }
8876
+ if (shipChain.distanceFactor === defs.distanceWeightMin) {
8877
+ 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`);
8878
+ }
8879
+ if (input.randomRoll === void 0 && input.useRandom !== true) {
8880
+ 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`);
8881
+ }
8882
+ if (!hasHealthRatio) {
8883
+ 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");
8884
+ }
8885
+ if (weaponLayer.damageSplit.Ds > 0 || weaponLayer.damageSplit.Da > 0) {
8886
+ 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");
8887
+ }
8888
+ if (weaponLayer.killBonus > 1) {
8889
+ 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");
8890
+ }
8891
+ if (weaponLayer.wk > 0) {
8892
+ 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");
8893
+ }
8894
+ if (input.rho !== void 0 && input.rho > 0) {
8895
+ 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");
8896
+ }
8897
+ 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");
8898
+ return notes;
8899
+ }
8900
+ function executeTargetingWeightQuery(args) {
8901
+ let input;
8902
+ try {
8903
+ input = parseTargetingChainInput(args);
8904
+ } catch (error) {
8905
+ return {
8906
+ error: `query_targeting_weight: ${error instanceof Error ? error.message : String(error)}`,
8907
+ hint: "Pass numeric attacker/weapon/target fields; every field must be a finite number."
8908
+ };
8909
+ }
8910
+ return computeTargetingChain(input);
8911
+ }
8912
+ function isRecord(value) {
8913
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8914
+ }
8915
+ function requireNumber(source, key, path) {
8916
+ const value = source[key];
8917
+ if (typeof value !== "number" || !Number.isFinite(value)) {
8918
+ throw new Error(`${path}.${key} must be a finite number.`);
8919
+ }
8920
+ return value;
8921
+ }
8922
+ function optionalNumber(source, key, path) {
8923
+ const value = source[key];
8924
+ if (value === void 0 || value === null) {
8925
+ return void 0;
8926
+ }
8927
+ if (typeof value !== "number" || !Number.isFinite(value)) {
8928
+ throw new Error(`${path}.${key} must be a finite number when provided.`);
8929
+ }
8930
+ return value;
8931
+ }
8932
+ function requireBoolean(source, key, path) {
8933
+ const value = source[key];
8934
+ if (typeof value !== "boolean") {
8935
+ throw new Error(`${path}.${key} must be a boolean.`);
8936
+ }
8937
+ return value;
8938
+ }
8939
+ function optionalBoolean(source, key, path) {
8940
+ const value = source[key];
8941
+ if (value === void 0 || value === null) {
8942
+ return void 0;
8943
+ }
8944
+ if (typeof value !== "boolean") {
8945
+ throw new Error(`${path}.${key} must be a boolean when provided.`);
8946
+ }
8947
+ return value;
8948
+ }
8949
+ function optionalNumberRecord(source, key, path) {
8950
+ const value = source[key];
8951
+ if (value === void 0 || value === null) {
8952
+ return void 0;
8953
+ }
8954
+ if (!isRecord(value)) {
8955
+ throw new Error(`${path}.${key} must be an object mapping ship_size id to number.`);
8956
+ }
8957
+ const out = {};
8958
+ for (const [entryKey, entryValue] of Object.entries(value)) {
8959
+ if (typeof entryValue !== "number" || !Number.isFinite(entryValue)) {
8960
+ throw new Error(`${path}.${key}.${entryKey} must be a finite number.`);
8961
+ }
8962
+ out[entryKey] = entryValue;
8963
+ }
8964
+ return out;
8965
+ }
8966
+ function parseTargetingChainInput(args) {
8967
+ if (!isRecord(args)) {
8968
+ throw new Error("arguments must be an object.");
8969
+ }
8970
+ const attackerRaw = args.attacker;
8971
+ const weaponRaw = args.weapon;
8972
+ const targetRaw = args.target;
8973
+ if (!isRecord(attackerRaw) || !isRecord(weaponRaw) || !isRecord(targetRaw)) {
8974
+ throw new Error("attacker, weapon and target must all be objects.");
8975
+ }
8976
+ const definesRaw = args.defines;
8977
+ let defines;
8978
+ if (definesRaw !== void 0 && definesRaw !== null) {
8979
+ if (!isRecord(definesRaw)) {
8980
+ throw new Error("defines must be an object when provided.");
8981
+ }
8982
+ defines = {};
8983
+ for (const key of Object.keys(exports2.VANILLA_TARGETING_DEFINES)) {
8984
+ const value = optionalNumber(definesRaw, key, "defines");
8985
+ if (value !== void 0) {
8986
+ defines[key] = value;
8987
+ }
8988
+ }
8989
+ }
8990
+ const shipSizeIdRaw = targetRaw.shipSizeId;
8991
+ if (shipSizeIdRaw !== void 0 && shipSizeIdRaw !== null && typeof shipSizeIdRaw !== "string") {
8992
+ throw new Error("target.shipSizeId must be a string when provided.");
8993
+ }
8994
+ return {
8995
+ attacker: {
8996
+ tracking: requireNumber(attackerRaw, "tracking", "attacker"),
8997
+ sizeMultiplier: requireNumber(attackerRaw, "sizeMultiplier", "attacker")
8998
+ },
8999
+ weapon: {
9000
+ minDamage: requireNumber(weaponRaw, "minDamage", "weapon"),
9001
+ maxDamage: requireNumber(weaponRaw, "maxDamage", "weapon"),
9002
+ accuracy: requireNumber(weaponRaw, "accuracy", "weapon"),
9003
+ tracking: requireNumber(weaponRaw, "tracking", "weapon"),
9004
+ shieldDamage: requireNumber(weaponRaw, "shieldDamage", "weapon"),
9005
+ armorDamage: requireNumber(weaponRaw, "armorDamage", "weapon"),
9006
+ hullDamage: requireNumber(weaponRaw, "hullDamage", "weapon"),
9007
+ shieldPenetration: optionalNumber(weaponRaw, "shieldPenetration", "weapon"),
9008
+ armorPenetration: optionalNumber(weaponRaw, "armorPenetration", "weapon"),
9009
+ sizeDamageFactor: optionalNumber(weaponRaw, "sizeDamageFactor", "weapon"),
9010
+ targetWeights: optionalNumberRecord(weaponRaw, "targetWeights", "weapon")
9011
+ },
9012
+ target: {
9013
+ shipSizeId: shipSizeIdRaw === null ? void 0 : shipSizeIdRaw,
9014
+ sizeMultiplier: requireNumber(targetRaw, "sizeMultiplier", "target"),
9015
+ evasion: requireNumber(targetRaw, "evasion", "target"),
9016
+ distance: requireNumber(targetRaw, "distance", "target"),
9017
+ hull: requireNumber(targetRaw, "hull", "target"),
9018
+ maxHull: optionalNumber(targetRaw, "maxHull", "target"),
9019
+ shield: requireNumber(targetRaw, "shield", "target"),
9020
+ armor: requireNumber(targetRaw, "armor", "target"),
9021
+ shieldHardening: optionalNumber(targetRaw, "shieldHardening", "target"),
9022
+ armorHardening: optionalNumber(targetRaw, "armorHardening", "target"),
9023
+ armed: requireBoolean(targetRaw, "armed", "target"),
9024
+ isStarbase: optionalBoolean(targetRaw, "isStarbase", "target"),
9025
+ isCurrentMainTarget: optionalBoolean(targetRaw, "isCurrentMainTarget", "target"),
9026
+ isRecentNonLatest: optionalBoolean(targetRaw, "isRecentNonLatest", "target")
9027
+ },
9028
+ defines,
9029
+ rho: optionalNumber(args, "rho", "root"),
9030
+ targetWeightMultModifier: optionalNumber(args, "targetWeightMultModifier", "root"),
9031
+ randomRoll: optionalNumber(args, "randomRoll", "root"),
9032
+ useRandom: optionalBoolean(args, "useRandom", "root"),
9033
+ fleetHasHittable: optionalBoolean(args, "fleetHasHittable", "root"),
9034
+ targetFocus: optionalBoolean(args, "targetFocus", "root")
9035
+ };
9036
+ }
7986
9037
  }
7987
9038
  });
7988
9039
 
@@ -8030,19 +9081,22 @@ var require_toolHandlers = __commonJS({
8030
9081
  Object.defineProperty(exports2, "__esModule", { value: true });
8031
9082
  exports2.defaultSharedToolDispatcher = void 0;
8032
9083
  var path = __importStar(require("path"));
9084
+ var lsp_1 = require_lsp();
8033
9085
  var diagnosticRouting_1 = require_diagnosticRouting();
8034
9086
  var rules_1 = require_rules();
8035
9087
  var profile_1 = require_profile();
8036
9088
  var knowledge_1 = require_knowledge();
8037
9089
  var localisation_1 = require_localisation();
8038
9090
  var pdxBlock_1 = require_pdxBlock();
9091
+ var targetingWeights_1 = require_targetingWeights();
8039
9092
  var schema_1 = require_schema();
8040
9093
  var symbols_1 = require_symbols();
8041
9094
  function asRecord(value) {
8042
9095
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
8043
9096
  }
8044
- async function executeLspTool(host, command, args, unavailableNextStep) {
8045
- const result = await host.lsp.executeCommand(command, args);
9097
+ async function executeLspTool(host, command, args, unavailableNextStep, signal) {
9098
+ (0, lsp_1.throwIfAborted)(signal);
9099
+ const result = await host.lsp.executeCommand(command, args, signal ? { signal } : void 0);
8046
9100
  const record = asRecord(result);
8047
9101
  const errorRecord = asRecord(record.error);
8048
9102
  const unavailable = record.status === "unavailable" || errorRecord.code === "lsp_unavailable";
@@ -8058,8 +9112,11 @@ var require_toolHandlers = __commonJS({
8058
9112
  nextSteps: unavailable ? [unavailableNextStep] : void 0
8059
9113
  };
8060
9114
  }
8061
- var defaultSharedToolDispatcher = async (host, name, rawArgs) => {
9115
+ var defaultSharedToolDispatcher = async (host, name, rawArgs, context) => {
8062
9116
  const args = asRecord(rawArgs);
9117
+ const signal = context?.signal;
9118
+ const lspTool = (command, args2, unavailableNextStep) => executeLspTool(host, command, args2, unavailableNextStep, signal);
9119
+ (0, lsp_1.throwIfAborted)(signal);
8063
9120
  switch (name) {
8064
9121
  case "query_project_profile":
8065
9122
  return (0, profile_1.queryProjectProfileWithHost)(host, args);
@@ -8081,7 +9138,7 @@ var require_toolHandlers = __commonJS({
8081
9138
  };
8082
9139
  }
8083
9140
  case "explore_pdx_project":
8084
- return executeLspTool(host, "cwtools.ai.exploreProject", [
9141
+ return lspTool("cwtools.ai.exploreProject", [
8085
9142
  typeof args.query === "string" ? args.query : "",
8086
9143
  typeof args.file === "string" && args.file ? toFileUri(args.file, host.workspaceRoot) : "",
8087
9144
  typeof args.typeName === "string" ? args.typeName : "",
@@ -8105,7 +9162,7 @@ var require_toolHandlers = __commonJS({
8105
9162
  }
8106
9163
  };
8107
9164
  }
8108
- return executeLspTool(host, "cwtools.ai.analyzePdxFlow", [{
9165
+ return lspTool("cwtools.ai.analyzePdxFlow", [{
8109
9166
  ...file ? { file } : {},
8110
9167
  ...definitionId ? { definitionId } : {},
8111
9168
  ...typeof args.entityType === "string" && args.entityType.trim() ? { entityType: args.entityType.trim() } : {},
@@ -8124,7 +9181,7 @@ var require_toolHandlers = __commonJS({
8124
9181
  }
8125
9182
  };
8126
9183
  }
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.");
9184
+ 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
9185
  }
8129
9186
  case "query_inline_instantiation": {
8130
9187
  const template = typeof args.template === "string" ? args.template.trim() : "";
@@ -8140,13 +9197,24 @@ var require_toolHandlers = __commonJS({
8140
9197
  }
8141
9198
  };
8142
9199
  }
8143
- return executeLspTool(host, "cwtools.ai.exploreInlineGraph", [{
9200
+ return lspTool("cwtools.ai.exploreInlineGraph", [{
8144
9201
  ...template ? { template } : {},
8145
9202
  ...file ? { file } : {},
8146
9203
  ...Number.isInteger(args.line) ? { line: Number(args.line) } : {},
8147
9204
  limit: Math.max(1, Math.min(Number(args.limit ?? 50) || 50, 200))
8148
9205
  }], "Start the CWTools LSP process and wait for the game model to load before resolving the inline template instantiation.");
8149
9206
  }
9207
+ case "query_targeting_weight": {
9208
+ const data = (0, targetingWeights_1.executeTargetingWeightQuery)(args);
9209
+ const failure = typeof data.error === "string" ? data.error : void 0;
9210
+ return {
9211
+ ok: failure === void 0,
9212
+ status: failure === void 0 ? "ready" : "error",
9213
+ source: "cwtools-shared",
9214
+ data,
9215
+ error: failure === void 0 ? void 0 : { code: "invalid_arguments", message: failure }
9216
+ };
9217
+ }
8150
9218
  case "query_localisation_index": {
8151
9219
  if (!host.indexing) {
8152
9220
  return (0, schema_1.toolUnavailable)(name, "Localisation index is not available in this host.", [
@@ -8154,7 +9222,7 @@ var require_toolHandlers = __commonJS({
8154
9222
  ]);
8155
9223
  }
8156
9224
  const data = await host.indexing.queryLocalisation(args);
8157
- const semanticAudit = args.auditMode === true ? await executeLspTool(host, "cwtools.ai.queryLocalisationAudit", [{
9225
+ const semanticAudit = args.auditMode === true ? await lspTool("cwtools.ai.queryLocalisationAudit", [{
8158
9226
  ...typeof args.key === "string" ? { key: args.key } : {},
8159
9227
  prefix: args.prefix === true,
8160
9228
  contains: args.contains === true,
@@ -8169,7 +9237,7 @@ var require_toolHandlers = __commonJS({
8169
9237
  };
8170
9238
  }
8171
9239
  case "get_diagnostics": {
8172
- const diagnostics = await host.diagnostics.getDiagnostics(args);
9240
+ const diagnostics = await host.diagnostics.getDiagnostics(args, signal ? { signal } : void 0);
8173
9241
  return {
8174
9242
  ok: diagnostics.ok,
8175
9243
  status: diagnostics.status === "unavailable" ? "unavailable" : diagnostics.status === "stale" ? "stale" : diagnostics.status === "pending" ? "loading" : "ready",
@@ -8225,9 +9293,9 @@ var require_toolHandlers = __commonJS({
8225
9293
  limit: typeof args.limit === "number" ? args.limit : void 0
8226
9294
  });
8227
9295
  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.");
9296
+ 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
9297
  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.");
9298
+ 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
9299
  case "query_rules":
8232
9300
  return (0, rules_1.queryRulesWithHost)(host, {
8233
9301
  category: String(args.category ?? "trigger"),
@@ -8256,19 +9324,19 @@ var require_toolHandlers = __commonJS({
8256
9324
  scope: String(args.scope ?? "")
8257
9325
  });
8258
9326
  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.");
9327
+ return lspTool("cwtools.ai.parseFragment", [String(args.code ?? "")], "Start the CWTools LSP process or connect this host to an existing language server.");
8260
9328
  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.");
9329
+ 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
9330
  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.");
9331
+ 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
9332
  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.");
9333
+ 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
9334
  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.");
9335
+ 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
9336
  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.");
9337
+ return lspTool("cwtools.ai.queryVariables", [args.filter ?? ""], "Start the CWTools LSP process or connect this host to an existing language server.");
8270
9338
  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.");
9339
+ 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
9340
  case "get_pdx_block":
8273
9341
  return (0, pdxBlock_1.getPdxBlockWithHost)(host, {
8274
9342
  file: String(args.file ?? ""),
@@ -8277,31 +9345,31 @@ var require_toolHandlers = __commonJS({
8277
9345
  // Shader knowledge tools: each LSP command takes a single JSON record
8278
9346
  // argument and returns { ok, ... } / { ok: false, status: 'error', ... }.
8279
9347
  case "query_shader_symbol":
8280
- return executeLspTool(host, "cwtools.ai.shader.symbols", [shaderRecord({
9348
+ return lspTool("cwtools.ai.shader.symbols", [shaderRecord({
8281
9349
  filter: typeof args.filter === "string" ? args.filter : void 0,
8282
9350
  kind: typeof args.kind === "string" ? args.kind : void 0,
8283
9351
  limit: typeof args.limit === "number" ? args.limit : void 0,
8284
9352
  cursor: typeof args.cursor === "number" ? args.cursor : void 0
8285
9353
  })], "Start the CWTools LSP process and wait for the shader model to load before querying shader symbols.");
8286
9354
  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.");
9355
+ 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
9356
  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.");
9357
+ 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
9358
  case "query_shader_callers":
8291
- return executeLspTool(host, "cwtools.ai.shader.callers", [shaderRecord({
9359
+ return lspTool("cwtools.ai.shader.callers", [shaderRecord({
8292
9360
  effectName: String(args.effectName ?? ""),
8293
9361
  limit: typeof args.limit === "number" ? args.limit : void 0
8294
9362
  })], "Start the CWTools LSP process and wait for the shader model to load before querying Effect callers.");
8295
9363
  case "explain_shader_reachability":
8296
- return executeLspTool(host, "cwtools.ai.shader.reachability", [typeof args.effectName === "string" && args.effectName ? { effectName: args.effectName } : shaderRecord({
9364
+ return lspTool("cwtools.ai.shader.reachability", [typeof args.effectName === "string" && args.effectName ? { effectName: args.effectName } : shaderRecord({
8297
9365
  uri: toFileUri(String(args.file ?? ""), host.workspaceRoot),
8298
9366
  limit: typeof args.limit === "number" ? args.limit : void 0,
8299
9367
  cursor: typeof args.cursor === "number" ? args.cursor : void 0
8300
9368
  })], "Start the CWTools LSP process and wait for the shader model to load before explaining Effect reachability.");
8301
9369
  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.");
9370
+ 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
9371
  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.");
9372
+ 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
9373
  case "get_ide_context":
8306
9374
  case "open_in_visual_editor":
8307
9375
  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 +9408,79 @@ var require_toolHandlers = __commonJS({
8340
9408
  }
8341
9409
  });
8342
9410
 
9411
+ // ../cwtools-shared/dist/tools/callHandler.js
9412
+ var require_callHandler = __commonJS({
9413
+ "../cwtools-shared/dist/tools/callHandler.js"(exports2) {
9414
+ "use strict";
9415
+ Object.defineProperty(exports2, "__esModule", { value: true });
9416
+ exports2.GENERIC_PARADOX_WARNING = void 0;
9417
+ exports2.createToolCallHandler = createToolCallHandler;
9418
+ exports2.bindToolCallHandler = bindToolCallHandler;
9419
+ var lsp_1 = require_lsp();
9420
+ var readiness_1 = require_readiness();
9421
+ var vanillaCache_1 = require_vanillaCache();
9422
+ var mcpSchema_1 = require_mcpSchema();
9423
+ var toolHandlers_1 = require_toolHandlers();
9424
+ 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.";
9425
+ function createToolCallHandler(host, dispatcher = toolHandlers_1.defaultSharedToolDispatcher) {
9426
+ let ready = false;
9427
+ const probeReadiness = async (context) => {
9428
+ if (ready)
9429
+ return { ready: true };
9430
+ try {
9431
+ const status = await host.lsp.executeCommand("cwtools.ai.getValidationStatus", [], {
9432
+ timeoutMs: 8e3,
9433
+ ...context?.signal ? { signal: context.signal } : {}
9434
+ });
9435
+ const verdict = (0, readiness_1.parseReadiness)(status);
9436
+ if (verdict.ready)
9437
+ ready = true;
9438
+ return verdict;
9439
+ } catch (error) {
9440
+ (0, lsp_1.throwIfAborted)(context?.signal);
9441
+ throw error;
9442
+ }
9443
+ };
9444
+ return async (name, args = {}, context) => {
9445
+ (0, lsp_1.throwIfAborted)(context?.signal);
9446
+ const writesEnabled = host.writesEnabled === true && host.readonlyMode === false;
9447
+ const cwtOnly = host.projectKind === "cwt-only";
9448
+ if (!(0, mcpSchema_1.isMcpToolAvailable)(name, { includeWrites: writesEnabled, cwtOnly })) {
9449
+ return {
9450
+ ok: false,
9451
+ status: "denied",
9452
+ source: "cwtools-shared",
9453
+ error: {
9454
+ code: cwtOnly ? "tool_not_available_in_cwt_only" : "tool_not_available",
9455
+ 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.`
9456
+ }
9457
+ };
9458
+ }
9459
+ const result = await dispatcher(host, name, args, context);
9460
+ const withGenericWarning = host.projectGameId === "paradox" ? {
9461
+ ...result,
9462
+ warnings: [...result.warnings ?? [], exports2.GENERIC_PARADOX_WARNING]
9463
+ } : result;
9464
+ const withVanilla = (0, vanillaCache_1.annotateVanillaCache)(name, withGenericWarning, host.vanillaCache);
9465
+ if (!readiness_1.LOAD_DEPENDENT_TOOLS.has(name))
9466
+ return withVanilla;
9467
+ return (0, readiness_1.annotateReadiness)(name, withVanilla, await probeReadiness(context));
9468
+ };
9469
+ }
9470
+ function bindToolCallHandler(host, dispatcher = toolHandlers_1.defaultSharedToolDispatcher) {
9471
+ return createToolCallHandler(host, dispatcher);
9472
+ }
9473
+ }
9474
+ });
9475
+
9476
+ // ../cwtools-shared/dist/tools/registry.js
9477
+ var require_registry = __commonJS({
9478
+ "../cwtools-shared/dist/tools/registry.js"(exports2) {
9479
+ "use strict";
9480
+ Object.defineProperty(exports2, "__esModule", { value: true });
9481
+ }
9482
+ });
9483
+
8343
9484
  // ../cwtools-shared/dist/index.js
8344
9485
  var require_dist = __commonJS({
8345
9486
  "../cwtools-shared/dist/index.js"(exports2) {
@@ -8362,6 +9503,8 @@ var require_dist = __commonJS({
8362
9503
  };
8363
9504
  Object.defineProperty(exports2, "__esModule", { value: true });
8364
9505
  __exportStar(require_mcpTools(), exports2);
9506
+ __exportStar(require_workspaceGameDetection(), exports2);
9507
+ __exportStar(require_capabilities(), exports2);
8365
9508
  __exportStar(require_diagnostics(), exports2);
8366
9509
  __exportStar(require_filesystem(), exports2);
8367
9510
  __exportStar(require_hostServices(), exports2);
@@ -8379,12 +9522,14 @@ var require_dist = __commonJS({
8379
9522
  __exportStar(require_localisation(), exports2);
8380
9523
  __exportStar(require_paths(), exports2);
8381
9524
  __exportStar(require_writes(), exports2);
9525
+ __exportStar(require_callHandler(), exports2);
8382
9526
  __exportStar(require_mcpSchema(), exports2);
8383
9527
  __exportStar(require_names(), exports2);
8384
9528
  __exportStar(require_pdxBlock(), exports2);
8385
9529
  __exportStar(require_registry(), exports2);
8386
9530
  __exportStar(require_schema(), exports2);
8387
9531
  __exportStar(require_symbols(), exports2);
9532
+ __exportStar(require_targetingWeights(), exports2);
8388
9533
  __exportStar(require_toolHandlers(), exports2);
8389
9534
  }
8390
9535
  });
@@ -13374,9 +14519,9 @@ var require_node = __commonJS({
13374
14519
  }
13375
14520
  });
13376
14521
 
13377
- // dist/hosts/vscodeCache.js
14522
+ // ../cwtools-node/dist/hosts/vscodeCache.js
13378
14523
  var require_vscodeCache = __commonJS({
13379
- "dist/hosts/vscodeCache.js"(exports2) {
14524
+ "../cwtools-node/dist/hosts/vscodeCache.js"(exports2) {
13380
14525
  "use strict";
13381
14526
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
13382
14527
  if (k2 === void 0) k2 = k;
@@ -13499,7 +14644,9 @@ var require_vscodeCache = __commonJS({
13499
14644
  }
13500
14645
  }
13501
14646
  function detectExtensionRulesDir(cacheDir, game) {
13502
- const g = (game ?? "stellaris").toLowerCase();
14647
+ if (!game || game === "paradox" || game === "cwt")
14648
+ return void 0;
14649
+ const g = game.toLowerCase();
13503
14650
  const roots = [
13504
14651
  ...cacheDir ? [cacheDir] : [],
13505
14652
  ...globalStorageBases().map((base) => path.join(base, PRIMARY_EXTENSION_DIR, ".cwtools"))
@@ -13517,9 +14664,9 @@ var require_vscodeCache = __commonJS({
13517
14664
  }
13518
14665
  });
13519
14666
 
13520
- // dist/hosts/projectSettings.js
14667
+ // ../cwtools-node/dist/hosts/projectSettings.js
13521
14668
  var require_projectSettings = __commonJS({
13522
- "dist/hosts/projectSettings.js"(exports2) {
14669
+ "../cwtools-node/dist/hosts/projectSettings.js"(exports2) {
13523
14670
  "use strict";
13524
14671
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
13525
14672
  if (k2 === void 0) k2 = k;
@@ -13774,9 +14921,9 @@ var require_projectSettings = __commonJS({
13774
14921
  }
13775
14922
  });
13776
14923
 
13777
- // dist/hosts/lspProcessHost.js
14924
+ // ../cwtools-node/dist/hosts/lspProcessHost.js
13778
14925
  var require_lspProcessHost = __commonJS({
13779
- "dist/hosts/lspProcessHost.js"(exports2) {
14926
+ "../cwtools-node/dist/hosts/lspProcessHost.js"(exports2) {
13780
14927
  "use strict";
13781
14928
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
13782
14929
  if (k2 === void 0) k2 = k;
@@ -13816,7 +14963,7 @@ var require_lspProcessHost = __commonJS({
13816
14963
  };
13817
14964
  })();
13818
14965
  Object.defineProperty(exports2, "__esModule", { value: true });
13819
- exports2.LspProcessHost = void 0;
14966
+ exports2.LspProcessHost = exports2.BackendIncompatibleError = void 0;
13820
14967
  exports2.resolveRulesCacheRoot = resolveRulesCacheRoot;
13821
14968
  exports2.createLspProcessHost = createLspProcessHost;
13822
14969
  exports2.resolveDefaultServerPath = resolveDefaultServerPath;
@@ -13828,41 +14975,65 @@ var require_lspProcessHost = __commonJS({
13828
14975
  var child_process_1 = require("child_process");
13829
14976
  var chokidar_1 = require_chokidar();
13830
14977
  var node_1 = require_node();
14978
+ var cwtools_shared_1 = require_dist();
13831
14979
  var vscodeCache_1 = require_vscodeCache();
13832
14980
  var projectSettings_1 = require_projectSettings();
13833
14981
  function resolveRulesCacheRoot(options) {
13834
14982
  return options.rulesCache ?? options.cachePath ?? path.join(options.workspaceRoot, ".cwtools", "rules-cache");
13835
14983
  }
14984
+ var DEFAULT_STARTUP_TIMEOUT_MS = 3e4;
14985
+ var BackendIncompatibleError = class extends Error {
14986
+ constructor(reason, message) {
14987
+ super(`CWTools backend is incompatible (${reason}): ${message}`);
14988
+ this.reason = reason;
14989
+ this.code = cwtools_shared_1.BACKEND_INCOMPATIBLE_CODE;
14990
+ this.name = "BackendIncompatibleError";
14991
+ }
14992
+ };
14993
+ exports2.BackendIncompatibleError = BackendIncompatibleError;
13836
14994
  var LspProcessHost = class {
14995
+ get debugEnabled() {
14996
+ return this.options.debug === true || !!process.env.CWTOOLS_MCP_DEBUG;
14997
+ }
13837
14998
  constructor(options) {
13838
14999
  this.options = options;
13839
15000
  this.pendingWatchedChanges = /* @__PURE__ */ new Map();
15001
+ this.generation = 0;
13840
15002
  }
13841
15003
  get readyAtMs() {
13842
15004
  return this.startedAtMs;
13843
15005
  }
15006
+ /** Capability record answered by the backend, once the handshake succeeded. */
15007
+ get backendCapabilities() {
15008
+ return this.capabilities;
15009
+ }
13844
15010
  async executeCommand(command, args = [], options) {
13845
15011
  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`);
15012
+ await this.ensureStarted(options?.signal);
15013
+ const result = await this.raceRequest("workspace/executeCommand", { command, arguments: args }, options?.timeoutMs ?? 2e4, `LSP command ${command} timed out`, options?.signal);
13851
15014
  return result;
13852
15015
  } catch (error) {
15016
+ if ((0, cwtools_shared_1.isAbortError)(error))
15017
+ throw error;
15018
+ if (error instanceof BackendIncompatibleError)
15019
+ return this.incompatibleResult(error);
13853
15020
  return this.unavailable(error instanceof Error ? error.message : String(error));
13854
15021
  }
13855
15022
  }
13856
- async sendRequest(method, params, timeoutMs = 2e4) {
15023
+ async sendRequest(method, params, timeoutMs = 2e4, signal) {
13857
15024
  try {
13858
- await this.ensureStarted(timeoutMs);
13859
- return await this.withTimeout(this.connection.sendRequest(method, params), timeoutMs, `LSP request ${method} timed out`);
15025
+ await this.ensureStarted(signal);
15026
+ return await this.raceRequest(method, params, timeoutMs, `LSP request ${method} timed out`, signal);
13860
15027
  } catch (error) {
15028
+ if ((0, cwtools_shared_1.isAbortError)(error))
15029
+ throw error;
15030
+ if (error instanceof BackendIncompatibleError)
15031
+ return this.incompatibleResult(error);
13861
15032
  return this.unavailable(error instanceof Error ? error.message : String(error));
13862
15033
  }
13863
15034
  }
13864
15035
  async request(method, params, options) {
13865
- return this.sendRequest(method, params, options?.timeoutMs);
15036
+ return this.sendRequest(method, params, options?.timeoutMs, options?.signal);
13866
15037
  }
13867
15038
  dispose() {
13868
15039
  const proc = this.process;
@@ -13870,6 +15041,7 @@ var require_lspProcessHost = __commonJS({
13870
15041
  this.connection = void 0;
13871
15042
  this.process = void 0;
13872
15043
  this.startPromise = void 0;
15044
+ this.generation += 1;
13873
15045
  this.stopFileWatcher();
13874
15046
  try {
13875
15047
  connection?.dispose();
@@ -13880,23 +15052,33 @@ var require_lspProcessHost = __commonJS({
13880
15052
  } catch {
13881
15053
  }
13882
15054
  }
13883
- async ensureStarted(timeoutMs = 3e4) {
15055
+ async ensureStarted(signal) {
15056
+ if (this.incompatible)
15057
+ throw this.incompatible;
13884
15058
  if (this.connection && !this.startError)
13885
15059
  return;
13886
15060
  if (!this.startPromise) {
13887
- this.startPromise = this.start();
15061
+ const generation = this.generation;
15062
+ this.startPromise = this.start(generation, signal).catch((error) => {
15063
+ if (this.generation === generation)
15064
+ this.startPromise = void 0;
15065
+ throw error;
15066
+ });
13888
15067
  }
13889
- await this.withTimeout(this.startPromise, timeoutMs, "CWTools LSP startup timed out");
15068
+ await this.startPromise;
13890
15069
  if (this.startError)
13891
15070
  throw new Error(this.startError);
13892
15071
  }
13893
- async start() {
15072
+ async start(generation, signal) {
15073
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15074
+ const startupTimeoutMs = this.options.startupTimeoutMs ?? DEFAULT_STARTUP_TIMEOUT_MS;
15075
+ const stale = () => this.generation !== generation;
13894
15076
  const serverPath = this.options.serverPath ?? resolveDefaultServerPath();
13895
15077
  if (!serverPath || !fs.existsSync(serverPath)) {
13896
15078
  this.startError = `CWTools server binary was not found. Checked: ${serverPath ?? "(none)"}`;
13897
15079
  throw new Error(this.startError);
13898
15080
  }
13899
- this.process = (0, child_process_1.spawn)(serverPath, [], {
15081
+ this.process = (0, child_process_1.spawn)(serverPath, this.options.serverArgs ?? [], {
13900
15082
  cwd: this.options.workspaceRoot,
13901
15083
  stdio: ["pipe", "pipe", "pipe"],
13902
15084
  windowsHide: true
@@ -13907,14 +15089,16 @@ var require_lspProcessHost = __commonJS({
13907
15089
  process.stderr.write(`[cwtools-lsp] ${text}`);
13908
15090
  }
13909
15091
  });
13910
- this.process.on("exit", (code, signal) => {
13911
- this.startError = `CWTools LSP exited with code ${code ?? "null"} signal ${signal ?? "null"}`;
15092
+ this.process.on("exit", (code, exitSignal) => {
15093
+ if (stale())
15094
+ return;
15095
+ this.startError = `CWTools LSP exited with code ${code ?? "null"} signal ${exitSignal ?? "null"}`;
13912
15096
  this.connection = void 0;
13913
15097
  this.stopFileWatcher();
13914
15098
  });
13915
15099
  this.connection = (0, node_1.createMessageConnection)(new node_1.StreamMessageReader(this.process.stdout), new node_1.StreamMessageWriter(this.process.stdin));
13916
15100
  this.connection.listen();
13917
- if (process.env.CWTOOLS_MCP_DEBUG) {
15101
+ if (this.debugEnabled) {
13918
15102
  this.connection.onNotification("window/logMessage", (p = {}) => {
13919
15103
  if (p.message)
13920
15104
  process.stderr.write(`[cwtools-lsp] ${String(p.message).slice(0, 240)}
@@ -13922,13 +15106,13 @@ var require_lspProcessHost = __commonJS({
13922
15106
  });
13923
15107
  }
13924
15108
  const rootUri = pathToFileUri(this.options.workspaceRoot);
13925
- const game = this.options.game ?? "stellaris";
15109
+ const game = this.options.game ?? "paradox";
13926
15110
  const rulesCacheRoot = resolveRulesCacheRoot(this.options);
13927
- const rulesFolder = this.options.bundledRulesPath ?? resolveBundledRulesPath(game, rulesCacheRoot);
15111
+ const rulesFolder = game === "paradox" || game === "cwt" ? "" : this.options.bundledRulesPath ?? resolveBundledRulesPath(game, rulesCacheRoot);
13928
15112
  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");
15113
+ 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
15114
  }
13931
- await this.connection.sendRequest("initialize", {
15115
+ await this.raceRequest("initialize", {
13932
15116
  processId: process.pid,
13933
15117
  rootPath: this.options.workspaceRoot,
13934
15118
  rootUri,
@@ -13961,10 +15145,14 @@ var require_lspProcessHost = __commonJS({
13961
15145
  diagnosticLogging: false
13962
15146
  },
13963
15147
  trace: "off"
13964
- });
15148
+ }, startupTimeoutMs, "CWTools LSP initialize timed out", signal);
15149
+ await this.handshake(startupTimeoutMs, signal, stale);
15150
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15151
+ if (stale())
15152
+ throw (0, cwtools_shared_1.createAbortError)("Operation was aborted.");
13965
15153
  void this.connection.sendNotification("initialized", {});
13966
15154
  const loc = (0, projectSettings_1.resolveLocalisationLanguages)(this.options.workspaceRoot);
13967
- process.stderr.write(`[cwtools-mcp] info: localisation languages = [${loc.languages.join(", ")}] (${loc.source})
15155
+ process.stderr.write(`[cwtools-node] info: localisation languages = [${loc.languages.join(", ")}] (${loc.source})
13968
15156
  `);
13969
15157
  void this.connection.sendNotification("workspace/didChangeConfiguration", {
13970
15158
  settings: {
@@ -13974,10 +15162,33 @@ var require_lspProcessHost = __commonJS({
13974
15162
  }, (0, projectSettings_1.resolveExperimental)(this.options.workspaceRoot))
13975
15163
  }
13976
15164
  });
13977
- await this.waitForExecuteCommandsReady(2e4);
15165
+ await this.waitForExecuteCommandsReady(Math.min(startupTimeoutMs, 2e4), signal, stale);
15166
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15167
+ if (stale())
15168
+ throw (0, cwtools_shared_1.createAbortError)("Operation was aborted.");
13978
15169
  this.startFileWatcher();
13979
15170
  this.startedAtMs = Date.now();
13980
15171
  }
15172
+ async handshake(timeoutMs, signal, stale = () => false) {
15173
+ const raw = await this.raceRequest("workspace/executeCommand", { command: "cwtools.ai.getHostCapabilities", arguments: [] }, timeoutMs, "CWTools capability handshake timed out", signal).catch((error) => {
15174
+ if ((0, cwtools_shared_1.isAbortError)(error))
15175
+ throw error;
15176
+ return { status: "unavailable", error: { message: String(error) } };
15177
+ });
15178
+ const verdict = (0, cwtools_shared_1.parseHostCapabilities)(raw);
15179
+ const checked = verdict.ok ? (0, cwtools_shared_1.checkRequiredCommands)(verdict.capabilities) : verdict;
15180
+ if (checked.ok) {
15181
+ this.capabilities = checked.capabilities;
15182
+ return;
15183
+ }
15184
+ const incompatibility = new BackendIncompatibleError(checked.reason, checked.message);
15185
+ if (!stale()) {
15186
+ this.dispose();
15187
+ this.incompatible = incompatibility;
15188
+ this.startError = incompatibility.message;
15189
+ }
15190
+ throw incompatibility;
15191
+ }
13981
15192
  startFileWatcher() {
13982
15193
  if (this.fileWatcher)
13983
15194
  return;
@@ -13990,8 +15201,8 @@ var require_lspProcessHost = __commonJS({
13990
15201
  watcher.on("change", (filePath) => this.queueWatchedFileChange(filePath, 2));
13991
15202
  watcher.on("unlink", (filePath) => this.queueWatchedFileChange(filePath, 3));
13992
15203
  watcher.on("error", (error) => {
13993
- if (process.env.CWTOOLS_MCP_DEBUG) {
13994
- process.stderr.write(`[cwtools-mcp] file watcher error: ${String(error)}
15204
+ if (this.debugEnabled) {
15205
+ process.stderr.write(`[cwtools-node] file watcher error: ${String(error)}
13995
15206
  `);
13996
15207
  }
13997
15208
  });
@@ -14029,6 +15240,19 @@ var require_lspProcessHost = __commonJS({
14029
15240
  this.pendingWatchedChanges.clear();
14030
15241
  void connection.sendNotification("workspace/didChangeWatchedFiles", { changes });
14031
15242
  }
15243
+ // A rejected handshake is a distinct failure: the caller must not treat it as a
15244
+ // transient "start the server" condition and retry.
15245
+ incompatibleResult(error) {
15246
+ return {
15247
+ ok: false,
15248
+ status: "unavailable",
15249
+ error: {
15250
+ code: cwtools_shared_1.BACKEND_INCOMPATIBLE_CODE,
15251
+ reason: error.reason,
15252
+ message: error.message
15253
+ }
15254
+ };
15255
+ }
14032
15256
  unavailable(message) {
14033
15257
  return {
14034
15258
  ok: false,
@@ -14039,27 +15263,66 @@ var require_lspProcessHost = __commonJS({
14039
15263
  }
14040
15264
  };
14041
15265
  }
14042
- async withTimeout(promise, timeoutMs, message) {
15266
+ // Issue a JSON-RPC request that is actually cancellable: the AbortSignal is
15267
+ // linked to a vscode-jsonrpc CancellationTokenSource, so aborting sends a
15268
+ // `$/cancelRequest` to the backend and releases its work — racing the promise
15269
+ // alone would leave the server computing a result nobody reads. The deadline and
15270
+ // the abort listener are both released in the finally block.
15271
+ async raceRequest(method, params, timeoutMs, timeoutMessage, signal) {
15272
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15273
+ const connection = this.connection;
15274
+ if (!connection)
15275
+ throw new Error("CWTools LSP connection is not established.");
15276
+ const cancellation = new node_1.CancellationTokenSource();
14043
15277
  let timer;
15278
+ let onAbort;
15279
+ let settled = false;
15280
+ const request = connection.sendRequest(method, params, cancellation.token);
14044
15281
  try {
14045
- return await Promise.race([
14046
- promise,
14047
- new Promise((_, reject) => {
14048
- timer = setTimeout(() => reject(new Error(message)), timeoutMs);
14049
- })
14050
- ]);
15282
+ const timeout = new Promise((_, reject) => {
15283
+ timer = setTimeout(() => {
15284
+ settled = true;
15285
+ cancellation.cancel();
15286
+ reject(new Error(timeoutMessage));
15287
+ }, timeoutMs);
15288
+ });
15289
+ const aborted = new Promise((_, reject) => {
15290
+ if (!signal)
15291
+ return;
15292
+ onAbort = () => {
15293
+ settled = true;
15294
+ cancellation.cancel();
15295
+ reject((0, cwtools_shared_1.createAbortError)(signal.reason instanceof Error ? signal.reason.message : "Operation was aborted."));
15296
+ };
15297
+ signal.addEventListener("abort", onAbort, { once: true });
15298
+ });
15299
+ return await Promise.race([request, timeout, aborted]);
14051
15300
  } finally {
14052
15301
  if (timer)
14053
15302
  clearTimeout(timer);
15303
+ if (onAbort && signal)
15304
+ signal.removeEventListener("abort", onAbort);
15305
+ if (settled) {
15306
+ cancellation.cancel();
15307
+ void request.catch(() => void 0);
15308
+ }
15309
+ cancellation.dispose();
14054
15310
  }
14055
15311
  }
14056
- async waitForExecuteCommandsReady(timeoutMs) {
15312
+ // Poll until the command surface answers. Abort- and generation-aware: a host
15313
+ // disposed (or an AbortSignal fired) mid-poll stops here instead of continuing
15314
+ // to touch a connection that may already be gone.
15315
+ async waitForExecuteCommandsReady(timeoutMs, signal, stale = () => false) {
14057
15316
  const start = Date.now();
14058
15317
  while (Date.now() - start < timeoutMs) {
14059
- const result = await this.connection.sendRequest("workspace/executeCommand", {
14060
- command: "cwtools.ai.getValidationStatus",
14061
- arguments: []
14062
- }).catch(() => null);
15318
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15319
+ if (stale())
15320
+ throw (0, cwtools_shared_1.createAbortError)("Operation was aborted.");
15321
+ 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) => {
15322
+ if ((0, cwtools_shared_1.isAbortError)(error) || error instanceof BackendIncompatibleError)
15323
+ throw error;
15324
+ return null;
15325
+ });
14063
15326
  if (result && typeof result === "object")
14064
15327
  return;
14065
15328
  await new Promise((resolve) => setTimeout(resolve, 500));
@@ -14175,154 +15438,32 @@ var require_lspProcessHost = __commonJS({
14175
15438
  }
14176
15439
  });
14177
15440
 
14178
- // dist/hosts/projectDetect.js
15441
+ // ../cwtools-node/dist/hosts/projectDetect.js
14179
15442
  var require_projectDetect = __commonJS({
14180
- "dist/hosts/projectDetect.js"(exports2) {
15443
+ "../cwtools-node/dist/hosts/projectDetect.js"(exports2) {
14181
15444
  "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
- })();
14219
15445
  Object.defineProperty(exports2, "__esModule", { value: true });
14220
15446
  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) {
14230
- try {
14231
- return fs.statSync(p).isFile();
14232
- } catch {
14233
- return false;
14234
- }
14235
- }
14236
- function isDir(p) {
14237
- try {
14238
- return fs.statSync(p).isDirectory();
14239
- } catch {
14240
- return false;
14241
- }
14242
- }
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}/`);
14261
- }
14262
- }
14263
- return found;
14264
- }
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
- }
15447
+ var cwtools_shared_1 = require_dist();
15448
+ function detectProjectSupport(workspaceRoot, options) {
15449
+ const detection = (0, cwtools_shared_1.detectWorkspaceProject)(workspaceRoot, (gameId) => options?.gamePath && options.game === gameId ? options.gamePath : void 0);
14314
15450
  return {
14315
- supported: false,
14316
- markers: [],
14317
- reason: `No Paradox mod markers (descriptor.mod, common/, events/, localisation/, .cwtools/) at, above, or directly under '${workspaceRoot}'.`
15451
+ supported: detection.kind === "mod" || detection.kind === "vanilla" || detection.kind === "cwt-only",
15452
+ reason: detection.reason,
15453
+ markers: [...detection.evidence],
15454
+ ...detection.matchedAt ? { matchedAt: detection.matchedAt } : {},
15455
+ kind: detection.kind,
15456
+ ...detection.gameId ? { gameId: detection.gameId } : {},
15457
+ ...detection.candidates ? { candidates: [...detection.candidates] } : {},
15458
+ detection
14318
15459
  };
14319
15460
  }
14320
15461
  }
14321
15462
  });
14322
15463
 
14323
- // dist/hosts/revalidation.js
15464
+ // ../cwtools-node/dist/hosts/revalidation.js
14324
15465
  var require_revalidation = __commonJS({
14325
- "dist/hosts/revalidation.js"(exports2) {
15466
+ "../cwtools-node/dist/hosts/revalidation.js"(exports2) {
14326
15467
  "use strict";
14327
15468
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
14328
15469
  if (k2 === void 0) k2 = k;
@@ -14365,6 +15506,7 @@ var require_revalidation = __commonJS({
14365
15506
  exports2.RevalidationCoordinator = void 0;
14366
15507
  var fs = __importStar(require("fs"));
14367
15508
  var path = __importStar(require("path"));
15509
+ var cwtools_shared_1 = require_dist();
14368
15510
  var lspProcessHost_1 = require_lspProcessHost();
14369
15511
  var REVALIDATE_EXTS = /* @__PURE__ */ new Set([".txt", ".yml", ".gui", ".gfx", ".asset", ".shader", ".fxh"]);
14370
15512
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "coverage"]);
@@ -14382,7 +15524,11 @@ var require_revalidation = __commonJS({
14382
15524
  this.lastReval = /* @__PURE__ */ new Map();
14383
15525
  }
14384
15526
  // absFile: absolute path for a single-file query, or undefined for whole-project.
14385
- async ensureFresh(absFile) {
15527
+ // `signal` cancels the revalidation and the drain wait; the abort propagates
15528
+ // instead of being swallowed so a cancelled diagnostics query is not reported
15529
+ // as an empty, fresh result.
15530
+ async ensureFresh(absFile, signal) {
15531
+ (0, cwtools_shared_1.throwIfAborted)(signal);
14386
15532
  const baseline = this.readyAt();
14387
15533
  if (baseline === void 0)
14388
15534
  return;
@@ -14393,16 +15539,17 @@ var require_revalidation = __commonJS({
14393
15539
  const uris = batch.map((c) => (0, lspProcessHost_1.pathToFileUri)(c.path));
14394
15540
  let baselineEpoch = 0;
14395
15541
  try {
14396
- const res = await this.lsp.executeCommand("cwtools.ai.revalidateFiles", [uris], { timeoutMs: 1e4 });
15542
+ const res = await this.lsp.executeCommand("cwtools.ai.revalidateFiles", [uris], { timeoutMs: 1e4, ...signal ? { signal } : {} });
14397
15543
  if (!res || res.ok !== true)
14398
15544
  return;
14399
15545
  baselineEpoch = numberOr(res.baselineEpoch, 0);
14400
- } catch {
15546
+ } catch (error) {
15547
+ (0, cwtools_shared_1.rethrowIfAborted)(error);
14401
15548
  return;
14402
15549
  }
14403
15550
  for (const c of batch)
14404
15551
  this.lastReval.set(c.path, c.mtimeMs);
14405
- await this.waitDrained(baselineEpoch);
15552
+ await this.waitDrained(baselineEpoch, signal);
14406
15553
  }
14407
15554
  changedSingle(absFile, baseline) {
14408
15555
  let mtimeMs;
@@ -14458,13 +15605,17 @@ var require_revalidation = __commonJS({
14458
15605
  }
14459
15606
  // Wait until the lint queue drains and the epoch advanced past the revalidation
14460
15607
  // baseline (so the posted re-lints have completed). Bounded; best-effort.
14461
- async waitDrained(baselineEpoch) {
15608
+ async waitDrained(baselineEpoch, signal) {
14462
15609
  const timeoutMs = 5e3;
14463
15610
  const intervalMs = 50;
14464
15611
  let elapsed = 0;
14465
15612
  await sleep(30);
14466
15613
  while (elapsed < timeoutMs) {
14467
- const s = await this.lsp.executeCommand("cwtools.ai.getValidationStatus", [], { timeoutMs: 5e3 }).catch(() => null);
15614
+ (0, cwtools_shared_1.throwIfAborted)(signal);
15615
+ const s = await this.lsp.executeCommand("cwtools.ai.getValidationStatus", [], { timeoutMs: 5e3, ...signal ? { signal } : {} }).catch((error) => {
15616
+ (0, cwtools_shared_1.rethrowIfAborted)(error);
15617
+ return null;
15618
+ });
14468
15619
  if (!s || typeof s !== "object")
14469
15620
  return;
14470
15621
  const epoch = numberOr(s.epoch, 0);
@@ -14481,9 +15632,9 @@ var require_revalidation = __commonJS({
14481
15632
  }
14482
15633
  });
14483
15634
 
14484
- // dist/hosts/nodeHostServices.js
15635
+ // ../cwtools-node/dist/hosts/nodeHostServices.js
14485
15636
  var require_nodeHostServices = __commonJS({
14486
- "dist/hosts/nodeHostServices.js"(exports2) {
15637
+ "../cwtools-node/dist/hosts/nodeHostServices.js"(exports2) {
14487
15638
  "use strict";
14488
15639
  var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
14489
15640
  if (k2 === void 0) k2 = k;
@@ -14534,34 +15685,45 @@ var require_nodeHostServices = __commonJS({
14534
15685
  var revalidation_1 = require_revalidation();
14535
15686
  var vscodeCache_1 = require_vscodeCache();
14536
15687
  function createNodeHostServices(config) {
14537
- const workspaceRoot = path.resolve(config.workspaceRoot);
15688
+ const requestedWorkspaceRoot = path.resolve(config.workspaceRoot);
15689
+ const support = (0, projectDetect_1.detectProjectSupport)(requestedWorkspaceRoot, { game: config.game, gamePath: config.gamePath });
15690
+ const workspaceRoot = path.resolve(support.supported ? support.matchedAt ?? requestedWorkspaceRoot : requestedWorkspaceRoot);
15691
+ const enabled = support.supported || config.forceStart;
15692
+ const projectKind = support.supported ? support.kind : config.forceStart ? "mod" : support.kind;
15693
+ const game = support.kind === "cwt-only" ? "cwt" : config.game ?? support.gameId ?? "paradox";
14538
15694
  const allowlist = config.allowedTools.length > 0 ? new Set(config.allowedTools) : new Set(cwtools_shared_1.MCP_WRITE_TOOL_NAMES);
14539
15695
  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);
15696
+ const autoCache = config.cachePath ?? (0, vscodeCache_1.detectExtensionCacheDir)(game);
15697
+ const detectedRulesPath = (0, vscodeCache_1.detectExtensionRulesDir)(autoCache, game);
14544
15698
  const rulesConfigDirs = uniqueStrings([config.rulesPath, detectedRulesPath].filter((item) => !!item));
14545
15699
  const lspProcess = enabled ? (0, lspProcessHost_1.createLspProcessHost)({
14546
15700
  workspaceRoot,
14547
- game: config.game,
15701
+ game,
14548
15702
  serverPath: config.serverPath,
14549
15703
  cachePath: autoCache,
14550
- gamePath: config.gamePath,
14551
- bundledRulesPath: config.rulesPath
15704
+ gamePath: game === "paradox" || game === "cwt" ? void 0 : config.gamePath,
15705
+ bundledRulesPath: config.rulesPath,
15706
+ ...config.startupTimeoutMs === void 0 ? {} : { startupTimeoutMs: config.startupTimeoutMs },
15707
+ ...config.debug === void 0 ? {} : { debug: config.debug }
14552
15708
  }) : void 0;
14553
15709
  const lsp = lspProcess ?? (0, cwtools_shared_1.createUnavailableLspHost)("Workspace is not a recognised Paradox mod; CWTools is disabled here.");
15710
+ const report = (message) => {
15711
+ if (config.logger)
15712
+ config.logger("info", message);
15713
+ else
15714
+ console.error(`[cwtools-node] info: ${message}`);
15715
+ };
14554
15716
  if (!enabled) {
14555
- console.error(`[cwtools-mcp] info: tool calls will be rejected (no language server) \u2014 ${support.reason} (pass --force-start to override)`);
15717
+ report(`tool calls will be rejected (no language server) \u2014 ${support.reason} (pass --force-start to override)`);
14556
15718
  } 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})`);
15719
+ report(`--force-start set; starting despite: ${support.reason}`);
15720
+ } else if (support.matchedAt && support.matchedAt !== requestedWorkspaceRoot) {
15721
+ report(`mod detected at ${support.matchedAt} (workspace = ${workspaceRoot})`);
14560
15722
  }
14561
15723
  if (enabled && !config.cachePath && autoCache) {
14562
- console.error(`[cwtools-mcp] info: auto-detected VS Code extension cache at ${autoCache}`);
15724
+ report(`auto-detected VS Code extension cache at ${autoCache}`);
14563
15725
  }
14564
- console.error(`[cwtools-mcp] info: workspace = ${workspaceRoot}${config.workspaceRoot === process.cwd() ? " (inherited cwd)" : ""}`);
15726
+ report(`workspace = ${workspaceRoot}${config.workspaceRoot === process.cwd() ? " (inherited cwd)" : ""}`);
14565
15727
  return {
14566
15728
  workspaceRoot,
14567
15729
  readonlyMode: !config.enableWrites,
@@ -14569,12 +15731,16 @@ var require_nodeHostServices = __commonJS({
14569
15731
  allowedWriteTools: allowlist,
14570
15732
  projectSupported: enabled,
14571
15733
  projectSupportReason: support.reason,
15734
+ projectKind,
15735
+ projectGameId: game,
15736
+ projectEvidence: [...support.markers],
15737
+ projectCandidates: support.candidates ? [...support.candidates] : void 0,
14572
15738
  lsp,
14573
15739
  diagnostics: new LspDiagnosticsHost(lsp, workspaceRoot, lspProcess ? new revalidation_1.RevalidationCoordinator(lsp, workspaceRoot, () => lspProcess.readyAtMs) : void 0),
14574
15740
  filesystem,
14575
15741
  indexing: new ThinNodeIndexHost(workspaceRoot),
14576
15742
  rules: {
14577
- gameId: config.game,
15743
+ gameId: game,
14578
15744
  configDirs: rulesConfigDirs,
14579
15745
  async readTextFile(filePath) {
14580
15746
  if (!fssync.existsSync(filePath))
@@ -14594,13 +15760,17 @@ var require_nodeHostServices = __commonJS({
14594
15760
  return results;
14595
15761
  }
14596
15762
  },
14597
- vanillaCache: probeVanillaCache(workspaceRoot, { ...config, cachePath: autoCache }),
15763
+ vanillaCache: game === "cwt" ? void 0 : probeVanillaCache(workspaceRoot, { game, gamePath: config.gamePath, cachePath: autoCache, workspaceRoot }),
14598
15764
  now: () => Date.now(),
14599
15765
  log: (level, message, data) => {
14600
- if (level === "debug")
15766
+ if (level === "debug" && !config.debug)
15767
+ return;
15768
+ if (config.logger) {
15769
+ config.logger(level, message, data);
14601
15770
  return;
15771
+ }
14602
15772
  const suffix = data === void 0 ? "" : ` ${JSON.stringify(data)}`;
14603
- console.error(`[cwtools-mcp] ${level}: ${message}${suffix}`);
15773
+ console.error(`[cwtools-node] ${level}: ${message}${suffix}`);
14604
15774
  },
14605
15775
  dispose: () => lspProcess?.dispose()
14606
15776
  };
@@ -14622,7 +15792,7 @@ var require_nodeHostServices = __commonJS({
14622
15792
  const rulesCacheRoot = (0, lspProcessHost_1.resolveRulesCacheRoot)({ cachePath: config.cachePath, workspaceRoot });
14623
15793
  const cacheFile = cacheFileName ? path.join(rulesCacheRoot, cacheFileName) : void 0;
14624
15794
  const cacheExists = !!cacheFile && fssync.existsSync(cacheFile);
14625
- const gamePathValid = !!config.gamePath && fssync.existsSync(config.gamePath);
15795
+ const gamePathValid = !!cacheFileName && !!config.gamePath && fssync.existsSync(config.gamePath);
14626
15796
  if (cacheExists) {
14627
15797
  return { available: true, source: "mod_plus_vanilla", cacheFile, reason: "Loaded a pre-built vanilla cache." };
14628
15798
  }
@@ -14648,29 +15818,30 @@ var require_nodeHostServices = __commonJS({
14648
15818
  this.workspaceRoot = workspaceRoot;
14649
15819
  this.revalidation = revalidation;
14650
15820
  }
14651
- async getDiagnostics(filter = {}) {
15821
+ async getDiagnostics(filter = {}, context) {
15822
+ (0, cwtools_shared_1.throwIfAborted)(context?.signal);
14652
15823
  if (this.revalidation) {
14653
15824
  const absFile = filter.file ? (0, cwtools_shared_1.resolveWorkspacePath)(this.workspaceRoot, filter.file).resolvedPath ?? void 0 : void 0;
14654
- await this.revalidation.ensureFresh(absFile);
15825
+ await this.revalidation.ensureFresh(absFile, context?.signal);
14655
15826
  }
14656
- return this.applyIgnoreList(await this.queryDiagnostics(filter));
15827
+ return this.applyIgnoreList(await this.queryDiagnostics(filter, context?.signal));
14657
15828
  }
14658
15829
  applyIgnoreList(result) {
14659
15830
  if (!result.ok || result.diagnostics.length === 0)
14660
15831
  return result;
14661
15832
  return (0, projectSettings_1.applyDiagnosticIgnoreList)(result, (0, projectSettings_1.readIgnoredDiagnostics)(this.workspaceRoot));
14662
15833
  }
14663
- async queryDiagnostics(filter) {
15834
+ async queryDiagnostics(filter, signal) {
14664
15835
  const file = filter.file;
14665
15836
  if (file) {
14666
15837
  const resolution = (0, cwtools_shared_1.resolveWorkspacePath)(this.workspaceRoot, file);
14667
15838
  const filePath = resolution.resolvedPath ?? file;
14668
- const raw2 = asRecord(await this.lsp.executeCommand("cwtools.ai.getDiagnosticsFresh", [(0, lspProcessHost_1.pathToFileUri)(filePath)], { timeoutMs: 2e4 }));
15839
+ const raw2 = asRecord(await this.lsp.executeCommand("cwtools.ai.getDiagnosticsFresh", [(0, lspProcessHost_1.pathToFileUri)(filePath)], { timeoutMs: 2e4, ...signal ? { signal } : {} }));
14669
15840
  return normalizeDiagnosticsFresh(raw2);
14670
15841
  }
14671
15842
  const severity = filter.severity === "information" ? "info" : filter.severity ?? "all";
14672
15843
  const limit = typeof filter.limit === "number" ? filter.limit : 1e3;
14673
- const raw = asRecord(await this.lsp.executeCommand("cwtools.ai.getAllDiagnostics", [severity, limit], { timeoutMs: 3e4 }));
15844
+ const raw = asRecord(await this.lsp.executeCommand("cwtools.ai.getAllDiagnostics", [severity, limit], { timeoutMs: 3e4, ...signal ? { signal } : {} }));
14674
15845
  if (raw.ok === false || raw.status === "unavailable") {
14675
15846
  return unavailableDiagnostics(raw);
14676
15847
  }
@@ -14971,6 +16142,31 @@ var require_nodeHostServices = __commonJS({
14971
16142
  }
14972
16143
  });
14973
16144
 
16145
+ // dist/hosts/nodeHostServices.js
16146
+ var require_nodeHostServices2 = __commonJS({
16147
+ "dist/hosts/nodeHostServices.js"(exports2) {
16148
+ "use strict";
16149
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
16150
+ if (k2 === void 0) k2 = k;
16151
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16152
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16153
+ desc = { enumerable: true, get: function() {
16154
+ return m[k];
16155
+ } };
16156
+ }
16157
+ Object.defineProperty(o, k2, desc);
16158
+ }) : (function(o, m, k, k2) {
16159
+ if (k2 === void 0) k2 = k;
16160
+ o[k2] = m[k];
16161
+ }));
16162
+ var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
16163
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
16164
+ };
16165
+ Object.defineProperty(exports2, "__esModule", { value: true });
16166
+ __exportStar(require_nodeHostServices(), exports2);
16167
+ }
16168
+ });
16169
+
14974
16170
  // ../../node_modules/zod/v3/helpers/util.cjs
14975
16171
  var require_util = __commonJS({
14976
16172
  "../../node_modules/zod/v3/helpers/util.cjs"(exports2) {
@@ -49724,6 +50920,31 @@ var require_server2 = __commonJS({
49724
50920
  }
49725
50921
  });
49726
50922
 
50923
+ // dist/hosts/vscodeCache.js
50924
+ var require_vscodeCache2 = __commonJS({
50925
+ "dist/hosts/vscodeCache.js"(exports2) {
50926
+ "use strict";
50927
+ var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
50928
+ if (k2 === void 0) k2 = k;
50929
+ var desc = Object.getOwnPropertyDescriptor(m, k);
50930
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
50931
+ desc = { enumerable: true, get: function() {
50932
+ return m[k];
50933
+ } };
50934
+ }
50935
+ Object.defineProperty(o, k2, desc);
50936
+ }) : (function(o, m, k, k2) {
50937
+ if (k2 === void 0) k2 = k;
50938
+ o[k2] = m[k];
50939
+ }));
50940
+ var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
50941
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
50942
+ };
50943
+ Object.defineProperty(exports2, "__esModule", { value: true });
50944
+ __exportStar(require_vscodeCache(), exports2);
50945
+ }
50946
+ });
50947
+
49727
50948
  // dist/mcp/resources.js
49728
50949
  var require_resources = __commonJS({
49729
50950
  "dist/mcp/resources.js"(exports2) {
@@ -49820,6 +51041,11 @@ var require_resources = __commonJS({
49820
51041
  mimeType: "application/json"
49821
51042
  }
49822
51043
  ];
51044
+ if (host?.projectSupported === false)
51045
+ return [];
51046
+ if (host?.projectKind === "cwt-only") {
51047
+ return base.filter((resource) => resource.uri === "cwtools://knowledge/diagnostic-routing");
51048
+ }
49823
51049
  if (host?.workspaceRoot) {
49824
51050
  for (const skill of discoverSkills(host.workspaceRoot)) {
49825
51051
  base.push({
@@ -49833,6 +51059,17 @@ var require_resources = __commonJS({
49833
51059
  return base;
49834
51060
  }
49835
51061
  async function readResource(host, uri) {
51062
+ if (host.projectSupported === false || host.projectKind === "cwt-only" && uri !== "cwtools://knowledge/diagnostic-routing") {
51063
+ const code = host.projectKind === "ambiguous" ? "project_ambiguous" : host.projectSupported === false ? "project_not_supported" : "resource_not_available_in_cwt_only";
51064
+ return {
51065
+ contents: [{
51066
+ uri,
51067
+ mimeType: "application/json",
51068
+ text: `${JSON.stringify({ status: "error", error: { code, message: host.projectSupportReason ?? "Resource is not available for this workspace." } }, null, 2)}
51069
+ `
51070
+ }]
51071
+ };
51072
+ }
49836
51073
  if (uri.startsWith("cwtools://skills/") && uri !== "cwtools://skills/catalog") {
49837
51074
  const skillName = decodeURIComponent(uri.slice("cwtools://skills/".length));
49838
51075
  const found = discoverSkills(host.workspaceRoot).find((entry) => entry.name === skillName);
@@ -50000,44 +51237,15 @@ var require_toolHandlers2 = __commonJS({
50000
51237
  "dist/mcp/toolHandlers.js"(exports2) {
50001
51238
  "use strict";
50002
51239
  Object.defineProperty(exports2, "__esModule", { value: true });
50003
- exports2.createToolCallHandler = createToolCallHandler;
51240
+ exports2.bindToolCallHandler = exports2.createToolCallHandler = void 0;
50004
51241
  exports2.toMcpCallToolResult = toMcpCallToolResult;
50005
51242
  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
- }
51243
+ Object.defineProperty(exports2, "createToolCallHandler", { enumerable: true, get: function() {
51244
+ return cwtools_shared_1.createToolCallHandler;
51245
+ } });
51246
+ Object.defineProperty(exports2, "bindToolCallHandler", { enumerable: true, get: function() {
51247
+ return cwtools_shared_1.bindToolCallHandler;
51248
+ } });
50041
51249
  function toMcpCallToolResult(result) {
50042
51250
  return {
50043
51251
  content: [
@@ -50095,6 +51303,9 @@ var require_bridgeProxy = __commonJS({
50095
51303
  };
50096
51304
  })();
50097
51305
  Object.defineProperty(exports2, "__esModule", { value: true });
51306
+ exports2.fallbackBridgeTools = fallbackBridgeTools;
51307
+ exports2.fallbackBridgeResources = fallbackBridgeResources;
51308
+ exports2.localBridgeToolDenied = localBridgeToolDenied;
50098
51309
  exports2.createBridgeProxyMcpServer = createBridgeProxyMcpServer;
50099
51310
  exports2.assertBridgeWorkspaceMatches = assertBridgeWorkspaceMatches;
50100
51311
  var fs = __importStar(require("fs"));
@@ -50102,12 +51313,37 @@ var require_bridgeProxy = __commonJS({
50102
51313
  var url_1 = require("url");
50103
51314
  var index_js_1 = require_server2();
50104
51315
  var types_js_1 = require_types2();
50105
- var vscodeCache_1 = require_vscodeCache();
51316
+ var cwtools_shared_1 = require_dist();
51317
+ var vscodeCache_1 = require_vscodeCache2();
50106
51318
  var resources_1 = require_resources();
50107
51319
  var toolRegistrar_1 = require_toolRegistrar();
50108
51320
  var toolHandlers_1 = require_toolHandlers2();
50109
51321
  var BRIDGE_MANIFEST_FILE = "bridge-manifest.json";
50110
51322
  var BRIDGE_PROTOCOL_VERSION = 1;
51323
+ function fallbackBridgeTools(project, includeWrites) {
51324
+ if (project.kind === "unsupported" || project.kind === "ambiguous")
51325
+ return [];
51326
+ return (0, toolRegistrar_1.listRegisteredTools)({ includeWrites, cwtOnly: project.kind === "cwt-only" });
51327
+ }
51328
+ function fallbackBridgeResources(project) {
51329
+ if (project.kind === "unsupported" || project.kind === "ambiguous")
51330
+ return [];
51331
+ const resources = (0, resources_1.listResources)();
51332
+ return project.kind === "cwt-only" ? resources.filter((resource) => resource.uri === "cwtools://knowledge/diagnostic-routing") : resources;
51333
+ }
51334
+ function localBridgeToolDenied(project, name) {
51335
+ if (project.kind !== "unsupported" && project.kind !== "ambiguous" && (project.kind !== "cwt-only" || fallbackBridgeTools(project, true).some((tool) => tool.name === name)))
51336
+ return void 0;
51337
+ return {
51338
+ ok: false,
51339
+ status: "denied",
51340
+ source: "cwtools-mcp-bridge-proxy",
51341
+ error: {
51342
+ code: project.kind === "ambiguous" ? "project_ambiguous" : project.kind === "unsupported" ? "project_not_supported" : "tool_not_available_in_cwt_only",
51343
+ message: project.kind === "cwt-only" ? `Tool '${name}' requires a full Paradox game model and is not available in a CWT-only workspace.` : project.reason
51344
+ }
51345
+ };
51346
+ }
50111
51347
  function createBridgeProxyMcpServer(config) {
50112
51348
  const server = new index_js_1.Server({
50113
51349
  name: "cwtools-mcp",
@@ -50126,25 +51362,65 @@ var require_bridgeProxy = __commonJS({
50126
51362
  });
50127
51363
  server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => {
50128
51364
  try {
51365
+ const manifest = await readBridgeManifest(config, server);
51366
+ if (!manifest.project) {
51367
+ const project = await detectProxyWorkspace(config, server);
51368
+ return { tools: fallbackBridgeTools(project, config.enableWrites) };
51369
+ }
50129
51370
  return await bridgeRpc(config, server, "tools/list", {
50130
51371
  allowDomainWrites: config.enableWrites
50131
- });
51372
+ }, manifest);
50132
51373
  } catch {
50133
- return { tools: (0, toolRegistrar_1.listRegisteredTools)({ includeWrites: config.enableWrites }) };
51374
+ try {
51375
+ const project = await detectProxyWorkspace(config, server);
51376
+ return { tools: fallbackBridgeTools(project, config.enableWrites) };
51377
+ } catch {
51378
+ return { tools: [] };
51379
+ }
50134
51380
  }
50135
51381
  });
50136
51382
  server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => {
50137
51383
  try {
50138
- return await bridgeRpc(config, server, "resources/list", {});
51384
+ const manifest = await readBridgeManifest(config, server);
51385
+ if (!manifest.project) {
51386
+ const project = await detectProxyWorkspace(config, server);
51387
+ return { resources: fallbackBridgeResources(project) };
51388
+ }
51389
+ return await bridgeRpc(config, server, "resources/list", {}, manifest);
50139
51390
  } catch {
50140
- return { resources: (0, resources_1.listResources)() };
51391
+ try {
51392
+ const project = await detectProxyWorkspace(config, server);
51393
+ return { resources: fallbackBridgeResources(project) };
51394
+ } catch {
51395
+ return { resources: [] };
51396
+ }
50141
51397
  }
50142
51398
  });
50143
51399
  server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request) => {
50144
51400
  try {
51401
+ const manifest = await readBridgeManifest(config, server);
51402
+ if (!manifest.project) {
51403
+ const project = await detectProxyWorkspace(config, server);
51404
+ if (!fallbackBridgeResources(project).some((resource) => resource.uri === request.params.uri)) {
51405
+ return {
51406
+ contents: [{
51407
+ uri: request.params.uri,
51408
+ mimeType: "application/json",
51409
+ text: `${JSON.stringify({
51410
+ status: "error",
51411
+ error: {
51412
+ code: project.kind === "ambiguous" ? "project_ambiguous" : project.kind === "unsupported" ? "project_not_supported" : "resource_not_available_in_cwt_only",
51413
+ message: project.reason
51414
+ }
51415
+ }, null, 2)}
51416
+ `
51417
+ }]
51418
+ };
51419
+ }
51420
+ }
50145
51421
  return await bridgeRpc(config, server, "resources/read", {
50146
51422
  uri: request.params.uri
50147
- });
51423
+ }, manifest);
50148
51424
  } catch (error) {
50149
51425
  return {
50150
51426
  contents: [
@@ -50161,20 +51437,34 @@ var require_bridgeProxy = __commonJS({
50161
51437
  server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
50162
51438
  try {
50163
51439
  const args = request.params.arguments && typeof request.params.arguments === "object" ? request.params.arguments : {};
51440
+ const manifest = await readBridgeManifest(config, server);
51441
+ if (!manifest.project) {
51442
+ const project = await detectProxyWorkspace(config, server);
51443
+ const denied = localBridgeToolDenied(project, request.params.name);
51444
+ if (denied)
51445
+ return (0, toolHandlers_1.toMcpCallToolResult)(denied);
51446
+ }
50164
51447
  const result = await bridgeRpc(config, server, "tools/call", {
50165
51448
  name: request.params.name,
50166
51449
  arguments: args,
50167
51450
  allowDomainWrites: config.enableWrites
50168
- });
51451
+ }, manifest);
50169
51452
  return normalizeCallToolResult(result);
50170
51453
  } catch (error) {
51454
+ try {
51455
+ const project = await detectProxyWorkspace(config, server);
51456
+ const denied = localBridgeToolDenied(project, request.params.name);
51457
+ if (denied)
51458
+ return (0, toolHandlers_1.toMcpCallToolResult)(denied);
51459
+ } catch {
51460
+ }
50171
51461
  return (0, toolHandlers_1.toMcpCallToolResult)(unavailableResult(error));
50172
51462
  }
50173
51463
  });
50174
51464
  return server;
50175
51465
  }
50176
- async function bridgeRpc(config, server, method, params) {
50177
- const manifest = await readBridgeManifest(config, server);
51466
+ async function bridgeRpc(config, server, method, params, knownManifest) {
51467
+ const manifest = knownManifest ?? await readBridgeManifest(config, server);
50178
51468
  const controller = new AbortController();
50179
51469
  const timer = setTimeout(() => controller.abort(), 3e4);
50180
51470
  try {
@@ -50236,6 +51526,19 @@ var require_bridgeProxy = __commonJS({
50236
51526
  }
50237
51527
  return { roots: [config.workspaceRoot], source: "MCP process cwd" };
50238
51528
  }
51529
+ async function detectProxyWorkspace(config, server) {
51530
+ const expected = await resolveExpectedWorkspace(config, server);
51531
+ if (expected.roots.length > 1) {
51532
+ return {
51533
+ kind: "ambiguous",
51534
+ strength: "none",
51535
+ evidence: [],
51536
+ candidates: [...expected.roots].sort(),
51537
+ reason: `Multiple MCP workspace roots are ambiguous for the CWTools bridge: ${expected.roots.join(", ")}`
51538
+ };
51539
+ }
51540
+ return (0, cwtools_shared_1.detectWorkspaceProject)(expected.roots[0] ?? config.workspaceRoot, () => void 0);
51541
+ }
50239
51542
  async function readClientWorkspaceRoots(server) {
50240
51543
  if (!server.getClientCapabilities()?.roots)
50241
51544
  return [];
@@ -52842,14 +54145,15 @@ var require_server3 = __commonJS({
52842
54145
  "dist/server.js"(exports2) {
52843
54146
  "use strict";
52844
54147
  Object.defineProperty(exports2, "__esModule", { value: true });
54148
+ exports2.listServerTools = listServerTools;
52845
54149
  exports2.createCwtoolsMcpServer = createCwtoolsMcpServer;
52846
54150
  var index_js_1 = require_server2();
52847
54151
  var types_js_1 = require_types2();
52848
54152
  var toolRegistrar_1 = require_toolRegistrar();
52849
54153
  var toolHandlers_1 = require_toolHandlers2();
52850
54154
  var resources_1 = require_resources();
52851
- var SERVER_INSTRUCTIONS = [
52852
- "CWTools is a read-only semantic service for Paradox mods. Ground every",
54155
+ var FULL_SERVER_INSTRUCTIONS = [
54156
+ "CWTools provides semantic and whitelisted domain-write tools for Paradox mods. Ground every",
52853
54157
  "claim about the mod in these tools instead of memory \u2014 PDX identifiers and syntax",
52854
54158
  "are routinely hallucinated.",
52855
54159
  "",
@@ -52872,9 +54176,31 @@ var require_server3 = __commonJS({
52872
54176
  "- Results carry vanillaCache metadata: if available is false, vanilla IDs are missing",
52873
54177
  " and references to them may show as false errors.",
52874
54178
  "",
52875
- "This server never writes files \u2014 perform edits with your own environment, then",
52876
- "re-check with get_diagnostics."
54179
+ "Use only the exposed whitelisted domain-write tools for writes, then re-check",
54180
+ "with get_diagnostics. Non-whitelisted writes remain unavailable."
52877
54181
  ].join("\n");
54182
+ function serverInstructions(host) {
54183
+ if (host.projectSupported === false) {
54184
+ return `CWTools is unavailable for this workspace: ${host.projectSupportReason ?? "not a Paradox/CWT project."}`;
54185
+ }
54186
+ if (host.projectKind === "cwt-only") {
54187
+ return "CWTools is running in CWT-only mode. Use the exposed document, navigation, and diagnostics tools for CWT rules; no game model is loaded.";
54188
+ }
54189
+ if (host.projectGameId === "paradox") {
54190
+ return `${FULL_SERVER_INSTRUCTIONS}
54191
+
54192
+ 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.`;
54193
+ }
54194
+ return FULL_SERVER_INSTRUCTIONS;
54195
+ }
54196
+ function listServerTools(host) {
54197
+ if (host.projectSupported === false || host.projectKind === "unsupported" || host.projectKind === "ambiguous")
54198
+ return [];
54199
+ return (0, toolRegistrar_1.listRegisteredTools)({
54200
+ includeWrites: host.writesEnabled === true && host.readonlyMode === false,
54201
+ cwtOnly: host.projectKind === "cwt-only"
54202
+ });
54203
+ }
52878
54204
  function createCwtoolsMcpServer(host, options = {}) {
52879
54205
  const supported = host.projectSupported !== false;
52880
54206
  const server = new index_js_1.Server({
@@ -52885,12 +54211,10 @@ var require_server3 = __commonJS({
52885
54211
  resources: {},
52886
54212
  tools: {}
52887
54213
  },
52888
- instructions: SERVER_INSTRUCTIONS
54214
+ instructions: serverInstructions(host)
52889
54215
  });
52890
54216
  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
- }));
54217
+ server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({ tools: listServerTools(host) }));
52894
54218
  server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async () => ({
52895
54219
  resources: (0, resources_1.listResources)(host)
52896
54220
  }));
@@ -52902,8 +54226,8 @@ var require_server3 = __commonJS({
52902
54226
  status: "denied",
52903
54227
  source: "cwtools-mcp",
52904
54228
  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.`
54229
+ code: host.projectKind === "ambiguous" ? "project_ambiguous" : "project_not_supported",
54230
+ 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
54231
  }
52908
54232
  });
52909
54233
  }
@@ -52919,7 +54243,7 @@ var require_server3 = __commonJS({
52919
54243
  // dist/cli.js
52920
54244
  Object.defineProperty(exports, "__esModule", { value: true });
52921
54245
  var config_1 = require_config();
52922
- var nodeHostServices_1 = require_nodeHostServices();
54246
+ var nodeHostServices_1 = require_nodeHostServices2();
52923
54247
  var bridgeProxy_1 = require_bridgeProxy();
52924
54248
  var transportHttp_1 = require_transportHttp();
52925
54249
  var transportStdio_1 = require_transportStdio();