hoi4-agent-tools 4.21.0 → 4.22.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 (100) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +2 -0
  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/domain-tools.js +8 -0
  12. package/dist/hoi4_agent_tools/core/job-controls.js +12 -2
  13. package/dist/hoi4_agent_tools/core/job-executor.js +8 -7
  14. package/dist/hoi4_agent_tools/core/job-operation-registration.js +4 -0
  15. package/dist/hoi4_agent_tools/core/job-store.js +97 -5
  16. package/dist/hoi4_agent_tools/core/job-worker-host.js +2 -2
  17. package/dist/hoi4_agent_tools/core/operation-result.js +118 -33
  18. package/dist/hoi4_agent_tools/core/operation-tasks.js +1 -1
  19. package/dist/hoi4_agent_tools/core/workspace.js +11 -1
  20. package/dist/hoi4_agent_tools/country/job-operations.js +42 -0
  21. package/dist/hoi4_agent_tools/country/write-operations.js +646 -0
  22. package/dist/hoi4_agent_tools/country/write-plan.js +28 -0
  23. package/dist/hoi4_agent_tools/map/engine-validation.js +1 -1
  24. package/dist/hoi4_agent_tools/map/landmass-source.js +42 -0
  25. package/dist/hoi4_agent_tools/map/landmass.js +190 -0
  26. package/dist/hoi4_agent_tools/map/operations.js +20 -6
  27. package/dist/hoi4_agent_tools/map/references.js +6 -3
  28. package/dist/hoi4_agent_tools/map/service.js +88 -8
  29. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  30. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  31. package/dist/hoi4_agent_tools/mcp/server/create.js +4 -0
  32. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +4 -0
  33. package/dist/hoi4_agent_tools/mcp/tools/common-write.js +21 -0
  34. package/dist/hoi4_agent_tools/mcp/tools/country-write.js +21 -0
  35. package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -1
  36. package/dist/hoi4_agent_tools/mcp/transports/http.js +2 -0
  37. package/dist/hoi4_agent_tools/runtime.js +79 -1
  38. package/dist/hoi4_agent_tools/schemas/character-write.js +5 -1
  39. package/dist/hoi4_agent_tools/schemas/common-write.js +74 -0
  40. package/dist/hoi4_agent_tools/schemas/country-write.js +206 -0
  41. package/dist/hoi4_agent_tools/schemas/decision-write.js +5 -1
  42. package/dist/hoi4_agent_tools/schemas/doctrine-write.js +5 -1
  43. package/dist/hoi4_agent_tools/schemas/event-write.js +5 -1
  44. package/dist/hoi4_agent_tools/schemas/idea-write.js +5 -1
  45. package/dist/hoi4_agent_tools/schemas/landmass.js +129 -0
  46. package/dist/hoi4_agent_tools/schemas/localisation-write.js +10 -1
  47. package/dist/hoi4_agent_tools/schemas/map-requests.js +1 -1
  48. package/dist/hoi4_agent_tools/schemas/map.js +2 -0
  49. package/dist/hoi4_agent_tools/schemas/tech-write.js +5 -1
  50. package/dist/hoi4_agent_tools/version.js +1 -1
  51. package/docs/jobs.md +2 -2
  52. package/docs/setup.md +1 -0
  53. package/docs/tools.md +16 -2
  54. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  55. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  56. package/engine/bin/linux-x64/hoi4-engine +0 -0
  57. package/engine/bin/manifest.json +8 -8
  58. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  59. package/npm-shrinkwrap.json +43 -19
  60. package/package.json +1 -1
  61. package/schemas/configuration.schema.json +1 -1
  62. package/schemas/continuous-focus-palette.schema.json +1 -1
  63. package/schemas/custom-weighted-pool.schema.json +1 -1
  64. package/schemas/decision-inspect-input.schema.json +1 -1
  65. package/schemas/error-log-input.schema.json +1 -1
  66. package/schemas/event-feature-manifest.schema.json +1 -1
  67. package/schemas/focus-plan.schema.json +1 -1
  68. package/schemas/focus-planning-sidecar.schema.json +1 -1
  69. package/schemas/geography-model.schema.json +1 -1
  70. package/schemas/gui-animation-source.schema.json +1 -1
  71. package/schemas/gui-helper.schema.json +1 -1
  72. package/schemas/gui-scenario.schema.json +1 -1
  73. package/schemas/helper-expansion-request.schema.json +1 -1
  74. package/schemas/helper-expansion-summary.schema.json +1 -1
  75. package/schemas/impact-inspect-input.schema.json +1 -1
  76. package/schemas/map-operation.schema.json +354 -1
  77. package/schemas/mechanic-test-input.schema.json +1 -1
  78. package/schemas/mod-index-input.schema.json +1 -1
  79. package/schemas/operation-result.schema.json +1 -1
  80. package/schemas/package-check-input.schema.json +1 -1
  81. package/schemas/package-manifest.schema.json +1 -1
  82. package/schemas/probability-analysis-result.schema.json +1 -1
  83. package/schemas/probability-compare-input.schema.json +1 -1
  84. package/schemas/probability-evaluate-input.schema.json +1 -1
  85. package/schemas/probability-inspect-input.schema.json +1 -1
  86. package/schemas/probability-render-input.schema.json +1 -1
  87. package/schemas/probability-scenario-set.schema.json +1 -1
  88. package/schemas/probability-sequence-input.schema.json +1 -1
  89. package/schemas/probability-simulate-input.schema.json +1 -1
  90. package/schemas/probability-sweep-input.schema.json +1 -1
  91. package/schemas/reference-context-input.schema.json +1 -1
  92. package/schemas/reference-read-input.schema.json +1 -1
  93. package/schemas/reference-search-input.schema.json +1 -1
  94. package/schemas/reference-sheets.schema.json +1 -1
  95. package/schemas/scenario-suite.schema.json +1 -1
  96. package/schemas/scenario-test-input.schema.json +1 -1
  97. package/schemas/script-validate-input.schema.json +1 -1
  98. package/schemas/shared-scenario.schema.json +1 -1
  99. package/schemas/source-lookup-input.schema.json +1 -1
  100. package/server.json +2 -2
