hoi4-agent-tools 4.12.0 → 4.14.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 (96) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +3 -3
  3. package/dist/bin/setup.js +38 -0
  4. package/dist/bin/stdio.js +5 -1
  5. package/dist/hoi4_agent_tools/core/configuration.js +16 -0
  6. package/dist/hoi4_agent_tools/core/domain-tools.js +4 -0
  7. package/dist/hoi4_agent_tools/core/engine-check.js +87 -0
  8. package/dist/hoi4_agent_tools/core/engine-client.js +1 -1
  9. package/dist/hoi4_agent_tools/core/job-operation-registration.js +2 -0
  10. package/dist/hoi4_agent_tools/localisation/job-operations.js +42 -0
  11. package/dist/hoi4_agent_tools/localisation/write-diff.js +96 -0
  12. package/dist/hoi4_agent_tools/localisation/write-format.js +329 -0
  13. package/dist/hoi4_agent_tools/localisation/write-operations.js +213 -0
  14. package/dist/hoi4_agent_tools/localisation/write-plan.js +557 -0
  15. package/dist/hoi4_agent_tools/map/gameplay/crossing-validation.js +17 -0
  16. package/dist/hoi4_agent_tools/map/model.js +31 -1
  17. package/dist/hoi4_agent_tools/map/operations.js +2 -1
  18. package/dist/hoi4_agent_tools/map/world-edge.js +0 -25
  19. package/dist/hoi4_agent_tools/map/world.js +124 -34
  20. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +5 -0
  21. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +8 -3
  22. package/dist/hoi4_agent_tools/mcp/server/create.js +5 -1
  23. package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +10 -2
  24. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +2 -0
  25. package/dist/hoi4_agent_tools/mcp/server/tool-profiles.js +83 -0
  26. package/dist/hoi4_agent_tools/mcp/tools/localisation-write.js +21 -0
  27. package/dist/hoi4_agent_tools/mcp/tools/reference.js +34 -0
  28. package/dist/hoi4_agent_tools/mcp/transports/http.js +6 -1
  29. package/dist/hoi4_agent_tools/reference/compat-patch.js +555 -0
  30. package/dist/hoi4_agent_tools/reference/compat.js +255 -0
  31. package/dist/hoi4_agent_tools/reference/docs-pack.js +164 -0
  32. package/dist/hoi4_agent_tools/reference/docs-pack.json +339 -0
  33. package/dist/hoi4_agent_tools/reference/documented-commands.js +26 -0
  34. package/dist/hoi4_agent_tools/reference/error-explain.js +235 -0
  35. package/dist/hoi4_agent_tools/reference/error-explanations.json +262 -0
  36. package/dist/hoi4_agent_tools/reference/error-log.js +30 -10
  37. package/dist/hoi4_agent_tools/reference/mod-health.js +255 -0
  38. package/dist/hoi4_agent_tools/reference/operations.js +435 -21
  39. package/dist/hoi4_agent_tools/reference/script-guard.js +109 -0
  40. package/dist/hoi4_agent_tools/reference/service.js +58 -20
  41. package/dist/hoi4_agent_tools/runtime.js +11 -0
  42. package/dist/hoi4_agent_tools/schemas/compat.js +153 -0
  43. package/dist/hoi4_agent_tools/schemas/localisation-write.js +154 -0
  44. package/dist/hoi4_agent_tools/schemas/map.js +13 -1
  45. package/dist/hoi4_agent_tools/schemas/modder-tools.js +191 -0
  46. package/dist/hoi4_agent_tools/version.js +1 -1
  47. package/docs/configuration.md +4 -1
  48. package/docs/jobs.md +2 -1
  49. package/docs/map.md +4 -2
  50. package/docs/reference.md +45 -5
  51. package/docs/setup.md +23 -3
  52. package/docs/tools.md +16 -1
  53. package/engine/bin/manifest.json +1 -1
  54. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  55. package/npm-shrinkwrap.json +2 -2
  56. package/package.json +1 -1
  57. package/schemas/configuration.schema.json +140 -113
  58. package/schemas/continuous-focus-palette.schema.json +1 -1
  59. package/schemas/custom-weighted-pool.schema.json +1 -1
  60. package/schemas/decision-inspect-input.schema.json +1 -1
  61. package/schemas/error-log-input.schema.json +1 -1
  62. package/schemas/event-feature-manifest.schema.json +1 -1
  63. package/schemas/focus-plan.schema.json +1 -1
  64. package/schemas/focus-planning-sidecar.schema.json +1 -1
  65. package/schemas/geography-model.schema.json +1 -1
  66. package/schemas/gui-animation-source.schema.json +1 -1
  67. package/schemas/gui-helper.schema.json +1 -1
  68. package/schemas/gui-scenario.schema.json +1 -1
  69. package/schemas/helper-expansion-request.schema.json +1 -1
  70. package/schemas/helper-expansion-summary.schema.json +1 -1
  71. package/schemas/impact-inspect-input.schema.json +1 -1
  72. package/schemas/map-operation.schema.json +170 -139
  73. package/schemas/mechanic-test-input.schema.json +1 -1
  74. package/schemas/mod-index-input.schema.json +1 -1
  75. package/schemas/operation-result.schema.json +1 -1
  76. package/schemas/package-check-input.schema.json +1 -1
  77. package/schemas/package-manifest.schema.json +1 -1
  78. package/schemas/probability-analysis-result.schema.json +1 -1
  79. package/schemas/probability-compare-input.schema.json +1 -1
  80. package/schemas/probability-evaluate-input.schema.json +1 -1
  81. package/schemas/probability-inspect-input.schema.json +1 -1
  82. package/schemas/probability-render-input.schema.json +1 -1
  83. package/schemas/probability-scenario-set.schema.json +1 -1
  84. package/schemas/probability-sequence-input.schema.json +1 -1
  85. package/schemas/probability-simulate-input.schema.json +1 -1
  86. package/schemas/probability-sweep-input.schema.json +1 -1
  87. package/schemas/reference-context-input.schema.json +1 -1
  88. package/schemas/reference-read-input.schema.json +1 -1
  89. package/schemas/reference-search-input.schema.json +1 -1
  90. package/schemas/reference-sheets.schema.json +1 -1
  91. package/schemas/scenario-suite.schema.json +1 -1
  92. package/schemas/scenario-test-input.schema.json +1 -1
  93. package/schemas/script-validate-input.schema.json +1 -1
  94. package/schemas/shared-scenario.schema.json +1 -1
  95. package/schemas/source-lookup-input.schema.json +1 -1
  96. package/server.json +2 -2
