hoi4-agent-tools 4.11.0 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/bin/stdio.js +8 -10
  3. package/dist/hoi4_agent_tools/core/configuration.js +13 -0
  4. package/dist/hoi4_agent_tools/core/engine.js +18 -2
  5. package/dist/hoi4_agent_tools/core/job-store.js +1 -1
  6. package/dist/hoi4_agent_tools/focus/native-effects.js +1 -1
  7. package/dist/hoi4_agent_tools/map/gameplay/crossings.js +55 -16
  8. package/dist/hoi4_agent_tools/map/operations.js +37 -8
  9. package/dist/hoi4_agent_tools/map/partition-fields.js +14 -0
  10. package/dist/hoi4_agent_tools/map/partition-geography.js +55 -6
  11. package/dist/hoi4_agent_tools/map/partition-provinces.js +105 -24
  12. package/dist/hoi4_agent_tools/map/references.js +87 -0
  13. package/dist/hoi4_agent_tools/map/relief/hydrology.js +16 -2
  14. package/dist/hoi4_agent_tools/map/relief/macro-relief.js +21 -1
  15. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +8 -5
  16. package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +1 -0
  17. package/dist/hoi4_agent_tools/map/service.js +13 -4
  18. package/dist/hoi4_agent_tools/map/tool-operations.js +6 -0
  19. package/dist/hoi4_agent_tools/map/world-provinces.js +36 -19
  20. package/dist/hoi4_agent_tools/map/world.js +168 -40
  21. package/dist/hoi4_agent_tools/mcp/plugins.js +74 -0
  22. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +7 -18
  23. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +64 -6
  24. package/dist/hoi4_agent_tools/probability/model.js +4 -4
  25. package/dist/hoi4_agent_tools/reference/mod-index.js +63 -65
  26. package/dist/hoi4_agent_tools/runtime.js +6 -2
  27. package/dist/hoi4_agent_tools/schemas/map.js +4 -0
  28. package/dist/hoi4_agent_tools/schemas/mod-tools.js +50 -0
  29. package/dist/hoi4_agent_tools/version.js +1 -1
  30. package/docs/configuration.md +10 -10
  31. package/docs/development.md +2 -0
  32. package/docs/jobs.md +1 -0
  33. package/docs/map.md +22 -18
  34. package/docs/reference.md +2 -0
  35. package/docs/research/probability-adapter-evidence.md +11 -1
  36. package/docs/tools.md +2 -3
  37. package/docs/troubleshooting.md +1 -1
  38. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  39. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  40. package/engine/bin/linux-x64/hoi4-engine +0 -0
  41. package/engine/bin/manifest.json +8 -8
  42. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  43. package/npm-shrinkwrap.json +2 -2
  44. package/package.json +1 -1
  45. package/schemas/configuration.schema.json +154 -138
  46. package/schemas/continuous-focus-palette.schema.json +1 -1
  47. package/schemas/custom-weighted-pool.schema.json +1 -1
  48. package/schemas/decision-inspect-input.schema.json +1 -1
  49. package/schemas/error-log-input.schema.json +1 -1
  50. package/schemas/event-feature-manifest.schema.json +1 -1
  51. package/schemas/focus-plan.schema.json +1 -1
  52. package/schemas/focus-planning-sidecar.schema.json +1 -1
  53. package/schemas/geography-model.schema.json +1 -1
  54. package/schemas/gui-animation-source.schema.json +1 -1
  55. package/schemas/gui-helper.schema.json +1 -1
  56. package/schemas/gui-scenario.schema.json +1 -1
  57. package/schemas/helper-expansion-request.schema.json +1 -1
  58. package/schemas/helper-expansion-summary.schema.json +1 -1
  59. package/schemas/impact-inspect-input.schema.json +1 -1
  60. package/schemas/map-operation.schema.json +152 -138
  61. package/schemas/mechanic-test-input.schema.json +1 -1
  62. package/schemas/mod-index-input.schema.json +1 -1
  63. package/schemas/operation-result.schema.json +1 -1
  64. package/schemas/package-check-input.schema.json +1 -1
  65. package/schemas/package-manifest.schema.json +1 -1
  66. package/schemas/probability-analysis-result.schema.json +1 -1
  67. package/schemas/probability-compare-input.schema.json +1 -1
  68. package/schemas/probability-evaluate-input.schema.json +1 -1
  69. package/schemas/probability-inspect-input.schema.json +1 -1
  70. package/schemas/probability-render-input.schema.json +1 -1
  71. package/schemas/probability-scenario-set.schema.json +1 -1
  72. package/schemas/probability-sequence-input.schema.json +1 -1
  73. package/schemas/probability-simulate-input.schema.json +1 -1
  74. package/schemas/probability-sweep-input.schema.json +1 -1
  75. package/schemas/reference-context-input.schema.json +1 -1
  76. package/schemas/reference-read-input.schema.json +1 -1
  77. package/schemas/reference-search-input.schema.json +1 -1
  78. package/schemas/reference-sheets.schema.json +1 -1
  79. package/schemas/scenario-suite.schema.json +1 -1
  80. package/schemas/scenario-test-input.schema.json +1 -1
  81. package/schemas/script-validate-input.schema.json +1 -1
  82. package/schemas/shared-scenario.schema.json +1 -1
  83. package/schemas/source-lookup-input.schema.json +1 -1
  84. package/server.json +2 -2
  85. package/dist/hoi4_agent_tools/mcp/tools/chaosx.js +0 -509