@@ -226,5 +226,5 @@ export function engineMapOperationSync(op, request, schema, fromPayload) {
226
226
  const length = typeof announced === 'number' && Number.isSafeInteger(announced) ? announced : 0;
227
227
  if (length < 0 || answer.length < newline + 1 + length)
228
228
  throw unavailable(`hoi4-engine ${op} answered a short payload`, 'invalid_output');
229
- return fromPayload(answer.subarray(newline + 1, newline + 1 + length));
229
+ return fromPayload(answer.subarray(newline + 1, newline + 1 + length), parsed.data);
230
230
  }
@@ -0,0 +1,42 @@
1
+ import { sha256Bytes } from '../core/canonical.js';
2
+ import { ServiceError } from '../core/result.js';
3
+ import { prepareSource, readBoundedFile, verifySource } from '../core/scanner.js';
4
+ /** Largest `add_landmass` mask image (a full-size 24-bit bitmap of the largest map fits). */
5
+ export const LANDMASS_MASK_MAX_BYTES = 256 * 1024 * 1024;
6
+ /**
7
+ * Read an `add_landmass` mask image from the workspace's own mod root, through the same
8
+ * canonical-path and stale-source checks as every other workspace source.
9
+ */
10
+ export async function readLandmassMask(resolver, workspaceId, requestedPath, principal, signal) {
11
+ const relativePath = requestedPath.replaceAll('\\', '/');
12
+ if (!/\.(?:png|tga|dds|bmp)$/iu.test(relativePath) || relativePath.includes(':'))
13
+ throw new ServiceError('MAP_LANDMASS_MASK_PATH_INVALID', 'maskImage.path must name a workspace-relative .png, .tga, .dds or .bmp file');
14
+ const resolved = await resolver.resolvePath(workspaceId, relativePath, 'read', ['mod'], principal);
15
+ const source = await prepareSource(resolved.root, relativePath, signal);
16
+ try {
17
+ if (!source.metadata.isFile())
18
+ throw new ServiceError('SOURCE_NOT_REGULAR_FILE', 'The mask image must be a regular file');
19
+ if (source.metadata.size < 1 || source.metadata.size > LANDMASS_MASK_MAX_BYTES)
20
+ throw new ServiceError('MAP_LANDMASS_MASK_TOO_LARGE', `The mask image must hold between 1 byte and ${LANDMASS_MASK_MAX_BYTES} bytes`, { limit: LANDMASS_MASK_MAX_BYTES });
21
+ const bytes = await readBoundedFile(source.handle, LANDMASS_MASK_MAX_BYTES, signal);
22
+ await verifySource(resolved.root, source);
23
+ const sha256 = sha256Bytes(bytes);
24
+ const displayPath = `mod:${relativePath}`;
25
+ return {
26
+ prepared: { displayPath, sha256, bytes },
27
+ evidence: {
28
+ absolutePath: source.canonicalPath,
29
+ displayPath,
30
+ relativePath,
31
+ rootKind: resolved.root.kind,
32
+ loadOrder: resolved.root.loadOrder,
33
+ size: source.metadata.size,
34
+ modifiedMs: source.metadata.mtimeMs,
35
+ sha256,
36
+ },
37
+ };
38
+ }
39
+ finally {
40
+ await source.handle.close();
41
+ }
42
+ }
@@ -0,0 +1,190 @@
1
+ import { z } from 'zod/v4';
2
+ import { ServiceError } from '../core/result.js';
3
+ import { engineMapOperationSync, mapValidateRequest } from './engine-validation.js';
4
+ import { nodeLocation } from '../core/source/index.js';
5
+ import { collectMapScriptReferences, mapReferenceScriptFile } from './references.js';
6
+ /**
7
+ * `add_landmass` (packet T4) on the engine: `map.add_landmass` plans an island with relief in
8
+ * open sea (provinces, heightmap, terrain, rivers, trees, normal and colour maps, states, its own
9
+ * strategic region, weather, positions and supply) from the scanned map files and returns every
10
+ * changed file. The map rewrite then validates the whole map against its baseline and writes the
11
+ * plan as one transaction, as for every map operation. Nothing falls back to TypeScript.
12
+ */
13
+ export const MAP_ADD_LANDMASS_OP = 'map.add_landmass';
14
+ const answerSchema = z
15
+ .object({
16
+ files: z.array(z
17
+ .object({
18
+ relativePath: z.string().min(1),
19
+ beforeSha256: z.string().nullable(),
20
+ length: z.number().int().min(0),
21
+ mediaType: z.string().min(1),
22
+ })
23
+ .strict()),
24
+ summary: z.record(z.string(), z.unknown()),
25
+ warnings: z.array(z.looseObject({ code: z.string(), message: z.string() })),
26
+ changedBounds: z
27
+ .object({
28
+ minX: z.number().int(),
29
+ minY: z.number().int(),
30
+ maxX: z.number().int(),
31
+ maxY: z.number().int(),
32
+ count: z.number().int().min(0),
33
+ })
34
+ .strict(),
35
+ })
36
+ .strict();
37
+ /** Typed arrays as plain arrays, so the resolved geography reads the same in the engine. */
38
+ function plainGeography(geography) {
39
+ return JSON.parse(JSON.stringify(geography, (_key, value) => ArrayBuffer.isView(value) && !(value instanceof DataView)
40
+ ? Array.from(value)
41
+ : value instanceof Map
42
+ ? undefined
43
+ : value));
44
+ }
45
+ /** The English names an island writes: its states, their capitals' victory points and its region. */
46
+ export function landmassLocalisation(operation, summary) {
47
+ const file = operation.localisation?.file ??
48
+ `localisation/english/map_landmass_${operation.id.replace(/[^A-Za-z0-9_]/gu, '_').toLowerCase()}_l_english.yml`;
49
+ const region = Number(summary.strategicRegion);
50
+ const regionName = operation.region.name ?? 'Island';
51
+ const states = summary.stateCapitals ?? [];
52
+ const entries = [];
53
+ states.forEach(({ state, capital, victoryPoints }, index) => {
54
+ const name = operation.states.names?.[index] ??
55
+ (states.length === 1 ? regionName : `${regionName} ${index + 1}`);
56
+ entries.push({ key: `STATE_${state}`, value: name, file });
57
+ if (victoryPoints)
58
+ entries.push({ key: `VICTORY_POINTS_${capital}`, value: name, file });
59
+ });
60
+ if (Number.isInteger(region))
61
+ entries.push({ key: `STRATEGICREGION_${region}`, value: regionName, file });
62
+ return entries;
63
+ }
64
+ export function planAddLandmass(index, operation, geography, mask) {
65
+ if (geography === undefined)
66
+ throw new ServiceError('MAP_GEOGRAPHY_NOT_PREPARED', 'Geography models must be prepared by the authorized workspace service');
67
+ if (!geography.valid)
68
+ throw new ServiceError('MAP_GEOGRAPHY_INVALID', 'The island geography has errors; fix them (see the MAP_GEOGRAPHY_* diagnostics) before adding it', { modelHash: geography.geography.hash });
69
+ if ((operation.maskImage === undefined) !== (mask === undefined))
70
+ throw new ServiceError('MAP_LANDMASS_MASK_NOT_PREPARED', 'The mask image was not prepared');
71
+ const request = mapValidateRequest(index);
72
+ // The localisation file is the adapter's (it writes the names); the engine plans the map only.
73
+ const { geography: _inline, geographyPath: _path, maskImage, localisation: _localisation, ...rest } = operation;
74
+ const body = {
75
+ files: request.body.files,
76
+ sourceRoots: request.body.sourceRoots,
77
+ operation: {
78
+ ...rest,
79
+ geography: plainGeography(geography.geography),
80
+ ...(maskImage === undefined || mask === undefined
81
+ ? {}
82
+ : {
83
+ maskImage: {
84
+ displayPath: mask.displayPath,
85
+ sha256: mask.sha256,
86
+ size: mask.bytes.length,
87
+ x: maskImage.x,
88
+ y: maskImage.y,
89
+ },
90
+ }),
91
+ },
92
+ };
93
+ const payload = mask === undefined ? request.payload : Buffer.concat([request.payload, mask.bytes]);
94
+ const plan = engineMapOperationSync(MAP_ADD_LANDMASS_OP, { body, payload }, answerSchema, (bytes, answer) => {
95
+ const changes = [];
96
+ let at = 0;
97
+ for (const file of answer.files) {
98
+ if (at + file.length > bytes.length)
99
+ throw new ServiceError('ENGINE_UNAVAILABLE', 'hoi4-engine map.add_landmass answered a short payload', {
100
+ op: MAP_ADD_LANDMASS_OP,
101
+ reason: 'invalid_output',
102
+ });
103
+ changes.push({
104
+ relativePath: file.relativePath,
105
+ content: Buffer.from(bytes.subarray(at, at + file.length)),
106
+ mediaType: file.mediaType,
107
+ });
108
+ at += file.length;
109
+ }
110
+ const diagnostics = answer.warnings.map((warning) => ({
111
+ code: warning.code,
112
+ severity: warning.severity === 'info' ? 'info' : 'warning',
113
+ category: 'map',
114
+ message: warning.message,
115
+ operationId: operation.id,
116
+ ...(typeof warning.details === 'object' && warning.details !== null
117
+ ? { details: warning.details }
118
+ : {}),
119
+ }));
120
+ diagnostics.push({
121
+ code: 'MAP_LANDMASS_ADDED',
122
+ severity: 'info',
123
+ category: 'map',
124
+ message: `Added an island of ${String(answer.summary.provinces?.land ?? 0)} land province(s) with its own strategic region ${String(answer.summary.strategicRegion)}`,
125
+ operationId: operation.id,
126
+ details: answer.summary,
127
+ });
128
+ return { changes, bounds: answer.changedBounds, diagnostics, summary: answer.summary };
129
+ });
130
+ const absorbed = plan.summary.seaProvincesAbsorbed;
131
+ if (Array.isArray(absorbed) && absorbed.length > 0)
132
+ refuseAbsorbedSeaReferences(index.sourceFiles, absorbed.filter((id) => typeof id === 'number'));
133
+ return plan;
134
+ }
135
+ /**
136
+ * Script files read for references to an absorbed sea province: the map reference folders
137
+ * (`MAP_REFERENCE_SCRIPT_PATTERNS`: events, focuses, decisions, scripted helpers, on-actions,
138
+ * ideas, characters, AI, country and unit history) and every other script under `common/`.
139
+ */
140
+ export function absorbedSeaScriptFile(relativePath) {
141
+ return (mapReferenceScriptFile(relativePath) ||
142
+ /^common\/.+\.txt$/iu.test(relativePath.replaceAll('\\', '/')));
143
+ }
144
+ /** Whether `text` holds `id` as a whole number token (not part of a longer number, word or decimal). */
145
+ function namesNumber(text, id) {
146
+ const match = new RegExp(`(?<![\\w.])${String(id)}(?![\\w.])`, 'u').exec(text);
147
+ return match === null ? undefined : text.slice(0, match.index).split('\n').length;
148
+ }
149
+ /**
150
+ * Script and unit-history references to the sea provinces an island absorbs
151
+ * (`absorbCoveredSeaProvinces`): fleets based or located there, and every event, focus, decision,
152
+ * scripted helper, on-action, idea, AI strategy, country history or other `common/` script that
153
+ * names the province. A file that does not parse is searched as text instead: it counts as a
154
+ * reference when it holds the province id as a whole number. The engine refuses the map-side
155
+ * references itself; these lie outside the map files.
156
+ */
157
+ export function absorbedSeaReferences(files, provinces) {
158
+ const wanted = new Set(provinces);
159
+ const { references, unparsable } = collectMapScriptReferences(files, absorbedSeaScriptFile);
160
+ return {
161
+ references: references
162
+ .filter(({ entity, id }) => entity === 'province' && wanted.has(id))
163
+ .map(({ id, file, key, document, node }) => ({
164
+ province: id,
165
+ file: file.displayPath,
166
+ key,
167
+ line: nodeLocation(document, node).start.line,
168
+ })),
169
+ unparsable: unparsable.flatMap(({ file }) => {
170
+ const text = file.bytes.toString('latin1');
171
+ return provinces.flatMap((province) => {
172
+ const line = namesNumber(text, province);
173
+ return line === undefined
174
+ ? []
175
+ : [{ province, file: file.displayPath, key: '(unparsable file)', line }];
176
+ });
177
+ }),
178
+ };
179
+ }
180
+ /**
181
+ * Refuses the island when a script uses an absorbed sea province, or may: a script that does not
182
+ * parse and holds the province id.
183
+ */
184
+ export function refuseAbsorbedSeaReferences(files, provinces) {
185
+ const { references, unparsable } = absorbedSeaReferences(files, provinces);
186
+ if (references.length > 0)
187
+ throw new ServiceError('MAP_LANDMASS_SEA_REFERENCED', `Sea province(s) ${[...new Set(references.map(({ province }) => province))].join(', ')} that the island would absorb are named by ${String(references.length)} script or unit-history reference(s); remove them or move the island`, { references });
188
+ if (unparsable.length > 0)
189
+ throw new ServiceError('MAP_LANDMASS_SEA_REFERENCED', `${String(unparsable.length)} script file(s) that do not parse hold the id of a sea province the island would absorb, so a reference cannot be ruled out; fix or check them first`, { provinces, unparsable });
190
+ }
@@ -2,6 +2,7 @@ import path from 'node:path';
2
2
  import { setImmediate as yieldToEventLoop } from 'node:timers/promises';