@@ -358,31 +358,6 @@ export function edgeWaterDarkness(edge, width, height, x, y) {
358
358
  const pole = edge.polarPx > 0 ? smooth(1 - poleDistance / (edge.polarPx * 1.2)) * 0.8 : 0;
359
359
  return Math.max(side, pole);
360
360
  }
361
- /**
362
- * Impassable rows for every pair of distinct land provinces that meet across the seam (`rim` and
363
- * `wall`), in
364
- * `adjacencies.csv` order (rows are sorted by the lower then the higher province ID).
365
- */
366
- export function rimAdjacencyRows(input) {
367
- const { provincePixels, provinceKinds, width, height } = input;
368
- const pairs = new Set();
369
- for (let y = 0; y < height; y += 1) {
370
- const left = provincePixels[y * width];
371
- const right = provincePixels[y * width + width - 1];
372
- if (left === right || provinceKinds[left] !== LAND || provinceKinds[right] !== LAND)
373
- continue;
374
- const low = Math.min(left, right) + 1;
375
- const high = Math.max(left, right) + 1;
376
- pairs.add(`${low};${high}`);
377
- }
378
- return [...pairs]
379
- .sort((a, b) => {
380
- const [al, ah] = a.split(';').map(Number);
381
- const [bl, bh] = b.split(';').map(Number);
382
- return al - bl || ah - bh;
383
- })
384
- .map((pair) => `${pair};impassable;-1;-1;-1;-1;-1;;World rim`);
385
- }
386
361
  /** Heights and positions of the base map's frame meshes, scaled to the world size. */
387
362
  export function frameBorderPositions(width, height) {
388
363
  return {
@@ -22,7 +22,7 @@ import { planEconomy } from './gameplay/economy.js';
22
22
  import { prepareGameplay } from './gameplay/prepare.js';
23
23
  import { fractal, lattice } from './world-noise.js';
24
24
  import { calibratedColourMap, COLOUR_CLASSES, } from './colormap.js';
25
- import { ambientObjectText, applyEdgePolicy, assertFeaturesOutsideBand, edgeWaterDarkness, hasRimRange, RIM_COLOUR_FACTOR, rimAdjacencyRows, rimHeight, rimStrength, WALL_TERRAIN_KINDS, wallRowKinds, } from './world-edge.js';
25
+ import { ambientObjectText, applyEdgePolicy, assertFeaturesOutsideBand, edgeWaterDarkness, hasRimRange, RIM_COLOUR_FACTOR, rimHeight, rimStrength, WALL_TERRAIN_KINDS, wallRowKinds, } from './world-edge.js';
26
26
  import { landDistanceField, lakeHeight, normalizeLakes, waterColourLevel } from './water.js';
27
27
  import { DEFAULT_PAINTED_RELIEF } from './relief/painted-relief.js';
28
28
  import { rowStrips, scanAreaStrip } from './geography/index.js';
@@ -258,6 +258,68 @@ function geographySurface(spec, geography, reference) {
258
258
  }
259
259
  return { kind, elevation: new Float32Array(total), moisture };
260
260
  }
261
+ /** Reference terrain code of drawn snow (`REFERENCE_TERRAIN.snow`). */
262
+ const REFERENCE_SNOW = 4;
263
+ /** The base game keeps flat permanent snow in the tenth of rows nearest each pole. */
264
+ const ICE_CAP_LATITUDE = 0.8;
265
+ /** Drawn snow at or above this height stays permanent, as the base game's snowy high ground. */
266
+ const PEAK_SNOW_HEIGHT = 150;
267
+ function permanentSnowRule(input) {
268
+ // A latitude above 1 and a height above 255 are never reached.
269
+ if (input === 'snowlines')
270
+ return { iceCapLatitude: 2, peakHeight: 256 };
271
+ return {
272
+ iceCapLatitude: input?.iceCapLatitude ?? ICE_CAP_LATITUDE,
273
+ peakHeight: input?.peakHeight ?? PEAK_SNOW_HEIGHT,
274
+ };
275
+ }
276
+ /** Strategic regions drawn mostly as snow take the weather of at least this latitude. */
277
+ const SNOW_REGION_LATITUDE = 0.7;
278
+ /**
279
+ * Permanent snow (`perm_snow = yes`, indices 16 and 19) in the base game 1.19.4.2 `terrain.bmp`,
280
+ * over its land pixels: 10,628 mountain and 22,626 plains pixels, the plains almost all in the
281
+ * tenth of rows nearest each pole.
282
+ */
283
+ export const VANILLA_PERMANENT_SNOW = { pixels: 33_254, land: 4_353_170, share: 0.0076 };
284
+ /** A permanent-snow share above this multiple of the base game's is reported as a warning. */
285
+ const PERMANENT_SNOW_WARNING_FACTOR = 4;
286
+ /** Distance of a pixel row from the equator: 0 in the middle row, 1 at the top and bottom. */
287
+ function pixelLatitude(y, height) {
288
+ return Math.abs((y + 0.5) / height - 0.5) * 2;
289
+ }
290
+ function permanentSnowNote(count, input) {
291
+ const rule = permanentSnowRule(input);
292
+ const share = count.permanent / Math.max(1, count.land);
293
+ const ratio = share / VANILLA_PERMANENT_SNOW.share;
294
+ const high = ratio > PERMANENT_SNOW_WARNING_FACTOR;
295
+ const percent = (value) => `${(value * 100).toFixed(2)}%`;
296
+ return {
297
+ code: 'MAP_PERMANENT_SNOW_SHARE',
298
+ severity: high ? 'warning' : 'info',
299
+ message: `Permanent snow covers ${percent(share)} of the land (${count.permanent} pixels), ` +
300
+ `${ratio.toFixed(1)} times the base game's ${percent(VANILLA_PERMANENT_SNOW.share)}` +
301
+ (count.painted > 0
302
+ ? `; ${count.seasonal} of ${count.painted} drawn snow pixels are ordinary land with seasonal snow`
303
+ : '') +
304
+ (high
305
+ ? '. The game draws permanent snow as bright ice: raise permanentSnow.iceCapLatitude or peakHeight, or set permanentSnow to "snowlines"'
306
+ : ''),
307
+ details: {
308
+ permanentPixels: count.permanent,
309
+ landPixels: count.land,
310
+ share: Number(share.toFixed(5)),
311
+ vanilla: VANILLA_PERMANENT_SNOW,
312
+ ratio: Number(ratio.toFixed(2)),
313
+ drawnSnowPixels: count.painted,
314
+ seasonalSnowPixels: count.seasonal,
315
+ // The snow range or wall at a `rim` or `wall` seam, counted apart from the land.
316
+ edgePixels: count.edge,
317
+ permanentSnow: input === 'snowlines'
318
+ ? 'snowlines'
319
+ : { iceCapLatitude: rule.iceCapLatitude, peakHeight: rule.peakHeight },
320
+ },
321
+ };
322
+ }
261
323
  /** Land relief of the base game 1.19.4.1 (`reliefStatistics` over its land provinces). */
262
324
  export const VANILLA_RELIEF = { median: 107, p99: 213, maximum: 239, meanStep: 2.69 };
263
325
  function terrainSummaryNote(terrain, geography) {
@@ -926,6 +988,16 @@ export function generateWorld(spec, context, options = {}) {
926
988
  return found;
927
989
  };
928
990
  const wallProvinces = majorityIn(wallMask);
991
+ // `rim` and `wall` close the seam with impassable land, never with adjacency rows: the engine
992
+ // does not wrap adjacencies and draws a row between the two edges as a line across the whole
993
+ // map. Every land province on the first or last column is therefore impassable.
994
+ if (hasRimRange(edge))
995
+ for (let y = 0; y < height; y += 1)
996
+ for (const pixel of [y * width, y * width + width - 1]) {
997
+ const id = provinces.pixel[pixel];
998
+ if (provinces.kind[id] === LAND)
999
+ wallProvinces.add(id);
1000
+ }
929
1001
  const impassableProvinces = new Set([...wallProvinces, ...majorityIn(impassableMask)]);
930
1002
  if (landIds.length < spec.countries.length)
931
1003
  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 });
