hoi4-agent-tools 4.21.0 → 4.22.1

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 (133) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +3 -1
  3. package/dist/bin/setup.js +1 -0
  4. package/dist/bin/stdio.js +1 -0
  5. package/dist/hoi4_agent_tools/common-write/documented-lists.js +62 -0
  6. package/dist/hoi4_agent_tools/common-write/limits.js +35 -0
  7. package/dist/hoi4_agent_tools/common-write/paths.js +17 -0
  8. package/dist/hoi4_agent_tools/common-write/write-job-operations.js +42 -0
  9. package/dist/hoi4_agent_tools/common-write/write-operations.js +360 -0
  10. package/dist/hoi4_agent_tools/common-write/write-plan.js +34 -0
  11. package/dist/hoi4_agent_tools/core/bounded-source.js +1 -1
  12. package/dist/hoi4_agent_tools/core/domain-tools.js +8 -0
  13. package/dist/hoi4_agent_tools/core/engine-client.js +3 -1
  14. package/dist/hoi4_agent_tools/core/image-diff.js +1 -1
  15. package/dist/hoi4_agent_tools/core/job-controls.js +12 -2
  16. package/dist/hoi4_agent_tools/core/job-executor.js +8 -7
  17. package/dist/hoi4_agent_tools/core/job-operation-registration.js +4 -0
  18. package/dist/hoi4_agent_tools/core/job-store.js +97 -5
  19. package/dist/hoi4_agent_tools/core/job-worker-host.js +2 -2
  20. package/dist/hoi4_agent_tools/core/lazy-native.js +26 -0
  21. package/dist/hoi4_agent_tools/core/operation-result.js +118 -33
  22. package/dist/hoi4_agent_tools/core/operation-tasks.js +1 -1
  23. package/dist/hoi4_agent_tools/core/svg-text.js +1 -1
  24. package/dist/hoi4_agent_tools/core/workspace.js +11 -1
  25. package/dist/hoi4_agent_tools/country/job-operations.js +42 -0
  26. package/dist/hoi4_agent_tools/country/write-operations.js +646 -0
  27. package/dist/hoi4_agent_tools/country/write-plan.js +28 -0
  28. package/dist/hoi4_agent_tools/event/render.js +1 -1
  29. package/dist/hoi4_agent_tools/focus/continuous-render.js +1 -1
  30. package/dist/hoi4_agent_tools/focus/game-view-output.js +1 -1
  31. package/dist/hoi4_agent_tools/focus/limits.js +3 -0
  32. package/dist/hoi4_agent_tools/focus/quality/schematic.js +1 -1
  33. package/dist/hoi4_agent_tools/focus/render.js +3 -3
  34. package/dist/hoi4_agent_tools/gui/assets.js +2 -2
  35. package/dist/hoi4_agent_tools/gui/limits.js +2 -0
  36. package/dist/hoi4_agent_tools/gui/renderer.js +1 -1
  37. package/dist/hoi4_agent_tools/gui/studio.js +2 -4
  38. package/dist/hoi4_agent_tools/map/engine-validation.js +1 -1
  39. package/dist/hoi4_agent_tools/map/geography/preview.js +1 -1
  40. package/dist/hoi4_agent_tools/map/landmass-source.js +42 -0
  41. package/dist/hoi4_agent_tools/map/landmass.js +190 -0
  42. package/dist/hoi4_agent_tools/map/operations.js +20 -6
  43. package/dist/hoi4_agent_tools/map/reference-import.js +1 -1
  44. package/dist/hoi4_agent_tools/map/reference-labels.js +1 -1
  45. package/dist/hoi4_agent_tools/map/reference-preparation.js +1 -1
  46. package/dist/hoi4_agent_tools/map/reference-world.js +1 -1
  47. package/dist/hoi4_agent_tools/map/references.js +6 -3
  48. package/dist/hoi4_agent_tools/map/render.js +1 -1
  49. package/dist/hoi4_agent_tools/map/service.js +88 -8
  50. package/dist/hoi4_agent_tools/map/world-preview.js +1 -1
  51. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  52. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  53. package/dist/hoi4_agent_tools/mcp/server/create.js +4 -0
  54. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +4 -0
  55. package/dist/hoi4_agent_tools/mcp/tools/common-write.js +21 -0
  56. package/dist/hoi4_agent_tools/mcp/tools/country-write.js +21 -0
  57. package/dist/hoi4_agent_tools/mcp/tools/focus.js +3 -2
  58. package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -1
  59. package/dist/hoi4_agent_tools/mcp/transports/http.js +2 -0
  60. package/dist/hoi4_agent_tools/probability/render.js +1 -1
  61. package/dist/hoi4_agent_tools/reference/known-mistakes.js +65 -0
  62. package/dist/hoi4_agent_tools/reference/known-mistakes.json +19 -0
  63. package/dist/hoi4_agent_tools/reference/operations.js +15 -2
  64. package/dist/hoi4_agent_tools/runtime.js +79 -1
  65. package/dist/hoi4_agent_tools/schemas/character-write.js +5 -1
  66. package/dist/hoi4_agent_tools/schemas/common-write.js +74 -0
  67. package/dist/hoi4_agent_tools/schemas/country-write.js +206 -0
  68. package/dist/hoi4_agent_tools/schemas/decision-write.js +5 -1
  69. package/dist/hoi4_agent_tools/schemas/doctrine-write.js +5 -1
  70. package/dist/hoi4_agent_tools/schemas/event-write.js +5 -1
  71. package/dist/hoi4_agent_tools/schemas/focus-requests.js +1 -1
  72. package/dist/hoi4_agent_tools/schemas/gui-requests.js +2 -1
  73. package/dist/hoi4_agent_tools/schemas/idea-write.js +5 -1
  74. package/dist/hoi4_agent_tools/schemas/landmass.js +129 -0
  75. package/dist/hoi4_agent_tools/schemas/localisation-write.js +10 -1
  76. package/dist/hoi4_agent_tools/schemas/map-requests.js +1 -1
  77. package/dist/hoi4_agent_tools/schemas/map.js +2 -0
  78. package/dist/hoi4_agent_tools/schemas/tech-write.js +5 -1
  79. package/dist/hoi4_agent_tools/technology/render.js +1 -1
  80. package/dist/hoi4_agent_tools/version.js +1 -1
  81. package/docs/focus.md +1 -1
  82. package/docs/jobs.md +2 -2
  83. package/docs/reference.md +10 -9
  84. package/docs/setup.md +13 -1
  85. package/docs/tools.md +16 -2
  86. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  87. package/engine/bin/darwin-x64/hoi4-engine +0 -0
  88. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  89. package/engine/bin/linux-x64/hoi4-engine +0 -0
  90. package/engine/bin/manifest.json +13 -8
  91. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  92. package/npm-shrinkwrap.json +43 -19
  93. package/package.json +1 -1
  94. package/schemas/configuration.schema.json +1 -1
  95. package/schemas/continuous-focus-palette.schema.json +1 -1
  96. package/schemas/custom-weighted-pool.schema.json +1 -1
  97. package/schemas/decision-inspect-input.schema.json +1 -1
  98. package/schemas/error-log-input.schema.json +1 -1
  99. package/schemas/event-feature-manifest.schema.json +1 -1
  100. package/schemas/focus-plan.schema.json +1 -1
  101. package/schemas/focus-planning-sidecar.schema.json +1 -1
  102. package/schemas/geography-model.schema.json +1 -1
  103. package/schemas/gui-animation-source.schema.json +1 -1
  104. package/schemas/gui-helper.schema.json +1 -1
  105. package/schemas/gui-scenario.schema.json +1 -1
  106. package/schemas/helper-expansion-request.schema.json +1 -1
  107. package/schemas/helper-expansion-summary.schema.json +1 -1
  108. package/schemas/impact-inspect-input.schema.json +1 -1
  109. package/schemas/map-operation.schema.json +354 -1
  110. package/schemas/mechanic-test-input.schema.json +1 -1
  111. package/schemas/mod-index-input.schema.json +1 -1
  112. package/schemas/operation-result.schema.json +1 -1
  113. package/schemas/package-check-input.schema.json +1 -1
  114. package/schemas/package-manifest.schema.json +1 -1
  115. package/schemas/probability-analysis-result.schema.json +1 -1
  116. package/schemas/probability-compare-input.schema.json +1 -1
  117. package/schemas/probability-evaluate-input.schema.json +1 -1
  118. package/schemas/probability-inspect-input.schema.json +1 -1
  119. package/schemas/probability-render-input.schema.json +1 -1
  120. package/schemas/probability-scenario-set.schema.json +1 -1
  121. package/schemas/probability-sequence-input.schema.json +1 -1
  122. package/schemas/probability-simulate-input.schema.json +1 -1
  123. package/schemas/probability-sweep-input.schema.json +1 -1
  124. package/schemas/reference-context-input.schema.json +1 -1
  125. package/schemas/reference-read-input.schema.json +1 -1
  126. package/schemas/reference-search-input.schema.json +1 -1
  127. package/schemas/reference-sheets.schema.json +1 -1
  128. package/schemas/scenario-suite.schema.json +1 -1
  129. package/schemas/scenario-test-input.schema.json +1 -1
  130. package/schemas/script-validate-input.schema.json +1 -1
  131. package/schemas/shared-scenario.schema.json +1 -1
  132. package/schemas/source-lookup-input.schema.json +1 -1
  133. package/server.json +2 -2