3
3
  import { lookupMapCoordinate } from './catalog.js';
4
4
  import { canonicalJson, compareCodeUnits, deterministicId, sha256Bytes, } from '../core/canonical.js';
5
+ import { publicServiceErrorDetails } from '../core/operation-result.js';
5
6
  import { ServiceError } from '../core/result.js';
6
7
  import { applyReplacements, assignments, encodeSource, parseLocalisation, parseClausewitz, } from '../core/source/index.js';
7
8
  import { rgbKey } from './bmp.js';
@@ -17,6 +18,7 @@ import { planWorldOutputs, refreshWorldOutputs, WORLD_OUTPUT_MANIFEST, } from '.
17
18
  import { resolvePartitionMode } from './partition.js';
18
19
  import { applyAssignTerritory, applyRepartitionStates, } from './territory-operations.js';
19
20
  import { unsupportedGeographyParts } from './relief/index.js';
21
+ import { landmassLocalisation, planAddLandmass, } from './landmass.js';
20
22
  import { resolvePaintedRelief } from './relief/painted-relief.js';
21
23
  export function* cancellationCheckpoint(signal, iteration = 0, stride = 1) {
22
24
  if (iteration % stride !== 0)
@@ -934,7 +936,10 @@ export function appendLocalisationEntry(document, key, value) {
934
936
  return encodeSource(`${document.text}${separator}${key}: "${escapedLocalisationValue(value)}"${document.newline}`, 'utf8-bom');
935
937
  }
936
938
  function applyStateLocalisation(index, changes, operation, key) {
937
- const policy = operation.localisation;
939
+ applyEnglishLocalisationPolicy(index, changes, operation.id, operation.localisation, key);
940
+ }
941
+ /** One English localisation key by an `existing` or `upsert` policy, as state creation writes it. */
942
+ function applyEnglishLocalisationPolicy(index, changes, operationId, policy, key) {
938
943
  if (policy === null || typeof policy !== 'object' || Array.isArray(policy)) {
939
944
  throw new ServiceError('MAP_STATE_LOCALISATION_POLICY_REQUIRED', 'State creation requires an explicit existing or upsert localisation policy');
940
945
  }
@@ -978,7 +983,7 @@ function applyStateLocalisation(index, changes, operation, key) {
978
983
  }
979
984
  const replacement = localisationEntryLine(current.document, current.entry, value);
980
985
  const text = `${current.document.text.slice(0, current.entry.start)}${replacement}${current.document.text.slice(current.entry.end)}`;
981
- addChange(changes, current.file.relativePath, encodeSource(text, 'utf8-bom'), operation.id, 'text/yaml');
986
+ addChange(changes, current.file.relativePath, encodeSource(text, 'utf8-bom'), operationId, 'text/yaml');
982
987
  return;
983
988
  }
984
989
  if (requestedFile === undefined) {
@@ -987,12 +992,12 @@ function applyStateLocalisation(index, changes, operation, key) {
987
992
  const relativePath = safeLocalisationRelativePath(index, requestedFile);
988
993
  const target = index.activeFiles.byRelativePath.get(normalizeRelative(relativePath));
989
994
  if (target === undefined) {
990
- addChange(changes, relativePath, encodeSource(`l_english:\n${key}: "${escapedLocalisationValue(value)}"\n`, 'utf8-bom'), operation.id, 'text/yaml');
995
+ addChange(changes, relativePath, encodeSource(`l_english:\n${key}: "${escapedLocalisationValue(value)}"\n`, 'utf8-bom'), operationId, 'text/yaml');
991
996
  return;
992
997
  }
993
998
  const document = parseLocalisation(target.bytes, target.displayPath);
994
999
  requireSafeLocalisationDocument(document, target.relativePath);
995
- addChange(changes, target.relativePath, appendLocalisationEntry(document, key, value), operation.id, 'text/yaml');
1000
+ addChange(changes, target.relativePath, appendLocalisationEntry(document, key, value), operationId, 'text/yaml');
996
1001
  }
997
1002
  function splitScalar(total, ratio, policy) {
998
1003
  if (policy.method === 'retain-in-source')
@@ -4228,6 +4233,15 @@ function* planMapOperationSteps(base, operations, signal, context = {}) {
4228
4233
  if (outputs !== undefined)
4229
4234
  worldOutputs.push(outputs);
4230
4235
  }
4236
+ else if (operation.kind === 'add_landmass') {
4237
+ const landmass = planAddLandmass(currentIndex(base, changes), operation, context.geographyModels?.get(operation.id), context.landmassMasks?.get(operation.id));
4238
+ for (const change of landmass.changes)
4239
+ addChange(changes, change.relativePath, change.content, operation.id, change.mediaType);
4240
+ for (const entry of landmassLocalisation(operation, landmass.summary))
4241
+ applyEnglishLocalisationPolicy(currentIndex(base, changes), changes, operation.id, { method: 'upsert', language: 'l_english', value: entry.value, file: entry.file }, entry.key);
4242
+ diagnostics.push(...landmass.diagnostics);
4243
+ expectedChangedBounds = mergeBounds(expectedChangedBounds, landmass.bounds);
4244
+ }
4231
4245
  else if (operation.kind === 'move_state_provinces')
4232
4246
  applyMoveStateProvinces(base, changes, operation);
4233
4247
  else if (operation.kind === 'assign_territory') {
@@ -4295,7 +4309,7 @@ function* planMapOperationSteps(base, operations, signal, context = {}) {
4295
4309
  operationId: operation.id,
4296
4310
  ...(Object.keys(serviceError.details).length === 0
4297
4311
  ? {}
4298
- : { details: serviceError.details }),
4312
+ : { details: publicServiceErrorDetails(serviceError) }),
4299
4313
  };
4300
4314
  blockers.push(blocker);
4301
4315
  diagnostics.push({
@@ -4345,7 +4359,7 @@ function* planMapOperationSteps(base, operations, signal, context = {}) {
4345
4359
  operationId: lastOperation.id,
4346
4360
  ...(Object.keys(serviceError.details).length === 0
4347
4361
  ? {}
4348
- : { details: serviceError.details }),
4362
+ : { details: publicServiceErrorDetails(serviceError) }),
4349
4363
  });
4350
4364
  diagnostics.push({
4351
4365
  code: serviceError.code,
@@ -116,12 +116,15 @@ const SINGLE_VALUED_KEYS = new Set([
116
116
  export function singleValuedReference(reference) {
117
117
  return reference.form === 'field' && SINGLE_VALUED_KEYS.has(reference.key);
118
118
  }
119
- /** Collect every numbered map reference in the active (unshadowed) script files given. */
120
- export function collectMapScriptReferences(files) {
119
+ /**
120
+ * Collect every numbered map reference in the active (unshadowed) script files given. `accept` picks
121
+ * the script files read (by default the folders of `MAP_REFERENCE_SCRIPT_PATTERNS`).
122
+ */
123
+ export function collectMapScriptReferences(files, accept = mapReferenceScriptFile) {
121
124
  const references = [];
122
125
  const unparsable = [];
123
126
  const active = files
124
- .filter((file) => file.shadowedBy === undefined && mapReferenceScriptFile(file.relativePath))
127
+ .filter((file) => file.shadowedBy === undefined && accept(file.relativePath))
125
128
  .sort((left, right) => left.loadOrder - right.loadOrder || compareCodeUnits(left.displayPath, right.displayPath));
126
129
  for (const file of active) {
127
130
  const document = parseClausewitz(file.bytes, file.displayPath);
@@ -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',
@@ -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
+ }