@@ -981,6 +1053,8 @@ export function generateWorld(spec, context, options = {}) {
981
1053
  'marsh',
982
1054
  'jungle',
983
1055
  ];
1056
+ // Provinces drawn as snow: plains in play, with cold weather for their strategic regions.
1057
+ const snowProvinces = new Set();
984
1058
  if (reference !== undefined) {
985
1059
  const votes = new Uint32Array(count * referenceTerrainNames.length);
986
1060
  for (let pixel = 0; pixel < width * height; pixel += 1)
@@ -993,6 +1067,8 @@ export function generateWorld(spec, context, options = {}) {
993
1067
  votes[id * referenceTerrainNames.length + selected])
994
1068
  selected = type;
995
1069
  terrain.set(id, referenceTerrainNames[selected]);
1070
+ if (selected === REFERENCE_SNOW)
1071
+ snowProvinces.add(id);
996
1072
  }
997
1073
  }
998
1074
  // Impassable land (the `wall` at the seam, painted or regional impassable land) joins no
@@ -1712,21 +1788,6 @@ export function generateWorld(spec, context, options = {}) {
1712
1788
  '',
1713
1789
  ].join('\n')));
1714
1790
  add(`${map}/continent.txt`, text(`continents = {\n${[...new Set([...generatedContinentKeys, ...(spec.inheritedContinents === 'drop' ? [] : (context.continentKeys ?? []))])].map((key) => `\t${key}`).join('\n')}\n}\n`));
1715
- const rimRows = hasRimRange(edge)
1716
- ? rimAdjacencyRows({
1717
- provincePixels: provinces.pixel,
1718
- provinceKinds: provinces.kind,
1719
- width,
1720
- height,
1721
- })
1722
- : [];
1723
- if (rimRows.length > 0)
1724
- notes.push({
1725
- code: 'MAP_EDGE_RIM_ADJACENCIES',
1726
- severity: 'info',
1727
- message: `The ${edge.mode} edge policy wrote ${rimRows.length} impassable adjacency row(s) for provinces that meet across the seam`,
1728
- details: { rows: rimRows.length },
1729
- });
1730
1791
  const crossingRows = (gameplay?.crossings.rows ?? []).map(adjacencyRowText);
1731
1792
  // Impassable land and rows must not cut a realm apart or box it in by accident (ZR-28).
1732
1793
  if (impassableProvinces.size > 0 || (gameplay?.crossings.blocked.length ?? 0) > 0)
@@ -1734,13 +1795,7 @@ export function generateWorld(spec, context, options = {}) {
1734
1795
  kind: provinces.kind,
1735
1796
  neighbors: provinces.neighbors,
1736
1797
  impassable: impassableProvinces,
1737
- blocked: [
1738
- ...(gameplay?.crossings.blocked ?? []),
1739
- ...rimRows.map((row) => {
1740
- const [from, to] = row.split(';').map(Number);
1741
- return [from - 1, to - 1];
1742
- }),
1743
- ],
1798
+ blocked: [...(gameplay?.crossings.blocked ?? [])],
1744
1799
  crossings: (gameplay?.crossings.rows ?? [])
1745
1800
  .filter(({ type }) => type === 'sea')
1746
1801
  .map(({ from, to }) => [from - 1, to - 1]),
@@ -1749,7 +1804,7 @@ export function generateWorld(spec, context, options = {}) {
1749
1804
  tags: spec.countries.map(({ tag }) => tag),
1750
1805
  }))