@@ -19,6 +19,7 @@ import { buildImportArtifacts, buildImportReport, } from './reference-import.js'
19
19
  import { buildGeographyArtifacts } from './geography/preview.js';
20
20
  import { operationHasGeography, prepareGeography, } from './geography/preparation.js';
21
21
  import { WORLD_OUTPUT_MANIFEST } from './world-outputs.js';
22
+ import { readLandmassMask } from './landmass-source.js';
22
23
  import { renderMap, renderMapDiff, } from './render.js';
23
24
  import { mapValidationChecks, validateMapAsync } from './validation.js';
24
25
  import { MAP_BASELINE_DIAGNOSTIC_LIMIT, mapBaselineFingerprint, mapWriteFootprint, } from './baseline.js';
@@ -28,6 +29,24 @@ import { evaluateTerritoryQuality, territoryAssignmentContent, territoryArtifact
28
29
  * Evidence of an imported reference: registered sheets, an exact or frame-fitted picture, or a
29
30
  * geography model beside the picture. Plain pictures keep their previous output.
30
31
  */
32
+ /** Names the way out of a write that only fails on the pre-existing findings of its map. */
33
+ export const MAP_BASELINE_REMEDY = 'Call a full hoi4.map_inspect (no lookupOnly), then pass its baselineFingerprint to hoi4.map_rewrite as baselineFingerprint; pre-existing errors outside the write then stop blocking it';
34
+ function withBaselineRemedy(error, prepared) {
35
+ if (!(error instanceof ServiceError) || error.code !== 'TRANSACTION_STRUCTURE_LIMIT')
36
+ return error;
37
+ const { diagnostics, diagnosticsLimit } = error.details;
38
+ if (prepared.baseline !== undefined ||
39
+ typeof diagnostics !== 'number' ||
40
+ typeof diagnosticsLimit !== 'number' ||
41
+ diagnostics <= diagnosticsLimit ||
42
+ // A new world replaces the whole map and has no baseline (ADR 0070).
43
+ prepared.plan.operations.some((operation) => operation.kind === 'create_world'))
44
+ return error;
45
+ return new ServiceError(error.code, error.message, {
46
+ ...error.details,
47
+ remedy: MAP_BASELINE_REMEDY,
48
+ });
49
+ }
31
50
  function importEvidence(operation, loaded, geography) {
32
51
  const reference = operation.reference;
33
52
  if (reference === undefined ||
@@ -642,8 +661,8 @@ export class AgentNudger {
642
661
  this.scanner = this.engine.scanner;
643
662
  this.transactions = this.engine.transactions;
644
663
  }
645
- async scan(workspaceId, principal, signal, includeExternalScriptReferences = false, includeWorldContext = false, includeAppearance = false, includeBorderInputs = false, includeContinentReferences = false) {
646
- const { files, sourceRoots } = await this.scanSources(workspaceId, principal, signal, includeExternalScriptReferences, includeWorldContext, includeAppearance, includeBorderInputs, includeContinentReferences);
664
+ async scan(workspaceId, principal, signal, includeExternalScriptReferences = false, includeWorldContext = false, includeAppearance = false, includeBorderInputs = false, includeContinentReferences = false, includeLandmass = false, includeCommonScripts = false) {
665
+ const { files, sourceRoots } = await this.scanSources(workspaceId, principal, signal, includeExternalScriptReferences, includeWorldContext, includeAppearance, includeBorderInputs, includeContinentReferences, includeLandmass, includeCommonScripts);
647
666
  const revision = hashCanonical(files.map(({ displayPath, loadOrder, sha256 }) => ({ displayPath, loadOrder, sha256 })));
648
667
  return {
649
668
  workspaceId,
@@ -653,7 +672,7 @@ export class AgentNudger {
653
672
  };
654
673
  }
655
674
  /** The source files a map scan reads, without the index built from them. */
656
- async scanSources(workspaceId, principal, signal, includeExternalScriptReferences = false, includeWorldContext = false, includeAppearance = false, includeBorderInputs = false, includeContinentReferences = false) {
675
+ async scanSources(workspaceId, principal, signal, includeExternalScriptReferences = false, includeWorldContext = false, includeAppearance = false, includeBorderInputs = false, includeContinentReferences = false, includeLandmass = false, includeCommonScripts = false) {
657
676
  signal?.throwIfAborted();
658
677
  const workspace = this.resolver.get(workspaceId, principal);
659
678
  const sourceRoots = {
@@ -714,6 +733,28 @@ export class AgentNudger {
714
733
  ],
715
734
  }, principal, signal)
716
735
  : undefined;
736
+ // add_landmass edits every raster of the map from whichever root holds it (the base game's
737
+ // included) and checks owners and state categories against the mod's definitions.
738
+ const landmassSnapshot = includeLandmass
739
+ ? await this.engine.scanFiles(workspaceId, {
740
+ patterns: [
741
+ 'common/state_category/**/*.txt',
742
+ 'common/country_tags/*.txt',
743
+ ...sourceRoots.map.flatMap((root) => {
744
+ const normalized = normalizeSourceRoot(root);
745
+ return [
746
+ ...['heightmap', 'terrain', 'rivers', 'trees', 'cities', 'world_normal'].map((name) => `${normalized}/${name}.bmp`),
747
+ `${normalized}/terrain/colormap_rgb_cityemissivemask_a.dds`,
748
+ `${normalized}/terrain/colormap_water_*.dds`,
749
+ ];
750
+ }),
751
+ ],
752
+ }, principal, signal)
753
+ : undefined;
754
+ // Every common/ script, read when an island may absorb a sea province: any of them may name it.
755
+ const commonScriptSnapshot = includeCommonScripts
756
+ ? await this.engine.scanFiles(workspaceId, { patterns: ['common/**/*.txt'] }, principal, signal)
757
+ : undefined;
717
758
  // Scripts that may name a continent, read when a new world drops the inherited continents.
718
759
  const continentSnapshot = includeContinentReferences
719
760
  ? await this.engine.scanFiles(workspaceId, { patterns: [...CONTINENT_REFERENCE_SCRIPT_PATTERNS] }, principal, signal)
@@ -727,6 +768,9 @@ export class AgentNudger {
727
768
  ...(appearanceSnapshot?.files ?? []).filter((file) => ![...contentSnapshot.files, ...(worldContextSnapshot?.files ?? [])].some((existing) => existing.displayPath === file.displayPath)),
728
769
  ...(generatedOutputsSnapshot?.files ?? []).filter((file) => ![...contentSnapshot.files, ...(worldContextSnapshot?.files ?? [])].some((existing) => existing.displayPath === file.displayPath)),
729
770
  ];
771
+ for (const file of [...(landmassSnapshot?.files ?? []), ...(commonScriptSnapshot?.files ?? [])])
772
+ if (!collected.some((existing) => existing.displayPath === file.displayPath))
773
+ collected.push(file);
730
774
  const collectedPaths = new Set(collected.map(({ displayPath }) => displayPath));
731
775
  const files = [
732
776
  ...collected,
@@ -769,9 +813,11 @@ export class AgentNudger {
769
813
  : await this.baselineFingerprint(workspaceId, principal, signal);
770
814
  const snapshot = await this.scan(workspaceId, principal, signal, operations.some((operation) => operation.kind === 'renumber_map_entity' ||
771
815
  operation.kind === 'remap_map_references' ||
772
- 'remapReferences' in operation),
816
+ 'remapReferences' in operation ||
817
+ // An absorbed sea province must not be named by fleets, events or other scripts.
818
+ (operation.kind === 'add_landmass' && operation.absorbCoveredSeaProvinces === true)),
773
819
  // record_world_outputs needs every world output scanned, as create_world does.
774
- operations.some((operation) => operation.kind === 'create_world' || operation.kind === 'record_world_outputs'), false, operations.some((operation) => operation.kind === 'assign_territory' || operation.kind === 'repartition_states'), operations.some((operation) => operation.kind === 'create_world' && operation.inheritedContinents === 'drop'));
820
+ operations.some((operation) => operation.kind === 'create_world' || operation.kind === 'record_world_outputs'), false, operations.some((operation) => operation.kind === 'assign_territory' || operation.kind === 'repartition_states'), operations.some((operation) => operation.kind === 'create_world' && operation.inheritedContinents === 'drop'), operations.some((operation) => operation.kind === 'add_landmass'), operations.some((operation) => operation.kind === 'add_landmass' && operation.absorbCoveredSeaProvinces === true));
775
821
  const referenceWorlds = new Map();
776
822
  const referenceImages = [];
777
823
  const referenceLoads = new Map();
@@ -798,9 +844,24 @@ export class AgentNudger {
798
844
  }
799
845
  const geographyModels = new Map();
800
846
  for (const operation of operations) {
801
- if (operation.kind !== 'create_world' || !operationHasGeography(operation))
847
+ const landmass = operation.kind === 'add_landmass';
848
+ if ((operation.kind !== 'create_world' && !landmass) || !operationHasGeography(operation))
802
849
  continue;
803
- const geography = await prepareGeography(this.resolver, workspaceId, operation, principal, signal);
850
+ // An island's geography uses the frame of the map it is added to.
851
+ const bitmap = snapshot.index.provinceBitmap;
852
+ if (landmass && bitmap === undefined)
853
+ throw new ServiceError('MAP_LANDMASS_SOURCE_UNSAFE', 'The map has no readable provinces.bmp, so an island cannot be placed on it');
854
+ const geography = await prepareGeography(this.resolver, workspaceId, landmass
855
+ ? {
856
+ id: operation.id,
857
+ width: bitmap.width,
858
+ height: bitmap.height,
859
+ geography: operation.geography,
860
+ geographyPath: operation.geographyPath,
861
+ // A drawn mask supplies the island's coast, so the model declares no land.
862
+ ...(operation.maskImage === undefined ? {} : { reference: operation.maskImage }),
863
+ }
864
+ : operation, principal, signal);
804
865
  geographyModels.set(operation.id, geography);
805
866
  if (geography.source.kind === 'file') {
806
867
  const evidence = geography.source.evidence;
@@ -833,9 +894,19 @@ export class AgentNudger {
833
894
  loadOrder,
834
895
  sha256,
835
896
  })));
897
+ const landmassMasks = new Map();
898
+ for (const operation of operations) {
899
+ if (operation.kind !== 'add_landmass' || operation.maskImage === undefined)
900
+ continue;
901
+ const mask = await readLandmassMask(this.resolver, workspaceId, operation.maskImage.path, principal, signal);
902
+ landmassMasks.set(operation.id, mask.prepared);
903
+ snapshot.referenceSources ??= [];
904
+ snapshot.referenceSources.push(mask.evidence);
905
+ }
836
906
  const plan = await planMapOperationsAsync(snapshot.index, operations, signal, {
837
907
  referenceWorlds,
838
908
  geographyModels,
909
+ landmassMasks,
839
910
  ...(synthesisCheck ? { synthesisCheck: true } : {}),
840
911
  });
841
912
  // Model diagnostics (including warnings of a model that is otherwise usable) travel with the plan.
@@ -971,6 +1042,15 @@ export class AgentNudger {
971
1042
  const planned = await this.planPrepared(input, prepared);
972
1043
  return prepared.baseline === undefined ? planned : { ...planned, baseline: prepared.baseline };
973
1044
  }
1045
+ /** Plans the transaction; a limit hit on pre-existing findings names the stated baseline. */
1046
+ async planTransaction(prepared, input) {
1047
+ try {
1048
+ return await this.transactions.plan(input);
1049
+ }
1050
+ catch (error) {
1051
+ throw withBaselineRemedy(error, prepared);
1052
+ }
1053
+ }
974
1054
  async planPrepared(input, prepared) {
975
1055
  input.signal?.throwIfAborted();
976
1056
  const { snapshot, plan, validation } = prepared;
@@ -987,7 +1067,7 @@ export class AgentNudger {
987
1067
  ...(input.artifacts ?? []),
988
1068
  ...(existingReport === undefined ? [report] : []),
989
1069
  ];
990
- const transaction = await this.transactions.plan({
1070
+ const transaction = await this.planTransaction(prepared, {
991
1071
  workspaceId: input.workspaceId,
992
1072
  ...(input.principal === undefined ? {} : { principal: input.principal }),
993
1073
  operationKind: 'agent-nudger-map-changes',
@@ -1,4 +1,4 @@
1
- import sharp from 'sharp';
1
+ import sharp from '../core/lazy-native.js';
2
2
  import { canonicalJson } from '../core/canonical.js';
3
3
  import { RENDER_MAX_DECODED_PIXELS, RenderBudget } from '../core/render-budget.js';
4
4
  import { ServiceError } from '../core/result.js';
@@ -31,8 +31,10 @@ export const ARGUMENT_EXAMPLES = {
31
31
  'hoi4.localisation_write': '{"mode":"add","entries":[{"key":"my_focus","text":"My focus"}]} or {"mode":"fix","apply":true}',
32
32
  'hoi4.idea_write': '{"operation":"add","id":"my_spirit","category":"country","body":"picture = my_spirit"}',
33
33
  'hoi4.character_write': '{"operation":"add","id":"TAG_jane_doe","body":"name = TAG_jane_doe"}',
34
+ 'hoi4.country_write': '{"operation":"add","tag":"NEW","name":"New Land","graphicalCulture":{"gfx":"western_european_gfx","twoD":"western_european_2d"},"color":{"r":40,"g":90,"b":160},"history":{"capital":1,"politics":{"rulingParty":"neutrality"},"popularities":[{"ideology":"neutrality","value":100}]}}',
34
35
  'hoi4.event_write': '{"operation":"add","id":"my_events.1","createNamespace":true,"body":"title = my_events.1.t"}',
35
36
  'hoi4.decision_write': '{"operation":"add","id":"my_decision","category":"my_category","body":"icon = generic_research"}',
37
+ 'hoi4.common_write': '{"kind":"on_action","operation":"add","id":"on_startup","file":"common/on_actions/my_mod.txt","createFile":true,"body":"effect = { add_political_power = 10 }"}',
36
38
  'hoi4.tech_write': '{"operation":"add","id":"my_tech","body":"research_cost = 1.5 start_year = 1936"}',
37
39
  'hoi4.doctrine_write': '{"operation":"add","kind":"track","id":"my_track","body":"name = my_track"}',
38
40
  'hoi4.gui_inspect': '{"windowName":"my_window"}',
@@ -48,7 +48,7 @@ export function createModernOperationServer(engine, context = {}, tasks = new Op
48
48
  const controls = new JobControlService(engine);
49
49
  const references = new ReferenceToolService(engine);
50
50
  const privateOperations = options.createPrivateTools?.(engine, context);
51
- const mapEnd = taskToolCatalog.findIndex(({ name }) => name === 'hoi4.doctrine_write') + 1;
51
+ const mapEnd = taskToolCatalog.findIndex(({ name }) => name === 'hoi4.common_write') + 1;
52
52
  const definitions = [
53
53
  ...taskToolCatalog.slice(0, mapEnd),
54
54
  ...referenceTools,
@@ -2,6 +2,8 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { PACKAGE_NAME, PACKAGE_VERSION } from '../../version.js';
4
4
  import { registerCharacterWriteTools } from '../tools/character-write.js';
5
+ import { registerCommonWriteTools } from '../tools/common-write.js';
6
+ import { registerCountryWriteTools } from '../tools/country-write.js';
5
7
  import { registerDecisionWriteTools } from '../tools/decision-write.js';
6
8
  import { registerDoctrineWriteTools } from '../tools/doctrine-write.js';
7
9
  import { registerTechWriteTools } from '../tools/tech-write.js';
@@ -73,10 +75,12 @@ export function createMcpServer(engine, context = {}) {
73
75
  registerLocalisationWriteTools(server, engine, serverContext);
74
76
  registerIdeaWriteTools(server, engine, serverContext);
75
77
  registerCharacterWriteTools(server, engine, serverContext);
78
+ registerCountryWriteTools(server, engine, serverContext);
76
79
  registerEventWriteTools(server, engine, serverContext);
77
80
  registerDecisionWriteTools(server, engine, serverContext);
78
81
  registerTechWriteTools(server, engine, serverContext);
79
82
  registerDoctrineWriteTools(server, engine, serverContext);
83
+ registerCommonWriteTools(server, engine, serverContext);
80
84
  registerReferenceTools(server, engine, serverContext);
81
85
  registerEventTools(server);
82
86
  registerAnalysisTools(server);
@@ -1,5 +1,7 @@
1
1
  import { analysisTaskTools } from '../tools/analysis.js';
2
2
  import { characterWriteTaskTools } from '../tools/character-write.js';
3
+ import { commonWriteTaskTools } from '../tools/common-write.js';
4
+ import { countryWriteTaskTools } from '../tools/country-write.js';
3
5
  import { decisionWriteTaskTools } from '../tools/decision-write.js';
4
6
  import { doctrineWriteTaskTools } from '../tools/doctrine-write.js';
5
7
  import { techWriteTaskTools } from '../tools/tech-write.js';
@@ -19,10 +21,12 @@ export const taskToolCatalog = [
19
21
  ...localisationTaskTools,
20
22
  ...ideaWriteTaskTools,
21
23
  ...characterWriteTaskTools,
24
+ ...countryWriteTaskTools,
22
25
  ...eventWriteTaskTools,
23
26
  ...decisionWriteTaskTools,
24
27
  ...techWriteTaskTools,
25
28
  ...doctrineWriteTaskTools,
29
+ ...commonWriteTaskTools,
26
30
  ...eventTaskTools,
27
31
  ...analysisTaskTools,
28
32
  ...technologyTaskTools,
@@ -0,0 +1,21 @@
1
+ import { strictOperationResultSchema } from '../server/result.js';
2
+ import { commonWriteDataSchema, commonWriteRequestSchema } from '../../schemas/common-write.js';
3
+ import { registerLegacyTaskTools } from '../server/legacy-task-tools.js';
4
+ export const commonWriteTaskTools = [
5
+ {
6
+ name: 'hoi4.common_write',
7
+ title: 'Add, replace or remove a balance of power, AI strategy, AI strategy plan or on_action',
8
+ description: 'Add, replace or remove one definition in a mod common file, touching only that block: kind bop, ai_strategy, ai_strategy_plan or on_action. body is raw script, the text between the braces; it must parse and is written as given. on_action add appends to the key; blockIndex picks one child block. apply false returns the diff. A bop whose ranges do not cover -1 to 1 once is refused. Example: {"kind":"ai_strategy","operation":"remove","id":"my_strategy"}',
9
+ inputSchema: commonWriteRequestSchema,
10
+ outputSchema: strictOperationResultSchema(commonWriteDataSchema),
11
+ annotations: {
12
+ readOnlyHint: false,
13
+ destructiveHint: true,
14
+ idempotentHint: false,
15
+ openWorldHint: false,
16
+ },
17
+ },
18
+ ];
19
+ export function registerCommonWriteTools(server, _engine, _context) {
20
+ registerLegacyTaskTools(server, commonWriteTaskTools);
21
+ }
@@ -0,0 +1,21 @@
1
+ import { strictOperationResultSchema } from '../server/result.js';
2
+ import { countryWriteDataSchema, countryWriteRequestSchema } from '../../schemas/country-write.js';
3
+ import { registerLegacyTaskTools } from '../server/legacy-task-tools.js';
4
+ export const countryWriteTaskTools = [
5
+ {
6
+ name: 'hoi4.country_write',
7
+ title: 'Add, update or remove a country',
8
+ description: 'Add, update or remove one mod country in one write: tag line, country file, colors.txt, history, localisation names and an optional bookmark entry. add needs name, graphicalCulture, color and history; update changes only what is given; remove refuses while mod files name the tag. Warns about missing flags or text. apply false returns diffs. Example: {"operation":"update","tag":"ABC","history":{"capital":5,"stability":0.6},"apply":false}',
9
+ inputSchema: countryWriteRequestSchema,
10
+ outputSchema: strictOperationResultSchema(countryWriteDataSchema),
11
+ annotations: {
12
+ readOnlyHint: false,
13
+ destructiveHint: true,
14
+ idempotentHint: false,
15
+ openWorldHint: false,
16
+ },
17
+ },
18
+ ];
19
+ export function registerCountryWriteTools(server, _engine, _context) {
20
+ registerLegacyTaskTools(server, countryWriteTaskTools);
21
+ }
@@ -1,6 +1,5 @@
1
1
  import { registerLegacyTaskTools } from '../server/legacy-task-tools.js';
2
2
  import { z } from 'zod/v4';
3
- import { computeFocusVisualRevisions as computeCoreFocusVisualRevisions, } from '../../focus/tool-operations.js';
4
3
  import { focusLayoutDeltaSchema, focusLayoutMetricsSchema, focusLayoutQualitySchema, } from '../../schemas/focus.js';
5
4
  import { focusInspectRequestSchema, focusRenderRequestSchema, focusRewriteRequestSchema, } from '../../schemas/focus-requests.js';
6
5
  import { nonNegativeIntegerSchema, renderHashesSchema, sha256Schema, } from '../server/output-schemas.js';
@@ -207,7 +206,9 @@ const artifactProducing = {
207
206
  openWorldHint: false,
208
207
  };
209
208
  /** Compatibility wrapper retained for callers that supplied the signal separately. */
210
- export function computeFocusVisualRevisions(engine, context, workspaceId, snapshot, selectors, signal) {
209
+ export async function computeFocusVisualRevisions(engine, context, workspaceId, snapshot, selectors, signal) {
210
+ // Loaded on first use: the focus renderer and its libraries are not needed to answer `initialize`.
211
+ const { computeFocusVisualRevisions: computeCoreFocusVisualRevisions } = await import('../../focus/tool-operations.js');
211
212
  return computeCoreFocusVisualRevisions(engine, {
212
213
  ...(context.principal === undefined ? {} : { principal: context.principal }),
213
214
  ...(signal === undefined ? {} : { signal }),
@@ -270,7 +270,7 @@ export const mapTaskTools = [
270
270
  {
271
271
  name: 'hoi4.map_rewrite',
272
272
  title: 'Build a world or edit the map',
273
- description: 'Build a world from a reference image or a geography model (geography, geographyPath), or edit provinces, states, regions and supply. Example: {"preview":true,"operations":[{"kind":"create_world","reference":{"imagePath":"references/world.png"}}]}. Preview first to check coastlines, terrain and countries, or a model overlay and report; omit preview to write the generated map and starting scenario (models with biomes or climate are blocked until that stage exists). Returns counts, diagnostics and linked PNGs.',
273
+ description: 'Build a world from a reference image or geography model (geography, geographyPath), add an island to the map (add_landmass), or edit provinces, states, regions and supply. Example: {"preview":true,"operations":[{"kind":"create_world","reference":{"imagePath":"references/world.png"}}]}. Preview first to check coastlines, terrain, countries or a model overlay and report; omit preview to write the map and start scenario (biome or climate models are blocked for now). Returns counts, diagnostics, linked PNGs.',
274
274
  inputSchema: mapRewriteRequestSchema,
275
275
  outputSchema: mapPlanOutputSchema,
276
276
  annotations: {
@@ -20,10 +20,12 @@ const WRITE_SCOPED_TOOLS = new Set([
20
20
  'hoi4.localisation_write',
21
21
  'hoi4.idea_write',
22
22
  'hoi4.character_write',
23
+ 'hoi4.country_write',
23
24
  'hoi4.event_write',
24
25
  'hoi4.decision_write',
25
26
  'hoi4.tech_write',
26
27
  'hoi4.doctrine_write',
28
+ 'hoi4.common_write',
27
29
  ]);
28
30
  const MCP_ALLOWED_METHODS = 'GET, POST, DELETE';
29
31
  const SINGLETON_SECURITY_HEADERS = new Set([
@@ -1,4 +1,4 @@
1
- import sharp from 'sharp';
1
+ import sharp from '../core/lazy-native.js';
2
2
  import { canonicalJson, compareCodeUnits } from '../core/canonical.js';
3
3
  function escapeXml(value) {
4
4
  return String(value)
@@ -144,6 +144,40 @@ function dateBounds(trigger) {
144
144
  return bounds;
145
145
  }
146
146
  const TRIGGER_CHECK_DAYS = 20;
147
+ const PLACEHOLDER = /\$[A-Za-z_]\w*\$/gu;
148
+ /** Every assignment below `block`, at any depth. */
149
+ function descendants(block) {
150
+ const found = [];
151
+ for (const entry of block.entries) {
152
+ if (entry.type === 'assignment') {
153
+ found.push(entry);
154
+ if (entry.value.type === 'block')
155
+ found.push(...descendants(entry.value));
156
+ }
157
+ else if (entry.type === 'block')
158
+ found.push(...descendants(entry));
159
+ }
160
+ return found;
161
+ }
162
+ /** Unquoted `$NAME$` placeholders in a definition's keys and values (quoted text is localisation). */
163
+ function placeholdersOf(definition) {
164
+ const names = new Set();
165
+ const scan = (node) => {
166
+ if (!node.quoted)
167
+ for (const match of node.value.matchAll(PLACEHOLDER))
168
+ names.add(match[0]);
169
+ };
170
+ const nodes = [
171
+ definition,
172
+ ...(definition.value.type === 'block' ? descendants(definition.value) : []),
173
+ ];
174
+ for (const node of nodes) {
175
+ scan(node.key);
176
+ if (node.value.type === 'scalar')
177
+ scan(node.value);
178
+ }
179
+ return [...names];
180
+ }
147
181
  const detectors = {
148
182
  event_triggered_only_with_mtth: (document) => eventsOf(document).flatMap(({ body }) => {
149
183
  const timer = field(body, 'mean_time_to_happen');
@@ -273,6 +307,29 @@ const detectors = {
273
307
  }
274
308
  return findings;
275
309
  },
310
+ scripted_arguments: (document, family, context) => {
311
+ const findings = [];
312
+ const definitions = family === 'scripted_effects' || family === 'scripted_triggers';
313
+ const top = new Set(definitions ? assignmentsOf(document.root) : []);
314
+ for (const helper of top) {
315
+ const names = placeholdersOf(helper);
316
+ if (names.length > 0)
317
+ findings.push({
318
+ node: helper,
319
+ message: `${helper.key.value} uses ${names.join(', ')}, but scripted effects and triggers take no arguments`,
320
+ });
321
+ }
322
+ const helpers = context.modScriptedHelpers;
323
+ if (helpers === undefined || helpers.size === 0)
324
+ return findings;
325
+ for (const call of descendants(document.root))
326
+ if (!top.has(call) && call.value.type === 'block' && helpers.has(call.key.value))
327
+ findings.push({
328
+ node: call,
329
+ message: `${call.key.value} is called with a block, but a scripted effect or trigger takes no arguments`,
330
+ });
331
+ return findings;
332
+ },
276
333
  };
277
334
  /** The rule ids that have a detector. */
278
335
  export const knownMistakeDetectorIds = Object.keys(detectors);
@@ -285,6 +342,14 @@ const ruleFamilies = {
285
342
  event_namespace_missing: ['events'],
286
343
  event_numeric_id_invalid: ['events'],
287
344
  temp_variable_scope_prefix: 'any',
345
+ scripted_arguments: [
346
+ 'events',
347
+ 'decisions',
348
+ 'national_focus',
349
+ 'on_actions',
350
+ 'scripted_effects',
351
+ 'scripted_triggers',
352
+ ],
288
353
  };
289
354
  /**
290
355
  * Flags the known mistakes in one checked file. Resolved rules are not applied. Each finding
@@ -149,6 +149,25 @@
149
149
  "item": "Scoping only exists for regular variables."
150
150
  }
151
151
  ]
152
+ },
153
+ {
154
+ "id": "scripted_arguments",
155
+ "status": "active",
156
+ "severity": "error",
157
+ "surfaces": ["event", "decision", "focus"],
158
+ "title": "Arguments on a scripted effect or trigger",
159
+ "mistake": "A scripted effect or trigger definition uses a $NAME$ placeholder, or a call passes arguments in a block, such as kb_add = { AMOUNT = 12 }.",
160
+ "symptom": "The game logs \"Invalid effect 'AMOUNT'\" and \"Unknown effect-type: AMOUNT\", then \"Unexpected token\" for the rest of the enclosing block, and the argument never reaches the body.",
161
+ "fix": "Set a variable before the call, such as set_temp_variable = { amount = 12 }, call the helper with name = yes, and read the variable in its body.",
162
+ "sources": [
163
+ {
164
+ "kind": "game_doc",
165
+ "page": "Game 1.20.1 vanilla scripts",
166
+ "heading": "common/scripted_effects and common/scripted_triggers",
167
+ "item": "No definition uses a $NAME$ placeholder and no call passes a block."
168
+ }
169
+ ],
170
+ "logPattern": "Unknown effect-type: "
152
171
  }
153
172
  ]
154
173
  }
@@ -51,11 +51,15 @@ function indexDerived(snapshot) {
51
51
  const ids = new Map();
52
52
  const effects = new Set();
53
53
  const triggers = new Set();
54
+ const modHelpers = new Set();
54
55
  for (const symbol of snapshot.index.symbols) {
55
56
  if (symbol.kind === 'scripted_effect')
56
57
  effects.add(symbol.id);
57
58
  else if (symbol.kind === 'scripted_trigger')
58
59
  triggers.add(symbol.id);
60
+ if ((symbol.kind === 'scripted_effect' || symbol.kind === 'scripted_trigger') &&
61
+ (symbol.rootKind === 'mod' || symbol.rootKind === 'dependency'))
62
+ modHelpers.add(symbol.id);
59
63
  const kind = identifierKinds[symbol.kind];
60
64
  if (kind === undefined)
61
65
  continue;
@@ -64,7 +68,13 @@ function indexDerived(snapshot) {
64
68
  ids.set(kind, (set = new Set()));
65
69
  set.add(symbol.id);
66
70
  }
67
- const derived = { ids, effects, triggers, implicitTriggers: implicitTriggerNames(snapshot) };
71
+ const derived = {
72
+ ids,
73
+ effects,
74
+ triggers,
75
+ modHelpers,
76
+ implicitTriggers: implicitTriggerNames(snapshot),
77
+ };
68
78
  derivedByIndex.set(snapshot.index, derived);
69
79
  return derived;
70
80
  }
@@ -775,7 +785,10 @@ export class ReferenceToolService {
775
785
  implicitTriggers: derived.implicitTriggers,
776
786
  ...(playerText === undefined ? {} : { playerText }),
777
787
  eventPopups: this.eventPopupContext(workspaceId, snapshot),
778
- knownMistakes: { eventNamespaces: this.eventNamespaces(workspaceId, snapshot) },
788
+ knownMistakes: {
789
+ eventNamespaces: this.eventNamespaces(workspaceId, snapshot),
790
+ modScriptedHelpers: derived.modHelpers,
791
+ },
779
792
  }, identifierContext(snapshot));
780
793
  }
781
794
  #eventNamespaces = new Map();
@@ -5,7 +5,7 @@ import { loadConfiguration, serverConfigurationSchema, } from './core/configurat
5
5
  import { canonicalJson } from './core/canonical.js';
6
6
  import { CoreEngine } from './core/engine.js';
7
7
  import { ServiceError } from './core/result.js';
8
- import { WorkspaceResolver } from './core/workspace.js';
8
+ import { WorkspaceResolver, canonicalPath, isWithin } from './core/workspace.js';
9
9
  import { CONFIG_VERSION } from './version.js';
10
10
  import { sweepTemporaryDirectories } from './core/temporary-directories.js';
11
11
  import { PROFILES_ENV, parseProfilesEnv, } from './mcp/server/tool-profiles.js';
@@ -231,6 +231,82 @@ export async function automaticConfiguration(start = process.cwd(), options = {}
231
231
  ],
232
232
  });
233
233
  }
234
+ /**
235
+ * Serve the working folder as one extra mod workspace when it is itself a mod (it has a
236
+ * `descriptor.mod` and passes the mod detection) and no workspace already serves it
237
+ * (maintainer decision D-176). Configured workspaces and their storage stay exactly as they are,
238
+ * the configuration on disk is never written, and a working folder that is not a mod changes
239
+ * nothing. Only the extra workspace gets storage of its own, outside the mod.
240
+ *
241
+ * Skipped, because the server's own checks would refuse the overlap and fail to start: a folder
242
+ * that contains a configured workspace or mod root (a mod root that is itself the mod included).
243
+ * A folder inside a configured workspace, or inside a direct child of a mod root, is already
244
+ * served by that workspace.
245
+ */
246
+ export async function withWorkingFolderMod(configuration, start = process.cwd()) {
247
+ const folder = path.resolve(start);
248
+ if (!(await isFile(path.join(folder, 'descriptor.mod'))) ||
249
+ (await isLikelyGameRoot(folder)) ||
250
+ !(await isLikelyModRoot(folder)))
251
+ return configuration;
252
+ const canonicalOrLexical = async (value) => canonicalPath(value).catch(() => path.resolve(value));
253
+ try {
254
+ const canonical = await canonicalPath(folder);
255
+ for (const workspace of configuration.workspaces) {
256
+ const root = await canonicalOrLexical(workspace.root);
257
+ if (isWithin(canonical, root) && !isWithin(root, canonical))
258
+ reportWorkingFolderNote('working_folder_mod_skipped', 'The working folder is a mod that contains a configured workspace, so it is not served as an extra workspace.');
259
+ if (isWithin(root, canonical) || isWithin(canonical, root))
260
+ return configuration;
261
+ }
262
+ for (const modRoot of configuration.modRoots) {
263
+ const root = await canonicalOrLexical(modRoot);
264
+ if (isWithin(canonical, root)) {
265
+ reportWorkingFolderNote('working_folder_mod_skipped', 'The working folder is a mod that is, or contains, a configured mod root, so it is not served as an extra workspace. Point modRoots at its parent folder, or pass workspaceId.');
266
+ return configuration;
267
+ }
268
+ if (!isWithin(root, canonical))
269
+ continue;
270
+ // Discovery serves every real, non-hidden folder directly below a mod root.
271
+ const child = path.relative(root, canonical).split(path.sep)[0] ?? '';
272
+ const status = await lstat(path.join(root, child)).catch(() => undefined);
273
+ if (!child.startsWith('.') && status?.isDirectory() === true && !status.isSymbolicLink())
274
+ return configuration;
275
+ }
276
+ const storage = automaticStorageRoots();
277
+ const baseId = automaticWorkspaceId(canonical);
278
+ const taken = new Set(configuration.workspaces.map((workspace) => workspace.id));
279
+ let id = baseId;
280
+ for (let suffix = 2; taken.has(id); suffix += 1)
281
+ id = `${baseId}_${suffix}`;
282
+ // Storage stays the default: <mod>/.hoi4-agent without a configured storage root, as for a
283
+ // configured workspace, or under the configured storage root. No global setting changes.
284
+ return serverConfigurationSchema.parse({
285
+ ...configuration,
286
+ // Only a configuration with neither workspaces nor mod roots lacks a state root, so no
287
+ // existing mod (configured or discovered) has its storage moved by this.
288
+ ...(configuration.serverStateRoot === undefined &&
289
+ configuration.workspaces.length === 0 &&
290
+ configuration.modRoots.length === 0
291
+ ? { serverStateRoot: storage.serverStateRoot }
292
+ : {}),
293
+ workspaces: [
294
+ ...configuration.workspaces,
295
+ { id, name: path.basename(canonical), root: canonical },
296
+ ],
297
+ });
298
+ }
299
+ catch {
300
+ // The registration limit, a configuration that needs a state root, or an unreadable folder:
301
+ // serve what is configured, and say so.
302
+ reportWorkingFolderNote('working_folder_mod_not_added', 'The working folder is a mod but could not be added as an extra workspace (registration limit reached, no server state root, or unreadable folder); only the configured workspaces are served.');
303
+ return configuration;
304
+ }
305
+ }
306
+ /** A note on stderr (never stdout) about the working-folder mod, without host paths. */
307
+ function reportWorkingFolderNote(event, message) {
308
+ process.stderr.write(`${canonicalJson({ level: 'warn', event, message })}\n`);
309
+ }
234
310
  async function configurationExists(configPath) {
235
311
  try {
236
312
  return (await stat(configPath)).isFile();
@@ -305,6 +381,8 @@ export async function createEngine(configPath = configurationPath(), options = {
305
381
  // The command-line servers read a fetched docs pack from the user's data folder by default.
306
382
  if (configuration.docsRoot === undefined)
307
383
  configuration = { ...configuration, docsRoot: defaultDocsRoot() };
384
+ if (options.workingFolderMod === true && startupError === undefined)
385
+ configuration = await withWorkingFolderMod(configuration);
308
386
  if (!background) {
309
387
  const resolver = await WorkspaceResolver.create(configuration);
310
388
  await sweepTemporaryDirectoriesOf(resolver);
@@ -9,7 +9,11 @@ export const characterWriteRequestSchema = z
9
9
  /** add only: create the file named by file when the mod has no such common/characters file. */
10
10
  createFile: z.boolean().optional(),
11
11
  /** The text between the character braces. Required by add and replace, refused by remove. */
12
- body: z.string().max(32_000).optional(),
12
+ body: z
13
+ .string()
14
+ .max(32_000)
15
+ .optional()
16
+ .describe('Only the text between the character braces, not the whole character_id = {...} block.'),
13
17
  /** The common/characters file. Omit it for replace and remove, and for an add when the mod has one characters file. */
14
18
  file: workspaceRelativePathSchema.max(512).optional(),
15
19
  apply: z