@@ -651,10 +651,44 @@ export function generateWorld(spec, context, options = {}) {
651
651
  height,
652
652
  land: (pixel) => surface.kind[pixel] === LAND,
653
653
  });
654
- if (pointProblems.length > 0 && options.riverCheck !== true)
655
- throw realmPointsError(pointProblems);
654
+ // Cities and capitals on impassable land are known from the impassable mask alone, so they are
655
+ // found before the synthesis, not after the partition.
656
+ const onImpassable = ({ x, y }) => {
657
+ const px = Math.floor(x);
658
+ const py = Math.floor(y);
659
+ return (px >= 0 && py >= 0 && px < width && py < height && impassableMask?.[py * width + px] === 1);
660
+ };
661
+ const offendingCities = (spec.referenceCities ?? []).filter(onImpassable);
662
+ const cityError = offendingCities.length === 0
663
+ ? undefined
664
+ : new ServiceError('MAP_FEATURE_IN_IMPASSABLE', `${offendingCities.length} city or cities stand on impassable land: ${offendingCities
665
+ .slice(0, 5)
666
+ .map(({ name, x, y }) => `${name} (${Math.round(x)}, ${Math.round(y)})`)
667
+ .join('; ')}. Move them or repaint the land.`, { cities: offendingCities.slice(0, 20) });
668
+ if (options.riverCheck !== true) {
669
+ if (pointProblems.length > 0)
670
+ throw realmPointsError(pointProblems);
671
+ if (cityError !== undefined)
672
+ throw cityError;
673
+ }
656
674
  if (options.riverCheck === true && geography !== undefined) {
657
- let failure;
675
+ // The check reports every blocking problem it can find without a partition in one answer:
676
+ // realm points, cities and capitals on impassable land, unreachable rivers and filled passes.
677
+ const blocking = [];
678
+ if (pointProblems.length > 0)
679
+ blocking.push(realmPointsError(pointProblems));
680
+ if (cityError !== undefined)
681
+ blocking.push(cityError);
682
+ const walledCapitals = (spec.realms?.list ?? []).filter(({ capital }) => onImpassable(capital));
683
+ if (walledCapitals.length > 0)
684
+ blocking.push(new ServiceError('MAP_FEATURE_IN_IMPASSABLE', `${walledCapitals.length} capital(s) stand on impassable land: ${walledCapitals
685
+ .slice(0, 5)
686
+ .map(({ tag, capital }) => `${tag} (${Math.round(capital.x)}, ${Math.round(capital.y)})`)
687
+ .join('; ')}. Move them onto passable land.`, {
688
+ capitals: walledCapitals
689
+ .slice(0, 20)
690
+ .map(({ tag, capital }) => ({ tag, x: capital.x, y: capital.y })),
691
+ }));
658
692
  try {
659
693
  const checked = checkTerrainRivers({
660
694
  geography,
@@ -670,34 +704,26 @@ export function generateWorld(spec, context, options = {}) {
670
704
  painted,
671
705
  signal: options.signal,
672
706
  });
673
- for (const note of checked) {
674
- if (note.severity === 'error')
675
- throw new ServiceError(note.code, note.message, note.details);
707
+ for (const note of checked)
676
708
  notes.push({
677
709
  code: note.code,
678
710
  severity: note.severity,
679
711
  message: note.message,
680
712
  ...(note.details === undefined ? {} : { details: note.details }),
681
713
  });
682
- }
683
714
  }
684
715
  catch (error) {
685
716
  if (!(error instanceof ServiceError))
686
717
  throw error;
687
- failure = error;
688
- }
689
- // The preview reports the realm points and the synthesis together.
690
- if (pointProblems.length > 0) {
691
- const pointError = realmPointsError(pointProblems);
692
- throw failure === undefined
693
- ? pointError
694
- : new ServiceError(pointError.code, `${pointError.message}. The relief synthesis also failed: ${failure.message}`, {
695
- ...pointError.details,
696
- synthesis: { code: failure.code, message: failure.message, details: failure.details },
697
- });
718
+ blocking.push(error);
698
719
  }
699
- if (failure !== undefined)
700
- throw failure;
720
+ for (const error of blocking)
721
+ notes.push({
722
+ code: error.code,
723
+ severity: 'error',
724
+ message: error.message,
725
+ details: error.details,
726
+ });
701
727
  return {
702
728
  files: [],
703
729
  warnings: [],
@@ -901,15 +927,6 @@ export function generateWorld(spec, context, options = {}) {
901
927
  };
902
928
  const wallProvinces = majorityIn(wallMask);
903
929
  const impassableProvinces = new Set([...wallProvinces, ...majorityIn(impassableMask)]);
904
- const offendingCities = (spec.referenceCities ?? []).filter(({ x, y }) => {
905
- const pixel = Math.floor(y) * width + Math.floor(x);
906
- return impassableMask?.[pixel] === 1;
907
- });
908
- if (offendingCities.length > 0)
909
- throw new ServiceError('MAP_FEATURE_IN_IMPASSABLE', `${offendingCities.length} city or cities stand on impassable land: ${offendingCities
910
- .slice(0, 5)
911
- .map(({ name, x, y }) => `${name} (${Math.round(x)}, ${Math.round(y)})`)
912
- .join('; ')}. Move them or repaint the land.`, { cities: offendingCities.slice(0, 20) });
913
930
  if (landIds.length < spec.countries.length)
914
931
  throw new ServiceError('MAP_WORLD_LAND_TOO_SMALL', 'The generated land has fewer provinces than countries; raise landCoverage or lower landProvincePixels', { landProvinces: landIds.length, countries: spec.countries.length });
915
932
  const coastal = (id) => [...provinces.neighbors[id]].some((other) => provinces.kind[id] === SEA
@@ -978,19 +995,50 @@ export function generateWorld(spec, context, options = {}) {
978
995
  terrain.set(id, referenceTerrainNames[selected]);
979
996
  }
980
997
  }
998
+ // Impassable land (the `wall` at the seam, painted or regional impassable land) joins no
999
+ // landmasses or strategic regions: no army crosses it, and the wall's two halves meet only
1000
+ // across the seam. Its connected pieces, never joined across the seam, follow the passable
1001
+ // land they border. A world without passable land keeps the plain land connectivity.
1002
+ const separateImpassable = impassableProvinces.size > 0 && landIds.some((id) => !impassableProvinces.has(id));
1003
+ const acrossSeam = (left, right) => Math.abs(provinces.sumX[left] / provinces.size[left] -
1004
+ provinces.sumX[right] / provinces.size[right]) >
1005
+ width / 2;
1006
+ const impassableComponents = [];
1007
+ if (separateImpassable) {
1008
+ const seen = new Set();
1009
+ for (const start of landIds) {
1010
+ if (!impassableProvinces.has(start) || seen.has(start))
1011
+ continue;
1012
+ const component = [start];
1013
+ seen.add(start);
1014
+ // The array iterator also visits the provinces pushed while it runs.
1015
+ for (const current of component) {
1016
+ for (const next of provinces.neighbors[current])
1017
+ if (impassableProvinces.has(next) && !seen.has(next) && !acrossSeam(current, next)) {
1018
+ seen.add(next);
1019
+ component.push(next);
1020
+ }
1021
+ }
1022
+ impassableComponents.push(component);
1023
+ }
1024
+ }
1025
+ const joinsLand = (id) => provinces.kind[id] === LAND && !(separateImpassable && impassableProvinces.has(id));
1026
+ const passableLandIds = separateImpassable
1027
+ ? landIds.filter((id) => !impassableProvinces.has(id))
1028
+ : landIds;
981
1029
  // Continents: the largest land masses, with islands joining the nearest one.
982
1030
  const landParts = new Map();
983
1031
  {
984
1032
  let part = 0;
985
1033
  for (const start of landIds) {
986
- if (landParts.has(start))
1034
+ if (landParts.has(start) || !joinsLand(start))
987
1035
  continue;
988
1036
  const queue = [start];
989
1037
  landParts.set(start, part);
990
1038
  while (queue.length > 0) {
991
1039
  const current = queue.pop();
992
1040
  for (const next of provinces.neighbors[current])
993
- if (provinces.kind[next] === LAND && !landParts.has(next)) {
1041
+ if (joinsLand(next) && !landParts.has(next)) {
994
1042
  landParts.set(next, part);
995
1043
  queue.push(next);
996
1044
  }
@@ -1033,6 +1081,45 @@ export function generateWorld(spec, context, options = {}) {
1033
1081
  best = position;
1034
1082
  continentOfPart.set(part, best + 1);
1035
1083
  }
1084
+ // Each impassable piece takes the landmass of its largest passable neighbour, or, when it
1085
+ // borders only water (as the wall usually does), the landmass of the nearest passable province.
1086
+ for (const component of impassableComponents) {
1087
+ let chosen = -1;
1088
+ for (const id of component)
1089
+ for (const next of provinces.neighbors[id]) {
1090
+ const part = landParts.get(next);
1091
+ if (part === undefined || impassableProvinces.has(next) || acrossSeam(id, next))
1092
+ continue;
1093
+ if (chosen < 0 ||
1094
+ partSizes.get(part) > partSizes.get(chosen) ||
1095
+ (partSizes.get(part) === partSizes.get(chosen) && part < chosen))
1096
+ chosen = part;
1097
+ }
1098
+ if (chosen < 0) {
1099
+ let sx = 0;
1100
+ let sy = 0;
1101
+ let n = 0;
1102
+ for (const id of component) {
1103
+ sx += provinces.sumX[id];
1104
+ sy += provinces.sumY[id];
1105
+ n += provinces.size[id];
1106
+ }
1107
+ let nearest = Number.POSITIVE_INFINITY;
1108
+ for (const id of landIds) {
1109
+ if (impassableProvinces.has(id))
1110
+ continue;
1111
+ const c = center(id);
1112
+ const distance = Math.hypot(c.x - sx / n, c.y - sy / n);
1113
+ if (distance < nearest) {
1114
+ nearest = distance;
1115
+ chosen = landParts.get(id);
1116
+ }
1117
+ }
1118
+ }
1119
+ for (const id of component)
1120
+ landParts.set(id, chosen);
1121
+ }
1122
+ const generatedContinentKeys = majorParts.map((_, index) => `world_continent_${index + 1}`);
1036
1123
  const continentNames = majorParts.map((_, index) => spec.continentNames?.[index] ?? `Continent ${String.fromCharCode(65 + (index % 26))}`);
1037
1124
  // Countries: grow territories from spread-out capitals in proportion to their shares.
1038
1125
  const owner = new Map();
@@ -1194,7 +1281,12 @@ export function generateWorld(spec, context, options = {}) {
1194
1281
  }
1195
1282
  const shares = spec.countries.map((country) => Math.max(0.05, country.share ?? 1));
1196
1283
  const owned = new Array(countryCount).fill(0);
1284
+ // Countries grow over passable land only, so none crosses impassable land or the wall from one
1285
+ // edge to the other. Impassable provinces stay unowned here; their states take the owner of the
1286
+ // passable state they link to (finishImpassableStates).
1197
1287
  for (const [id, country] of realmRules?.forced ?? referenceOwners) {
1288
+ if (!joinsLand(id))
1289
+ continue;
1198
1290
  owner.set(id, country);
1199
1291
  owned[country] += provinces.size[id];
1200
1292
  }
@@ -1206,7 +1298,7 @@ export function generateWorld(spec, context, options = {}) {
1206
1298
  owner.set(capital, index);
1207
1299
  if (realmRules !== undefined)
1208
1300
  return [...owner]
1209
- .filter(([, country]) => country === index)
1301
+ .filter(([id, country]) => country === index && joinsLand(id))
1210
1302
  .flatMap(([id]) => [...provinces.neighbors[id]]);
1211
1303
  return [...provinces.neighbors[capital]];
1212
1304
  });
@@ -1214,13 +1306,13 @@ export function generateWorld(spec, context, options = {}) {
1214
1306
  // The feature-aware partition grows generated countries along its natural lines (ADR 0060).
1215
1307
  // Workspace-owned countries keep the realm growth with its forced and blocked land (ADR 0069).
1216
1308
  if (featurePartition !== undefined && referenceOwners.size === 0 && realmRules === undefined) {
1217
- const atoms = buildTerritoryAtoms(territoryGraphFromPartition(featurePartition.graph, provinces.sumX, provinces.sumY), landIds.map((id) => [id]));
1309
+ const atoms = buildTerritoryAtoms(territoryGraphFromPartition(featurePartition.graph, provinces.sumX, provinces.sumY), passableLandIds.map((id) => [id]));
1218
1310
  const grown = growTerritory(atoms, spec.countries.map((country, index) => ({
1219
1311
  tag: country.tag,
1220
1312
  weight: shares[index],
1221
1313
  seeds: [atoms.atomOfProvince[capitals[index]]],
1222
1314
  })), { seed: spec.seed });
1223
- for (const [atom, id] of landIds.entries())
1315
+ for (const [atom, id] of passableLandIds.entries())
1224
1316
  if (grown.owner[atom] >= 0)
1225
1317
  owner.set(id, grown.owner[atom]);
1226
1318
  grownByTerritory = true;
@@ -1228,7 +1320,7 @@ export function generateWorld(spec, context, options = {}) {
1228
1320
  while (!grownByTerritory) {
1229
1321
  let chosen = -1;
1230
1322
  for (let index = 0; index < countryCount; index += 1) {
1231
- frontiers[index] = frontiers[index].filter((id) => provinces.kind[id] === LAND && !owner.has(id) && !blockedFor(index, id));
1323
+ frontiers[index] = frontiers[index].filter((id) => joinsLand(id) && !owner.has(id) && !blockedFor(index, id));
1232
1324
  if (frontiers[index].length === 0)
1233
1325
  continue;
1234
1326
  if (chosen < 0 || owned[index] / shares[index] < owned[chosen] / shares[chosen])
@@ -1247,7 +1339,7 @@ export function generateWorld(spec, context, options = {}) {
1247
1339
  // Land no workspace country reached follows the island rule; the rest of the land is unowned.
1248
1340
  if (realmRules !== undefined)
1249
1341
  assignUnreachedRealmLand({
1250
- landIds,
1342
+ landIds: passableLandIds,
1251
1343
  owner,
1252
1344
  unowned: unownedLand,
1253
1345
  capitals,
@@ -1257,7 +1349,7 @@ export function generateWorld(spec, context, options = {}) {
1257
1349
  center,
1258
1350
  });
1259
1351
  // Islands no country reached go to the nearest capital's country.
1260
- for (const id of landIds)
1352
+ for (const id of passableLandIds)
1261
1353
  if (!owner.has(id) && !unownedLand.has(id)) {
1262
1354
  const c = center(id);
1263
1355
  let best = 0;
@@ -1269,9 +1361,40 @@ export function generateWorld(spec, context, options = {}) {
1269
1361
  }
1270
1362
  // Strategic regions: land regions over the land graph, sea regions over the sea graph.
1271
1363
  const graph = (id) => provinces.neighbors[id];
1364
+ // Impassable land is clustered apart from passable land, so no region bridges two landmasses
1365
+ // over it or spans the seam over the wall.
1272
1366
  const landRegion = featurePartition === undefined
1273
- ? growClusters(landIds, graph, spec.landProvincesPerRegion, random)
1274
- : clusterRegions(featurePartition, landIds, 'land');
1367
+ ? growClusters(passableLandIds, graph, spec.landProvincesPerRegion, random)
1368
+ : clusterRegions(featurePartition, passableLandIds, 'land');
1369
+ if (separateImpassable) {
1370
+ const regionTarget = featurePartition?.tuning.regions.target ?? spec.landProvincesPerRegion;
1371
+ let nextRegion = Math.max(-1, ...landRegion.values()) + 1;
1372
+ for (const component of impassableComponents) {
1373
+ // A piece no larger than a region joins the passable region it borders most; a larger
1374
+ // piece, or one that borders only water, forms regions of its own.
1375
+ const contacts = new Map();
1376
+ for (const id of component)
1377
+ for (const next of provinces.neighbors[id]) {
1378
+ const region = landRegion.get(next);
1379
+ if (region === undefined || impassableProvinces.has(next) || acrossSeam(id, next))
1380
+ continue;
1381
+ contacts.set(region, (contacts.get(region) ?? 0) + 1);
1382
+ }
1383
+ if (contacts.size > 0 && component.length <= regionTarget) {
1384
+ const [joined] = [...contacts].sort((left, right) => right[1] - left[1] || left[0] - right[0])[0];
1385
+ for (const id of component)
1386
+ landRegion.set(id, joined);
1387
+ continue;
1388
+ }
1389
+ const clusters = growClusters(component, (id) => [...provinces.neighbors[id]].filter((next) => !acrossSeam(id, next)), regionTarget, random);
1390
+ let largest = -1;
1391
+ for (const [id, cluster] of clusters) {
1392
+ landRegion.set(id, nextRegion + cluster);
1393
+ largest = Math.max(largest, cluster);
1394
+ }
1395
+ nextRegion += largest + 1;
1396
+ }
1397
+ }
1275
1398
  const seaRegion = featurePartition === undefined
1276
1399
  ? growClusters(seaIds, graph, spec.seaProvincesPerRegion, random)
1277
1400
  : clusterRegions(featurePartition, seaIds, 'sea');
@@ -1588,7 +1711,7 @@ export function generateWorld(spec, context, options = {}) {
1588
1711
  'tree = { 3 4 7 10 }',
1589
1712
  '',
1590
1713
  ].join('\n')));
1591
- add(`${map}/continent.txt`, text(`continents = {\n${[...new Set([...continentNames.map((_, index) => `world_continent_${index + 1}`), ...(context.continentKeys ?? [])])].map((key) => `\t${key}`).join('\n')}\n}\n`));
1714
+ add(`${map}/continent.txt`, text(`continents = {\n${[...new Set([...generatedContinentKeys, ...(spec.inheritedContinents === 'drop' ? [] : (context.continentKeys ?? []))])].map((key) => `\t${key}`).join('\n')}\n}\n`));
1592
1715
  const rimRows = hasRimRange(edge)
1593
1716
  ? rimAdjacencyRows({
1594
1717
  provincePixels: provinces.pixel,
@@ -2250,5 +2373,10 @@ export function generateWorld(spec, context, options = {}) {
2250
2373
  rivers: riverCount,
2251
2374
  },
2252
2375
  ...(spec.realms === undefined ? {} : { realms: realmSummary() }),
2376
+ ...(spec.inheritedContinents === 'drop'
2377
+ ? {
2378
+ droppedContinents: (context.continentKeys ?? []).filter((key) => !generatedContinentKeys.includes(key)),
2379
+ }
2380
+ : {}),
2253
2381
  };
2254
2382
  }
@@ -0,0 +1,74 @@
1
+ import { lstat, realpath } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ const PLUGIN_TOOL_NAME = /^(?!hoi4\.)[a-z][a-z0-9_]{1,31}\.[a-z][a-z0-9_]{1,63}$/u;
5
+ const MAX_PLUGIN_TOOLS = 16;
6
+ const SERVER_MODULE_ROOT = fileURLToPath(new URL('..', import.meta.url));
7
+ export class PluginError extends Error {
8
+ code;
9
+ constructor(code, message) {
10
+ super(message);
11
+ this.name = 'PluginError';
12
+ this.code = code;
13
+ }
14
+ }
15
+ function sameFile(left, right) {
16
+ const normalize = (value) => process.platform === 'win32' ? path.normalize(value).toLowerCase() : path.normalize(value);
17
+ return normalize(left) === normalize(right);
18
+ }
19
+ function createHost(serverVersion) {
20
+ return {
21
+ serverVersion,
22
+ importServerModule: async (relativePath) => {
23
+ const target = path.resolve(SERVER_MODULE_ROOT, relativePath);
24
+ if (!target.startsWith(SERVER_MODULE_ROOT) ||
25
+ !/\.(?:js|ts)$/u.test(target) ||
26
+ relativePath.includes('..'))
27
+ throw new PluginError('PLUGIN_IMPORT_REFUSED', `Not a server module: ${relativePath}`);
28
+ return (await import(pathToFileURL(target).href));
29
+ },
30
+ dependency: async (name) => name === 'zod' ? await import('zod/v4') : await import('sharp'),
31
+ };
32
+ }
33
+ /**
34
+ * Load every configured plugin. A listed file that does not exist is skipped, because a private
35
+ * plugin lives on one machine and the shared configuration may list it on others; `onSkipped`
36
+ * reports it. A file that exists and is not a plain `.mjs` or `.js` file, or that does not export
37
+ * a factory, is an error.
38
+ */
39
+ export async function loadPlugins(paths, serverVersion, onSkipped = () => undefined) {
40
+ const factories = [];
41
+ for (const file of paths) {
42
+ if (!path.isAbsolute(file) || !/\.(?:mjs|js)$/u.test(file))
43
+ throw new PluginError('PLUGIN_PATH_INVALID', 'A plugin path is absolute and names a .mjs or .js file');
44
+ const info = await lstat(file).catch(() => undefined);
45
+ if (info === undefined) {
46
+ onSkipped(file, 'file not found');
47
+ continue;
48
+ }
49
+ if (!info.isFile() || info.isSymbolicLink())
50
+ throw new PluginError('PLUGIN_PATH_INVALID', 'A plugin is a plain file, not a link');
51
+ if (!sameFile(await realpath(file), file))
52
+ throw new PluginError('PLUGIN_PATH_INVALID', 'A plugin path passes through a link or a short 8.3 name; list its full canonical path');
53
+ const loaded = (await import(pathToFileURL(file).href));
54
+ if (typeof loaded.default !== 'function')
55
+ throw new PluginError('PLUGIN_INVALID', 'A plugin exports a factory function as default');
56
+ factories.push(await loaded.default(createHost(serverVersion)));
57
+ }
58
+ if (factories.length === 0)
59
+ return undefined;
60
+ return (engine, context) => {
61
+ const tools = factories.flatMap((factory) => factory(engine, context));
62
+ const seen = new Set();
63
+ if (tools.length > MAX_PLUGIN_TOOLS)
64
+ throw new PluginError('PLUGIN_INVALID', `Plugins add at most ${MAX_PLUGIN_TOOLS} tools`);
65
+ for (const { definition } of tools) {
66
+ if (!PLUGIN_TOOL_NAME.test(definition.name))
67
+ throw new PluginError('PLUGIN_INVALID', `Plugin tool "${definition.name}" must be named <plugin>.<tool> and not start with hoi4.`);
68
+ if (seen.has(definition.name))
69
+ throw new PluginError('PLUGIN_INVALID', `Two plugin tools are named ${definition.name}`);
70
+ seen.add(definition.name);
71
+ }
72
+ return tools;
73
+ };
74
+ }
@@ -38,8 +38,8 @@ function clientCapabilities(envelope) {
38
38
  }
39
39
  /**
40
40
  * Modern operation/task factory, shared by the connection and HTTP serving entries.
41
- * The stdio entry explicitly opts into the two private ChaosX tools when configured.
42
- * HTTP remains mod-independent and never enables that private extension.
41
+ * The stdio entry adds the tools of the plugins its configuration lists (M-14).
42
+ * HTTP remains mod-independent and never loads a plugin.
43
43
  */
44
44
  export function createModernOperationServer(engine, context = {}, tasks = new OperationTaskService(engine), options = {}) {
45
45
  const adapter = new ModernTaskAdapter(tasks);
@@ -54,7 +54,7 @@ export function createModernOperationServer(engine, context = {}, tasks = new Op
54
54
  ...jobControlTools,
55
55
  ...(privateOperations === undefined
56
56
  ? []
57
- : [privateOperations.visual.definition, privateOperations.country.definition]),
57
+ : privateOperations.map(({ definition }) => definition)),
58
58
  ];
59
59
  const server = new ModernTaskRoutingServer({ name: PACKAGE_NAME, version: PACKAGE_VERSION }, {
60
60
  capabilities: {
@@ -148,22 +148,11 @@ export function createModernOperationServer(engine, context = {}, tasks = new Op
148
148
  const operations = operationContext === context || options.createPrivateTools === undefined
149
149
  ? privateOperations
150
150
  : options.createPrivateTools(engine, operationContext);
151
- const progress = modernProgressReporter(extra);
152
- if (definition.name === operations.visual.definition.name) {
153
- const result = await operations.visual.call(operations.visual.definition.inputSchema.parse(arguments_), progress);
151
+ const tool = operations.find((candidate) => candidate.definition.name === definition.name);
152
+ if (tool !== undefined) {
153
+ const result = await tool.call(input.data, modernProgressReporter(extra));
154
154
  if (result.isError !== true)
155
- operations.visual.definition.outputSchema.parse(result.structuredContent);
156
- return CallToolResultSchema.parse({
157
- ...result,
158
- resultType: 'complete',
159
- ttlMs: 0,
160
- cacheScope: 'private',
161
- });
162
- }
163
- if (definition.name === operations.country.definition.name) {
164
- const result = await operations.country.call(operations.country.definition.inputSchema.parse(arguments_), progress);
165
- if (result.isError !== true)
166
- operations.country.definition.outputSchema.parse(result.structuredContent);
155
+ definition.outputSchema?.parse(result.structuredContent);
167
156
  return CallToolResultSchema.parse({
168
157
  ...result,
169
158
  resultType: 'complete',
@@ -1,9 +1,24 @@
1
1
  import { serveStdio } from '@modelcontextprotocol/server/stdio';
2
+ import { progressReporter } from '../server/progress.js';
2
3
  import { createMcpServer } from '../server/create.js';
3
4
  import { createModernOperationServer } from '../server/create-modern-operations.js';
4
5
  import { BoundedStdioServerTransport, STDIO_MAX_FRAME_BYTES } from './bounded-stdio.js';
5
6
  import { FinalProtocolTransport } from './protocol-gate.js';
6
7
  const MAX_QUEUED_MESSAGES = 128;
8
+ /**
9
+ * Requests that only describe the server. They are answered while startup recovery still runs;
10
+ * every other message waits for it, in arrival order, so no request reads or writes a workspace
11
+ * whose interrupted rewrite is not yet recovered.
12
+ */
13
+ const ANSWERED_BEFORE_RECOVERY = new Set([
14
+ 'initialize',
15
+ 'notifications/initialized',
16
+ 'ping',
17
+ 'server/discover',
18
+ 'tools/list',
19
+ 'prompts/list',
20
+ 'logging/setLevel',
21
+ ]);
7
22
  function isRecord(value) {
8
23
  return typeof value === 'object' && value !== null && !Array.isArray(value);
9
24
  }
@@ -93,15 +108,12 @@ export async function serveNegotiatedStdio(engine, options) {
93
108
  reportError(error);
94
109
  pinned?.onerror(error);
95
110
  };
96
- physical.onmessage = (message) => {
97
- observer?.received(message);
111
+ const deliver = (message) => {
98
112
  if (pinned === undefined) {
99
113
  pinned = new PinnedStdioTransport(physical, reportError);
100
114
  try {
101
115
  if (isModernStdioOpening(message)) {
102
- serveStdio(() => createModernOperationServer(engine, {}, undefined, options.createModernPrivateTools === undefined
103
- ? {}
104
- : { createPrivateTools: options.createModernPrivateTools }), {
116
+ serveStdio(() => createModernOperationServer(engine, {}, undefined, options.plugins === undefined ? {} : { createPrivateTools: options.plugins }), {
105
117
  transport: pinned,
106
118
  legacy: 'reject',
107
119
  onerror: reportError,
@@ -109,7 +121,11 @@ export async function serveNegotiatedStdio(engine, options) {
109
121
  }
110
122
  else {
111
123
  const server = createMcpServer(engine, {});
112
- options.registerLegacy?.(server);
124
+ if (options.plugins !== undefined)
125
+ for (const tool of options.plugins(engine, {})) {
126
+ const { name, ...definition } = tool.definition;
127
+ server.registerTool(name, definition, (input, extra) => tool.call(input, progressReporter(extra)));
128
+ }
113
129
  server.server.onerror = reportError;
114
130
  void server.connect(new FinalProtocolTransport(pinned)).catch((error) => {
115
131
  options.onFailure(error);
@@ -125,6 +141,48 @@ export async function serveNegotiatedStdio(engine, options) {
125
141
  }
126
142
  pinned.receive(message);
127
143
  };
144
+ // Startup recovery: `held` until it ends, then `open`; `closed` drops every later message.
145
+ let recovery = 'held';
146
+ let heldBytes = 0;
147
+ const held = [];
148
+ const closeHeld = () => {
149
+ recovery = 'closed';
150
+ held.length = 0;
151
+ heldBytes = 0;
152
+ void physical.close();
153
+ };
154
+ engine.recovered().then(() => {
155
+ if (recovery === 'closed')
156
+ return;
157
+ recovery = 'open';
158
+ heldBytes = 0;
159
+ for (const message of held.splice(0))
160
+ deliver(message);
161
+ }, (error) => {
162
+ if (recovery === 'closed')
163
+ return;
164
+ options.onFailure(error);
165
+ closeHeld();
166
+ });
167
+ physical.onmessage = (message) => {
168
+ observer?.received(message);
169
+ if (recovery === 'closed')
170
+ return;
171
+ if (recovery === 'open' ||
172
+ (held.length === 0 &&
173
+ (!('method' in message) || ANSWERED_BEFORE_RECOVERY.has(message.method)))) {
174
+ deliver(message);
175
+ return;
176
+ }
177
+ const bytes = Buffer.byteLength(JSON.stringify(message)) + 1;
178
+ if (held.length >= MAX_QUEUED_MESSAGES || bytes > STDIO_MAX_FRAME_BYTES - heldBytes) {
179
+ reportError(new Error('Requests held during startup recovery exceeded their bounded limit'));
180
+ closeHeld();
181
+ return;
182
+ }
183
+ held.push(message);
184
+ heldBytes += bytes;
185
+ };
128
186
  await physical.start();
129
187
  return physical;
130
188
  }
@@ -1,5 +1,5 @@
1
1
  export const PROBABILITY_SCHEMA_VERSION = 1;
2
- export const PROBABILITY_ADAPTER_VERSION = 'hoi4-1.19.4.1.v1';
3
- export const VERIFIED_GAME_VERSION = 'Operation Postern 1.19.4.1 (f584)';
4
- export const VERIFIED_GAME_RAW_VERSION = '1.19.4.1';
5
- export const VERIFIED_GAME_CHECKSUM = 'f584';
2
+ export const PROBABILITY_ADAPTER_VERSION = 'hoi4-1.19.4.2.v1';
3
+ export const VERIFIED_GAME_VERSION = 'Operation Postern 1.19.4.2 (0bdb)';
4
+ export const VERIFIED_GAME_RAW_VERSION = '1.19.4.2';
5
+ export const VERIFIED_GAME_CHECKSUM = '0bdb';