1751
1806
  notes.push(note);
1752
- add(`${map}/adjacencies.csv`, text(`From;To;Type;Through;start_x;start_y;stop_x;stop_y;adjacency_rule_name;Comment\r\n${[...crossingRows, ...rimRows].map((row) => `${row}\r\n`).join('')}-1;-1;;-1;-1;-1;-1;-1;-1\r\n`));
1807
+ add(`${map}/adjacencies.csv`, text(`From;To;Type;Through;start_x;start_y;stop_x;stop_y;adjacency_rule_name;Comment\r\n${crossingRows.map((row) => `${row}\r\n`).join('')}-1;-1;;-1;-1;-1;-1;-1;-1\r\n`));
1753
1808
  add(`${map}/adjacency_rules.txt`, text(gameplay === undefined
1754
1809
  ? '# No straits or canals in this world yet.\n'
1755
1810
  : adjacencyRulesText(gameplay.crossings.rules)));
@@ -1829,12 +1884,28 @@ export function generateWorld(spec, context, options = {}) {
1829
1884
  Math.abs(heights[Math.min(height - 1, y + 1) * width + x] -
1830
1885
  heights[Math.max(0, y - 1) * width + x]) <=
1831
1886
  2;
1832
- const snowAt = (pixel, type) => synthesized !== undefined
1833
- ? (synthesized.snow[pixel] === 1 || reference?.terrain[pixel] === 4) &&
1834
- surface.kind[pixel] === LAND
1835
- : reference === undefined
1836
- ? type === 'mountain' && latitude(provinces.pixel[pixel]) > 0.7
1837
- : reference.terrain[pixel] === 4 && surface.kind[pixel] === LAND;
1887
+ // Drawn snow is ordinary land with seasonal snow, as the base game's northern lands are; only
1888
+ // ice caps near the poles and high ground keep permanent snow. Snow lines are always permanent.
1889
+ const snowRule = permanentSnowRule(spec.permanentSnow);
1890
+ const paintedSnow = (pixel) => reference?.terrain[pixel] === REFERENCE_SNOW && surface.kind[pixel] === LAND;
1891
+ const iceCapOrPeak = (pixel) => pixelLatitude(Math.floor(pixel / width), height) >= snowRule.iceCapLatitude ||
1892
+ heights[pixel] >= snowRule.peakHeight;
1893
+ const snowAt = (pixel, type) => surface.kind[pixel] !== LAND
1894
+ ? false
1895
+ : synthesized?.snow[pixel] === 1 ||
1896
+ (reference !== undefined
1897
+ ? paintedSnow(pixel) && iceCapOrPeak(pixel)
1898
+ : synthesized === undefined &&
1899
+ type === 'mountain' &&
1900
+ latitude(provinces.pixel[pixel]) > 0.7);
1901
+ // The base game draws snowy high ground with its mountain entry (16) and flat ice caps with its
1902
+ // plains entry (19), both `perm_snow = yes`.
1903
+ const snowIndex = (pixel) => reference === undefined ||
1904
+ synthesized?.snow[pixel] === 1 ||
1905
+ heights[pixel] >= snowRule.peakHeight
1906
+ ? 16
1907
+ : 19;
1908
+ const snowCount = { permanent: 0, painted: 0, seasonal: 0, land: 0, edge: 0 };
1838
1909
  // A wall takes the look of the land it meets, row by row on each side.
1839
1910
  const wallLook = wallMask === undefined
1840
1911
  ? undefined
@@ -1870,9 +1941,7 @@ export function generateWorld(spec, context, options = {}) {
1870
1941
  ? 16
1871
1942
  : (terrainIndex.get(walled) ?? DEFAULT_TERRAIN_INDEX.get(walled) ?? 0)
1872
1943
  : snowy
1873
- ? reference === undefined
1874
- ? 16
1875
- : 19
1944
+ ? snowIndex(pixel)
1876
1945
  : rimmed
1877
1946
  ? 16
1878
1947
  : type === 'lakes'
@@ -1884,6 +1953,20 @@ export function generateWorld(spec, context, options = {}) {
1884
1953
  : snowy || rimmed
1885
1954
  ? 'snow'
1886
1955
  : type);
1956
+ if (surface.kind[pixel] === LAND) {
1957
+ if (walled !== undefined || rimmed)
1958
+ snowCount.edge += 1;
1959
+ else {
1960
+ snowCount.land += 1;
1961
+ if (snowy)
1962
+ snowCount.permanent += 1;
1963
+ if (paintedSnow(pixel)) {
1964
+ snowCount.painted += 1;
1965
+ if (!snowy)
1966
+ snowCount.seasonal += 1;
1967
+ }
1968
+ }
1969
+ }
1887
1970
  if (calibrated && walled === undefined && !snowy && !rimmed && surface.kind[pixel] === LAND) {
1888
1971
  // Variant graphical terrains by rule, so one class is not one flat texture.
1889
1972
  const y = (pixel - x) / width;
@@ -1911,6 +1994,8 @@ export function generateWorld(spec, context, options = {}) {
1911
1994
  colourClasses[pixel] = classCode(colour);
1912
1995
  }
1913
1996
  }
1997
+ if (snowCount.permanent > 0 || snowCount.painted > 0)
1998
+ notes.push(permanentSnowNote(snowCount, spec.permanentSnow));
1914
1999
  add(`${map}/terrain.bmp`, createBmp({
1915
2000
  width,
1916
2001
  height,
@@ -2096,6 +2181,11 @@ export function generateWorld(spec, context, options = {}) {
2096
2181
  const meanLatitude = indexes.reduce((sum, id) => sum + 1 - (2 * center(id).y) / height, 0) / indexes.length;
2097
2182
  const desert = indexes.filter((id) => terrain.get(id) === 'desert').length > indexes.length / 2;
2098
2183
  const naval = indexes.every((id) => provinces.kind[id] !== LAND);
2184
+ // A region drawn mostly as snow gets winters cold enough for seasonal snow.
2185
+ const snowy = indexes.filter((id) => snowProvinces.has(id)).length > indexes.length / 2;
2186
+ const weatherLatitude = snowy && Math.abs(meanLatitude) < SNOW_REGION_LATITUDE
2187
+ ? (meanLatitude < 0 ? -1 : 1) * SNOW_REGION_LATITUDE
2188
+ : meanLatitude;
2099
2189
  add(`${map}/strategicregions/${region}-${slug(regionNames.get(region) ?? `World region ${region}`).slice(0, 80)}.txt`, text([
2100
2190
  'strategic_region={',
2101
2191
  `\tid=${region}`,
@@ -2104,7 +2194,7 @@ export function generateWorld(spec, context, options = {}) {
2104
2194
  `\t\t${members.sort((a, b) => a - b).join(' ')} `,
2105
2195
  '\t}',
2106
2196
  ...(naval ? ['\tnaval_terrain=water_deep_ocean'] : []),
2107
- weatherBlock(meanLatitude, desert),
2197
+ weatherBlock(weatherLatitude, desert),
2108
2198
  '}',
2109
2199
  '',
2110
2200
  ].join('\n')));
@@ -12,8 +12,12 @@ export const ARGUMENT_EXAMPLES = {
12
12
  'hoi4.source_lookup': '{"symbol":"my_scripted_effect"} or {"path":"events/my_events.txt","line":42}',
13
13
  'hoi4.script_validate': '{"path":"events/my_events.txt"} or {"source":"add_political_power = 10","kind":"effect","scope":"country"}',
14
14
  'hoi4.error_log': '{"scope":"mod","category":"effect"}',
15
+ 'hoi4.script_guard': '{"paths":["events/my_events.txt"]} or {"sinceMinutes":30}',
16
+ 'hoi4.mod_health': '{"limit":5} or {"checks":["error_log","engine_check"]}',
17
+ 'hoi4.explain_error': `{"line":"Invalid trigger 'stability' in events/my_events.txt line : 12"}`,
15
18
  'hoi4.mod_index': '{"mode":"overview"} or {"mode":"next_id","kind":"event","namespace":"my_mod"}',
16
19
  'hoi4.localisation_inspect': '{"mode":"key","key":"my_event.1.t"} or {"mode":"audit"}',
20
+ 'hoi4.compat_check': '{"mode":"mod","other":"my_other_mod"} or {"mode":"patch"}',
17
21
  'hoi4.idea_inspect': '{"kind":"idea","id":"my_idea"} or {"kind":"character","audit":true}',
18
22
  'hoi4.system_inspect': '{"kind":"mio","id":"my_organization"} or {"kind":"on_actions","audit":true}',
19
23
  'hoi4.unit_inspect': '{"kind":"oob","id":"GER_1936"} or {"kind":"variant","audit":true}',
@@ -24,6 +28,7 @@ export const ARGUMENT_EXAMPLES = {
24
28
  'hoi4.focus_inspect': '{"treeId":"my_focus_tree"}',
25
29
  'hoi4.focus_render': '{"relativePath":"common/national_focus/my_tree.txt","treeId":"my_focus_tree"}',
26
30
  'hoi4.focus_rewrite': '{"relativePath":"common/national_focus/my_tree.txt","treeId":"my_focus_tree","layoutMode":"compact"}',
31
+ 'hoi4.localisation_write': '{"mode":"add","entries":[{"key":"my_focus","text":"My focus"}]} or {"mode":"fix","apply":true}',
27
32
  'hoi4.gui_inspect': '{"windowName":"my_window"}',
28
33
  'hoi4.gui_render': '{"windowName":"my_window","scenario":{"id":"normal"}}',
29
34
  'hoi4.gui_rewrite': '{"mode":"patches","relativePath":"interface/my_window.gui","windowName":"my_window","scenario":{"id":"normal"},"expectedSourceHash":"<sha256 of the file>","patches":[{"description":"Move the button right","start":120,"end":130,"expectedText":"x = 10 y","text":"x = 40 y"}]}',
@@ -19,6 +19,7 @@ import { ModernTaskAdapter, TASKS_EXTENSION } from './modern-tasks.js';
19
19
  import { SERVER_INSTRUCTIONS } from './instructions.js';
20
20
  import { jobProgressReporter, modernProgressReporter, withProgressHeartbeat } from './progress.js';
21
21
  import { taskToolCatalog } from './task-tool-catalog.js';
22
+ import { isListed, profileInstructions, resolveProfiles } from './tool-profiles.js';
22
23
  const rootsResponseSchema = z
23
24
  .object({
24
25
  roots: z
@@ -46,7 +47,7 @@ export function createModernOperationServer(engine, context = {}, tasks = new Op
46
47
  const controls = new JobControlService(engine);
47
48
  const references = new ReferenceToolService(engine);
48
49
  const privateOperations = options.createPrivateTools?.(engine, context);
49
- const mapEnd = taskToolCatalog.findIndex(({ name }) => name === 'hoi4.map_rewrite') + 1;
50
+ const mapEnd = taskToolCatalog.findIndex(({ name }) => name === 'hoi4.localisation_write') + 1;
50
51
  const definitions = [
51
52
  ...taskToolCatalog.slice(0, mapEnd),
52
53
  ...referenceTools,
@@ -63,7 +64,8 @@ export function createModernOperationServer(engine, context = {}, tasks = new Op
63
64
  prompts: {},
64
65
  extensions: { [TASKS_EXTENSION]: {} },
65
66
  },
66
- instructions: SERVER_INSTRUCTIONS,
67
+ instructions: SERVER_INSTRUCTIONS +
68
+ (profileInstructions(resolveProfiles(engine.resolver.config().profiles)) ?? ''),
67
69
  });
68
70
  // Warm job workers outlive single calls, not the client session that used them.
69
71
  const previousOnClose = server.onclose;
@@ -73,8 +75,11 @@ export function createModernOperationServer(engine, context = {}, tasks = new Op
73
75
  };
74
76
  registerModernResources(server, engine, context);
75
77
  registerModernPrompts(server);
78
+ const profiles = resolveProfiles(engine.resolver.config().profiles);
76
79
  server.setRequestHandler('tools/list', () => ListToolsResultSchema.parse({
77
- tools: definitions.map(({ name, inputSchema, outputSchema, ...metadata }) => slimListedTool({
80
+ tools: definitions
81
+ .filter(({ name }) => isListed(name, profiles))
82
+ .map(({ name, inputSchema, outputSchema, ...metadata }) => slimListedTool({
78
83
  ...metadata,
79
84
  name,
80
85
  inputSchema: {
@@ -3,6 +3,7 @@ import { fileURLToPath } from 'node:url';
3
3
  import { PACKAGE_NAME, PACKAGE_VERSION } from '../../version.js';
4
4
  import { registerFocusTools } from '../tools/focus.js';
5
5
  import { registerGuiTools } from '../tools/gui.js';
6
+ import { registerLocalisationWriteTools } from '../tools/localisation-write.js';
6
7
  import { registerMapTools } from '../tools/map.js';
7
8
  import { registerReferenceTools } from '../tools/reference.js';
8
9
  import { registerEventTools } from '../tools/event.js';
@@ -15,6 +16,7 @@ import { installRequestLifecycle } from './request-lifecycle.js';
15
16
  import { PersistentJobTaskStore } from './job-task-store.js';
16
17
  import { SERVER_INSTRUCTIONS } from './instructions.js';
17
18
  import { releaseIdleWorkers } from '../../core/operation-tasks.js';
19
+ import { profileInstructions, resolveProfiles } from './tool-profiles.js';
18
20
  export { SERVER_INSTRUCTIONS } from './instructions.js';
19
21
  export function createMcpServer(engine, context = {}) {
20
22
  let serverContext = context;
@@ -28,7 +30,8 @@ export function createMcpServer(engine, context = {}) {
28
30
  logging: {},
29
31
  tasks: { list: {}, cancel: {}, requests: { tools: { call: {} } } },
30
32
  },
31
- instructions: SERVER_INSTRUCTIONS,
33
+ instructions: SERVER_INSTRUCTIONS +
34
+ (profileInstructions(resolveProfiles(engine.resolver.config().profiles)) ?? ''),
32
35
  taskStore,
33
36
  });
34
37
  installRequestLifecycle(server, engine);
@@ -61,6 +64,7 @@ export function createMcpServer(engine, context = {}) {
61
64
  registerFocusTools(server, engine, serverContext);
62
65
  registerGuiTools(server, engine, serverContext);
63
66
  registerMapTools(server, engine, serverContext);
67
+ registerLocalisationWriteTools(server, engine, serverContext);
64
68
  registerReferenceTools(server, engine, serverContext);
65
69
  registerEventTools(server);
66
70
  registerAnalysisTools(server);
@@ -8,6 +8,7 @@ import { taskToolCatalog } from './task-tool-catalog.js';
8
8
  import { jobProgressReporter, progressReporter, withProgressHeartbeat } from './progress.js';
9
9
  import { withTaskRequestSignal } from './task-request-context.js';
10
10
  import { slimToolList } from './tool-listing.js';
11
+ import { isListed, resolveProfiles } from './tool-profiles.js';
11
12
  // Durable task compatibility and cancellation are control traffic. They must
12
13
  // remain responsive while every domain-execution slot is occupied.
13
14
  const controlTools = new Set(['hoi4.job_inspect', 'hoi4.job_cancel']);
@@ -23,8 +24,15 @@ export function installRequestLifecycle(server, engine) {
23
24
  const owner = {};
24
25
  server.server.setRequestHandler = (schema, handler) => {
25
26
  register(schema, (request, extra) => {
26
- if (request.method === 'tools/list')
27
- return Promise.resolve(handler(request, extra)).then(slimToolList);
27
+ if (request.method === 'tools/list') {
28
+ const profiles = resolveProfiles(engine.resolver.config().profiles);
29
+ return Promise.resolve(handler(request, extra)).then((result) => {
30
+ const slim = slimToolList(result);
31
+ return slim.tools === undefined
32
+ ? slim
33
+ : { ...slim, tools: slim.tools.filter(({ name }) => isListed(name, profiles)) };
34
+ });
35
+ }
28
36
  if (request.method !== 'tools/call')
29
37
  return handler(request, extra);
30
38
  const params = request.params;
@@ -2,6 +2,7 @@ import { analysisTaskTools } from '../tools/analysis.js';
2
2
  import { eventTaskTools } from '../tools/event.js';
3
3
  import { focusTaskTools } from '../tools/focus.js';
4
4
  import { guiTaskTools } from '../tools/gui.js';
5
+ import { localisationTaskTools } from '../tools/localisation-write.js';
5
6
  import { mapTaskTools } from '../tools/map.js';
6
7
  import { probabilityTaskTools } from '../tools/probability.js';
7
8
  import { technologyTaskTools } from '../tools/technology.js';
@@ -9,6 +10,7 @@ export const taskToolCatalog = [
9
10
  ...focusTaskTools,
10
11
  ...guiTaskTools,
11
12
  ...mapTaskTools,
13
+ ...localisationTaskTools,
12
14
  ...eventTaskTools,
13
15
  ...analysisTaskTools,
14
16
  ...technologyTaskTools,
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Tool profiles (maintainer decision R-4): every session pays for the tools it lists, so a
3
+ * session lists the core profile unless it asks for more. `core` holds the tools most modding
4
+ * sessions use; `map` the world builder; `advanced` the editors, renders and analyses of focus
5
+ * trees, GUI, events, technology and probability, and the rest. A tool outside the listed
6
+ * profiles is not listed, and still answers a call that names it.
7
+ */
8
+ export const TOOL_PROFILES = ['core', 'map', 'advanced'];
9
+ /** `all` stands for every profile. */
10
+ export const PROFILE_SELECTION_VALUES = [...TOOL_PROFILES, 'all'];
11
+ /** The profile a session lists when nothing chooses one. */
12
+ export const DEFAULT_PROFILES = ['core'];
13
+ /** The environment variable that chooses profiles for one client registration. */
14
+ export const PROFILES_ENV = 'HOI4_AGENT_TOOLS_PROFILES';
15
+ const coreTools = new Set([
16
+ 'hoi4.skill',
17
+ 'hoi4.reference_search',
18
+ 'hoi4.reference_read',
19
+ 'hoi4.reference_context',
20
+ 'hoi4.source_lookup',
21
+ 'hoi4.script_validate',
22
+ 'hoi4.script_guard',
23
+ 'hoi4.error_log',
24
+ 'hoi4.explain_error',
25
+ 'hoi4.mod_health',
26
+ 'hoi4.mod_index',
27
+ 'hoi4.localisation_inspect',
28
+ 'hoi4.localisation_write',
29
+ ]);
30
+ const mapTools = new Set(['hoi4.map_inspect', 'hoi4.map_rewrite']);
31
+ /** Job controls follow the long-running tools of map and advanced. */
32
+ const jobTools = new Set(['hoi4.job_inspect', 'hoi4.job_cancel']);
33
+ /** The profiles a tool belongs to. */
34
+ export function profilesOf(name) {
35
+ // A plugin tool (ADR 0081) is listed by every session: the configuration that loads the plugin
36
+ // is the choice, so a profile never hides it.
37
+ if (!name.startsWith('hoi4.'))
38
+ return TOOL_PROFILES;
39
+ if (coreTools.has(name))
40
+ return ['core'];
41
+ if (mapTools.has(name))
42
+ return ['map'];
43
+ if (jobTools.has(name))
44
+ return ['map', 'advanced'];
45
+ return ['advanced'];
46
+ }
47
+ /** Every profile when the selection names `all` or nothing; else the named ones. */
48
+ export function resolveProfiles(selection) {
49
+ if (selection === undefined || selection.includes('all'))
50
+ return new Set(TOOL_PROFILES);
51
+ return new Set(selection.filter((value) => value !== 'all'));
52
+ }
53
+ /** Whether a session with these profiles lists the tool. */
54
+ export function isListed(name, profiles) {
55
+ return profilesOf(name).some((profile) => profiles.has(profile));
56
+ }
57
+ /**
58
+ * Parse `HOI4_AGENT_TOOLS_PROFILES` (`core,map`, `all`). Unknown names fail, so a typo never
59
+ * silently hides every tool.
60
+ */
61
+ export function parseProfilesEnv(value) {
62
+ if (value === undefined || value.trim() === '')
63
+ return undefined;
64
+ const names = value
65
+ .split(/[\s,]+/u)
66
+ .map((name) => name.trim().toLowerCase())
67
+ .filter(Boolean);
68
+ const unknown = names.filter((name) => !PROFILE_SELECTION_VALUES.includes(name));
69
+ if (unknown.length > 0)
70
+ throw new Error(`${PROFILES_ENV} names unknown profiles: ${unknown.join(', ')}; use ${PROFILE_SELECTION_VALUES.join(', ')}`);
71
+ return names;
72
+ }
73
+ /** One sentence for the server instructions when some tools are not listed. */
74
+ export function profileInstructions(profiles) {
75
+ const missing = TOOL_PROFILES.filter((profile) => !profiles.has(profile));
76
+ if (missing.length === 0)
77
+ return undefined;
78
+ return ` This session lists the ${[...profiles].join(' and ')} tools; the ${missing.join(' and ')} tools (${missing
79
+ .map((profile) => profile === 'map'
80
+ ? 'world maps'
81
+ : 'focus, GUI, event, technology, probability and other editors')
82
+ .join('; ')}) need ${PROFILES_ENV}=${[...TOOL_PROFILES].join(',')} in the client's server entry.`;
83
+ }
@@ -0,0 +1,21 @@
1
+ import { strictOperationResultSchema } from '../server/result.js';
2
+ import { localisationWriteDataSchema, localisationWriteRequestSchema, } from '../../schemas/localisation-write.js';
3
+ import { registerLegacyTaskTools } from '../server/legacy-task-tools.js';
4
+ export const localisationTaskTools = [
5
+ {
6
+ name: 'hoi4.localisation_write',
7
+ title: 'Add or fix localisation',
8
+ description: 'Add localisation keys (mode add: key and text; language, file, replace) or repair localisation files (mode fix: BOM, broken quotes, keys missing from supported languages). Game keys are overridden from a replace folder. apply false returns the diff and writes nothing; apply true writes it. Returns up to 10 files with diffs. Example: {"mode":"add","entries":[{"key":"my_focus","text":"My focus"}]}',
9
+ inputSchema: localisationWriteRequestSchema,
10
+ outputSchema: strictOperationResultSchema(localisationWriteDataSchema),
11
+ annotations: {
12
+ readOnlyHint: false,
13
+ destructiveHint: true,
14
+ idempotentHint: false,
15
+ openWorldHint: false,
16
+ },
17
+ },
18
+ ];
19
+ export function registerLocalisationWriteTools(server, _engine, _context) {
20
+ registerLegacyTaskTools(server, localisationTaskTools);
21
+ }
@@ -3,10 +3,12 @@ import { ReferenceToolService } from '../../reference/operations.js';
3
3
  import { referenceContextRequestSchema, referenceReadRequestSchema, referenceSearchRequestSchema, sourceLookupRequestSchema, referenceContextToolDataSchema, referenceReadDataSchema, referenceSearchToolDataSchema, sourceLookupDataSchema, } from '../../schemas/reference.js';
4
4
  import { localisationInspectDataSchema, localisationInspectRequestSchema, } from '../../schemas/localisation.js';
5
5
  import { systemInspectDataSchema, systemInspectRequestSchema, unitInspectDataSchema, unitInspectRequestSchema, assetInspectDataSchema, assetInspectRequestSchema, } from '../../schemas/system.js';
6
+ import { compatCheckDataSchema, compatCheckRequestSchema } from '../../schemas/compat.js';
6
7
  import { ideaInspectDataSchema, ideaInspectRequestSchema } from '../../schemas/ideas.js';
7
8
  import { errorLogDataSchema, errorLogRequestSchema, modIndexDataSchema, modIndexRequestSchema, } from '../../schemas/mod-tools.js';
8
9
  import { scriptValidateDataSchema, scriptValidateRequestSchema, } from '../../schemas/script-validation.js';
9
10
  import { skillDataSchema, skillRequestSchema } from '../../schemas/skill.js';
11
+ import { explainErrorDataSchema, explainErrorRequestSchema, modHealthDataSchema, modHealthRequestSchema, scriptGuardDataSchema, scriptGuardRequestSchema, } from '../../schemas/modder-tools.js';
10
12
  const readOnly = {
11
13
  readOnlyHint: true,
12
14
  destructiveHint: false,
@@ -62,6 +64,30 @@ export const referenceTools = [
62
64
  outputSchema: strictOperationResultSchema(errorLogDataSchema),
63
65
  annotations: readOnly,
64
66
  },
67
+ {
68
+ name: 'hoi4.explain_error',
69
+ title: 'Explain error.log lines',
70
+ description: 'Explain error.log lines: the rule each one breaks, its file and line with the lines around it, and the fix, from a reviewed catalogue of the game\'s messages. Says whether the game documents the command a line names, and the closest documented names. Example: {"line":"Invalid trigger \'stability\' in events/my_events.txt line : 12"}. Returns up to 20 explanations (10 lines).',
71
+ inputSchema: explainErrorRequestSchema,
72
+ outputSchema: strictOperationResultSchema(explainErrorDataSchema),
73
+ annotations: readOnly,
74
+ },
75
+ {
76
+ name: 'hoi4.mod_health',
77
+ title: 'Check a whole mod',
78
+ description: 'Check a whole mod in one call: the last error.log, the engine check (unknown effects, triggers and modifiers, duplicate ids, broken overrides), script validation, and the localisation and asset audits. Returns the 10 problems that matter most, each counted with 2 examples, its fix and the tool to use next, and which audits ran. Example: {"limit":5} or {"checks":["error_log","engine_check"]}. Takes up to a minute on a large mod.',
79
+ inputSchema: modHealthRequestSchema,
80
+ outputSchema: strictOperationResultSchema(modHealthDataSchema),
81
+ annotations: readOnly,
82
+ },
83
+ {
84
+ name: 'hoi4.script_guard',
85
+ title: 'Find invented commands in new script',
86
+ description: 'Check the files you wrote for invented commands: every effect, trigger and modifier that the installed game documentation does not list and no loaded file defines, with its file, line and the closest real name. Checks the named paths, or the mod script files changed in the last 120 minutes. Needs hoi4-engine. Example: {"paths":["events/my_events.txt"]}. Returns up to 40 names.',
87
+ inputSchema: scriptGuardRequestSchema,
88
+ outputSchema: strictOperationResultSchema(scriptGuardDataSchema),
89
+ annotations: readOnly,
90
+ },
65
91
  {
66
92
  name: 'hoi4.mod_index',
67
93
  title: 'Explore mod content and find free IDs',
@@ -118,6 +144,14 @@ export const referenceTools = [
118
144
  outputSchema: strictOperationResultSchema(skillDataSchema),
119
145
  annotations: readOnly,
120
146
  },
147
+ {
148
+ name: 'hoi4.compat_check',
149
+ title: 'Check a mod against another mod or a game patch',
150
+ description: 'mod: compare this mod with another in both load orders: files at the same path and who wins, duplicate ids, definitions and hooks dropped, replace_path losses, and which order loses less. patch: store the vanilla files the mod overrides and list those a game update changed. Example: {"mode":"mod","other":"my_other_mod"} or {"mode":"patch"}',
151
+ inputSchema: compatCheckRequestSchema,
152
+ outputSchema: strictOperationResultSchema(compatCheckDataSchema),
153
+ annotations: readOnly,
154
+ },
121
155
  ];
122
156
  export function registerReferenceTools(server, engine, context) {
123
157
  const service = new ReferenceToolService(engine);
@@ -13,7 +13,12 @@ import { authenticate, bearerChallenge, HttpAuthError, protectedResourceMetadata
13
13
  import { BoundedEventStore, SharedEventStoreBudget } from './event-store.js';
14
14
  import { createModernOperationServer } from '../server/create-modern-operations.js';
15
15
  import { FinalProtocolTransport } from './protocol-gate.js';
16
- const WRITE_SCOPED_TOOLS = new Set(['hoi4.focus_rewrite', 'hoi4.gui_rewrite', 'hoi4.map_rewrite']);
16
+ const WRITE_SCOPED_TOOLS = new Set([
17
+ 'hoi4.focus_rewrite',
18
+ 'hoi4.gui_rewrite',
19
+ 'hoi4.map_rewrite',
20
+ 'hoi4.localisation_write',
21
+ ]);
17
22
  const MCP_ALLOWED_METHODS = 'GET, POST, DELETE';
18
23
  const SINGLETON_SECURITY_HEADERS = new Set([
19
24
  'authorization',