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
@@ -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([
@@ -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
@@ -0,0 +1,74 @@
1
+ import { z } from 'zod/v4';
2
+ import { backgroundRequestKeySchema, workspaceIdSchema, workspaceRelativePathSchema, } from './common.js';
3
+ /** The kinds `hoi4.common_write` writes; each is one descriptor in the engine (`hoi4-script-write`, ADR 0089). */
4
+ export const COMMON_WRITE_KINDS = ['bop', 'ai_strategy', 'ai_strategy_plan', 'on_action'];
5
+ export const commonWriteRequestSchema = z
6
+ .object({
7
+ workspaceId: workspaceIdSchema,
8
+ kind: z.enum(COMMON_WRITE_KINDS),
9
+ operation: z.enum(['add', 'replace', 'remove']),
10
+ /** The definition: a top-level key of the file, or the on_action name for kind on_action. */
11
+ id: z.string().regex(/^[A-Za-z_][A-Za-z0-9_.-]{0,255}$/u),
12
+ /** The text between the braces of the definition (for on_action, of the on_action key). Required by add and replace, refused by remove. Raw script: it must parse, and it is written byte for byte. */
13
+ body: z
14
+ .string()
15
+ .max(64_000)
16
+ .optional()
17
+ .describe('Only the text between the definition braces, not the whole id = {...} block.'),
18
+ /** on_action only: the child block of the on_action key that replace or remove acts on, counted from 0. */
19
+ blockIndex: z.number().int().min(0).max(10_000).optional(),
20
+ /** add only: create the file named by file when the mod has no such file. */
21
+ createFile: z.boolean().optional(),
22
+ /** The file under the kind's folder. Omit it to use the mod file that defines the id; add into a folder with one file also needs no name. */
23
+ file: workspaceRelativePathSchema.max(512).optional(),
24
+ apply: z
25
+ .boolean()
26
+ .default(false)
27
+ .describe('false returns the diff and writes nothing; true makes the same change.'),
28
+ requestKey: backgroundRequestKeySchema.optional(),
29
+ })
30
+ .strict();
31
+ export const commonWriteDataSchema = z
32
+ .object({
33
+ operation: z.enum(['add', 'replace', 'remove']),
34
+ kind: z.enum(COMMON_WRITE_KINDS),
35
+ id: z.string().max(256),
36
+ path: z.string().max(1024),
37
+ applied: z.boolean(),
38
+ /** The unified diff of the file, cut at a line when it is long. */
39
+ diff: z.string().max(12_000),
40
+ diffTruncated: z.boolean(),
41
+ /** The other definitions of the file, checked to be byte for byte as they were. */
42
+ untouchedDefinitions: z.number().int().min(0),
43
+ /** What the kind's check found that does not stop the write. */
44
+ findings: z
45
+ .array(z
46
+ .object({
47
+ severity: z.enum(['warning']),
48
+ code: z.string().max(128),
49
+ message: z.string().max(1024),
50
+ })
51
+ .strict())
52
+ .max(50),
53
+ /** How many findings and undefined references were left out of the lists above to keep the answer short. */
54
+ omitted: z
55
+ .object({
56
+ findings: z.number().int().min(0),
57
+ diagnostics: z.number().int().min(0),
58
+ localisation: z.number().int().min(0),
59
+ sprites: z.number().int().min(0),
60
+ categories: z.number().int().min(0),
61
+ focuses: z.number().int().min(0),
62
+ })
63
+ .strict(),
64
+ /** What the definition refers to and the mod does not define. The write still happens. */
65
+ missing: z
66
+ .object({
67
+ localisation: z.array(z.string().max(256)).max(50),
68
+ sprites: z.array(z.string().max(256)).max(20),
69
+ categories: z.array(z.string().max(256)).max(5),
70
+ focuses: z.array(z.string().max(256)).max(100),
71
+ })
72
+ .strict(),
73
+ })
74
+ .strict();
@@ -0,0 +1,206 @@
1
+ import { z } from 'zod/v4';
2
+ import { backgroundRequestKeySchema, workspaceIdSchema, workspaceRelativePathSchema, } from './common.js';
3
+ /** A token the game reads as a bare word: ids, ideologies, cultures, technologies. */
4
+ const tokenSchema = z.string().regex(/^[A-Za-z0-9_.:@-]{1,256}$/u);
5
+ /** Text written between quotes: one line without a quote. */
6
+ const quotedSchema = z
7
+ .string()
8
+ .min(1)
9
+ .max(512)
10
+ .regex(/^[^"\r\n]+$/u);
11
+ /** A localised text: one line. */
12
+ const textSchema = z
13
+ .string()
14
+ .min(1)
15
+ .max(200)
16
+ .regex(/^[^\p{Cc}\p{Zl}\p{Zp}]+$/u);
17
+ const channelSchema = z.number().int().min(0).max(255);
18
+ const rgbSchema = z.object({ r: channelSchema, g: channelSchema, b: channelSchema }).strict();
19
+ export const countryIdeologyNameSchema = z
20
+ .object({
21
+ ideology: tokenSchema,
22
+ /** `<TAG>_<ideology>`. */
23
+ name: textSchema.optional(),
24
+ /** `<TAG>_<ideology>_ADJ`. */
25
+ adjective: textSchema.optional(),
26
+ /** `<TAG>_<ideology>_DEF`. */
27
+ definition: textSchema.optional(),
28
+ })
29
+ .strict();
30
+ export const countryHistorySchema = z
31
+ .object({
32
+ /** The capital state id. Required by add. */
33
+ capital: z.number().int().min(1).max(100_000).optional(),
34
+ /** The order of battle file of history/units, without .txt. */
35
+ oob: tokenSchema.optional(),
36
+ /** add only: the starting ideas (add_ideas). */
37
+ ideas: z.array(tokenSchema).min(1).max(50).optional(),
38
+ researchSlots: z.number().int().min(0).max(20).optional(),
39
+ stability: z.number().min(0).max(1).optional(),
40
+ warSupport: z.number().min(0).max(1).optional(),
41
+ /** set_technology, in order. Update replaces the block. */
42
+ technology: z
43
+ .array(z.object({ id: tokenSchema, level: z.number().int().min(0).max(10) }).strict())
44
+ .min(1)
45
+ .max(200)
46
+ .optional(),
47
+ /** set_politics. Required by add; update replaces the block. */
48
+ politics: z
49
+ .object({
50
+ rulingParty: tokenSchema,
51
+ lastElection: z
52
+ .string()
53
+ .regex(/^\d{1,5}\.\d{1,2}\.\d{1,2}$/u)
54
+ .optional(),
55
+ electionFrequency: z.number().int().min(1).max(1200).optional(),
56
+ electionsAllowed: z.boolean().optional(),
57
+ })
58
+ .strict()
59
+ .optional(),
60
+ /** set_popularities, in order, adding up to 100. Required by add; update replaces the block. */
61
+ popularities: z
62
+ .array(z.object({ ideology: tokenSchema, value: z.number().int().min(0).max(100) }).strict())
63
+ .min(1)
64
+ .max(20)
65
+ .optional(),
66
+ /** recruit_character lines; update adds the missing ones and removes none. */
67
+ recruitCharacters: z.array(tokenSchema).min(1).max(50).optional(),
68
+ })
69
+ .strict();
70
+ export const countryBookmarkSchema = z
71
+ .object({
72
+ /** The bookmark file under common/bookmarks. */
73
+ file: workspaceRelativePathSchema.max(512),
74
+ /** The bookmark's name key. */
75
+ name: quotedSchema.optional(),
76
+ /** The ideology the bookmark shows. Required to list the country. */
77
+ ideology: tokenSchema.optional(),
78
+ /** The localisation key of the country's bookmark text. */
79
+ history: quotedSchema.optional(),
80
+ /** major lists the country before "---"; minor after it, with minor = yes. */
81
+ role: z.enum(['major', 'minor']).optional(),
82
+ /** add only: create file as a new bookmark that starts with this country. */
83
+ create: z
84
+ .object({
85
+ desc: quotedSchema,
86
+ /** 1936.1.1.12 */
87
+ date: z.string().regex(/^\d{1,5}\.\d{1,2}\.\d{1,2}(?:\.\d{1,2})?$/u),
88
+ picture: quotedSchema,
89
+ default: z.boolean().optional(),
90
+ /** The "---" entry's text key, for the countries the list does not name. */
91
+ otherHistory: quotedSchema.optional(),
92
+ })
93
+ .strict()
94
+ .optional(),
95
+ })
96
+ .strict();
97
+ /**
98
+ * Published shapes: the nested fields are named in the descriptions, which keeps the tool listing
99
+ * inside the discovery budget. Every field is validated by the full schema behind each pipe.
100
+ */
101
+ const compactHistorySchema = z
102
+ .looseObject({ capital: z.number().int().optional() })
103
+ .describe('capital (state id); politics {rulingParty, lastElection?, electionFrequency?, electionsAllowed?}; popularities [{ideology, value}] summing to 100; oob; ideas (add only); researchSlots; stability and warSupport (0-1); technology [{id, level}]; recruitCharacters [id]. add needs capital, politics and popularities; update replaces only what is given.')
104
+ .transform((value) => value)
105
+ .pipe(countryHistorySchema);
106
+ const compactBookmarkSchema = z
107
+ .looseObject({ file: z.string() })
108
+ .describe('file (common/bookmarks/*.txt); name (the bookmark name key); ideology; history (text key); role major|minor; create {desc, date 1936.1.1.12, picture, default?, otherHistory?} makes a new bookmark (add only). remove takes no bookmark: it clears the tag from every bookmark of the mod.')
109
+ .transform((value) => value)
110
+ .pipe(countryBookmarkSchema);
111
+ const compactIdeologyNamesSchema = z
112
+ .unknown()
113
+ .describe('[{ideology, name?, adjective?, definition?}]: <TAG>_<ideology>, _ADJ, _DEF.')
114
+ .pipe(z.array(countryIdeologyNameSchema).min(1).max(20));
115
+ export const countryWriteRequestSchema = z
116
+ .object({
117
+ workspaceId: workspaceIdSchema,
118
+ operation: z.enum(['add', 'update', 'remove']),
119
+ /** The country tag. A new tag is an upper-case letter and two upper-case letters or digits. */
120
+ tag: z.string().regex(/^[A-Z0-9]{3}$/u),
121
+ /** add: the country name; it names the files and, with no localisation given, its text. */
122
+ name: textSchema.optional(),
123
+ /** <TAG>_ADJ; defaults to name on add. */
124
+ adjective: textSchema.optional(),
125
+ /** <TAG>_DEF; defaults to name on add. */
126
+ definition: textSchema.optional(),
127
+ /** Per-ideology names (<TAG>_<ideology>, _ADJ, _DEF). */
128
+ ideologyNames: compactIdeologyNamesSchema.optional(),
129
+ /** add: the mod's common/country_tags file; needed when the mod has several or none. */
130
+ tagFile: workspaceRelativePathSchema.max(512).optional(),
131
+ /** Both graphical cultures: gfx (…_gfx) and twoD (…_2d). Required by add. */
132
+ graphicalCulture: z.object({ gfx: tokenSchema, twoD: tokenSchema }).strict().optional(),
133
+ /** The map colour. Required by add. */
134
+ color: rgbSchema.optional(),
135
+ /** The interface colour; defaults to color on add. */
136
+ colorUi: rgbSchema.optional(),
137
+ history: compactHistorySchema.optional(),
138
+ bookmark: compactBookmarkSchema.optional(),
139
+ apply: z
140
+ .boolean()
141
+ .default(false)
142
+ .describe('false returns the diff and writes nothing; true makes the same change.'),
143
+ requestKey: backgroundRequestKeySchema.optional(),
144
+ })
145
+ .strict()
146
+ .superRefine((value, context) => {
147
+ const issue = (path, message) => context.addIssue({ code: 'custom', path: [path], message });
148
+ if (value.operation === 'add') {
149
+ if (value.name === undefined)
150
+ issue('name', 'add needs the country name');
151
+ if (value.graphicalCulture === undefined)
152
+ issue('graphicalCulture', 'add needs both graphical cultures');
153
+ if (value.color === undefined)
154
+ issue('color', 'add needs the map colour');
155
+ if (value.history === undefined)
156
+ issue('history', 'add needs the history');
157
+ }
158
+ if (value.operation === 'remove')
159
+ for (const field of [
160
+ 'name',
161
+ 'adjective',
162
+ 'definition',
163
+ 'ideologyNames',
164
+ 'graphicalCulture',
165
+ 'color',
166
+ 'colorUi',
167
+ 'history',
168
+ 'bookmark',
169
+ ])
170
+ if (value[field] !== undefined)
171
+ issue(field, `remove takes no ${field}`);
172
+ if (value.operation !== 'add' && value.bookmark?.create !== undefined)
173
+ issue('bookmark', 'only add creates a bookmark');
174
+ if (value.operation !== 'add' && value.tagFile !== undefined)
175
+ issue('tagFile', 'only add chooses the tag file; update and remove find it');
176
+ });
177
+ const missingListSchema = z.array(z.string().max(512)).max(30);
178
+ export const countryWriteDataSchema = z
179
+ .object({
180
+ operation: z.enum(['add', 'update', 'remove']),
181
+ tag: z.string().max(3),
182
+ applied: z.boolean(),
183
+ files: z
184
+ .array(z
185
+ .object({
186
+ path: z.string().max(1024),
187
+ action: z.enum(['create', 'modify', 'delete']),
188
+ /** The unified diff of the file, cut at a line when it is long; empty for a deletion. */
189
+ diff: z.string().max(12_000),
190
+ diffTruncated: z.boolean(),
191
+ })
192
+ .strict())
193
+ .max(16),
194
+ /** What the country refers to and the mod does not have. The write still happens. */
195
+ missing: z
196
+ .object({
197
+ flags: missingListSchema,
198
+ localisation: missingListSchema,
199
+ characters: missingListSchema,
200
+ oob: missingListSchema,
201
+ })
202
+ .strict(),
203
+ /** Localisation keys of the country that remove leaves in place. */
204
+ localisationKept: missingListSchema,
205
+ })
206
+ .strict();
@@ -13,7 +13,11 @@ export const decisionWriteRequestSchema = z
13
13
  /** add only: create the file named by file when the mod has no such common/decisions file. */
14
14
  createFile: z.boolean().optional(),
15
15
  /** The text between the decision braces. Required by add and replace, refused by remove. */
16
- body: z.string().max(32_000).optional(),
16
+ body: z
17
+ .string()
18
+ .max(32_000)
19
+ .optional()
20
+ .describe('Only the text between the decision braces, not the whole decision_id = {...} block.'),
17
21
  /** The common/decisions file. Omit it for replace and remove, and for an add into a category that one file defines. */
18
22
  file: workspaceRelativePathSchema.max(512).optional(),
19
23
  apply: z
@@ -12,7 +12,11 @@ export const doctrineWriteRequestSchema = z
12
12
  /** add only: create the file named by file when the mod has no such doctrine file. */
13
13
  createFile: z.boolean().optional(),
14
14
  /** The text between the doctrine braces. Required by add and replace, refused by remove. */
15
- body: z.string().max(32_000).optional(),
15
+ body: z
16
+ .string()
17
+ .max(32_000)
18
+ .optional()
19
+ .describe('Only the text between the doctrine braces, not the whole doctrine_id = {...} block.'),
16
20
  /** The doctrine file under common/doctrines/grand_doctrines, tracks or subdoctrines. Omit it for replace and remove, and for an add when the mod has one file of that kind. */
17
21
  file: workspaceRelativePathSchema.max(512).optional(),
18
22
  apply: z
@@ -22,7 +22,11 @@ export const eventWriteRequestSchema = z
22
22
  /** add only: create the file named by file when the mod has no such events file. */
23
23
  createFile: z.boolean().optional(),
24
24
  /** The text between the event braces, without the id line. Required by add and replace, refused by remove. */
25
- body: z.string().max(32_000).optional(),
25
+ body: z
26
+ .string()
27
+ .max(32_000)
28
+ .optional()
29
+ .describe('Only the text between the event braces (title, desc, option = {...}), without id; not a country_event = {...} block.'),
26
30
  /** The events file. Omit it for replace and remove, and for an add when one file holds the namespace. */
27
31
  file: workspaceRelativePathSchema.max(512).optional(),
28
32
  apply: z
@@ -13,7 +13,11 @@ export const ideaWriteRequestSchema = z
13
13
  /** add only: create the file named by file when the mod has no such common/ideas file. */
14
14
  createFile: z.boolean().optional(),
15
15
  /** The text between the idea braces. Required by add and replace, refused by remove. */
16
- body: z.string().max(32_000).optional(),
16
+ body: z
17
+ .string()
18
+ .max(32_000)
19
+ .optional()
20
+ .describe('Only the text between the idea braces, not the whole idea_id = {...} block.'),
17
21
  /** The common/ideas file. Omit it for replace and remove, and for an add into a category that one file defines. */
18
22
  file: workspaceRelativePathSchema.max(512).optional(),
19
23
  apply: z
@@ -0,0 +1,129 @@
1
+ import { z } from 'zod/v4';
2
+ import { workspaceRelativePathSchema } from './common.js';
3
+ import { geographyModelSchema, geographyPathSchema } from './geography.js';
4
+ /**
5
+ * `add_landmass` (packet T4): one island with relief in open sea on the existing map. The engine
6
+ * (`map.add_landmass`) plans every file; the map rewrite validates and writes them as one
7
+ * transaction. The island always gets its own strategic region and never changes an existing
8
+ * one (issue 223).
9
+ */
10
+ const pixel = z.number().int().min(0).max(16_383);
11
+ const provinceId = z.number().int().min(1).max(65_535);
12
+ const countryTag = z.string().regex(/^[A-Z][A-Z0-9]{2}$/u);
13
+ const nameText = z.string().min(1).max(80);
14
+ export const addLandmassOperationSchema = z
15
+ .object({
16
+ id: z.string().min(1).max(256),
17
+ summary: z.string().max(1000).optional(),
18
+ kind: z.literal('add_landmass'),
19
+ geography: geographyModelSchema
20
+ .optional()
21
+ .describe('Geography model version 1 on the map frame (0..1 of provinces.bmp): exactly one land, the island, plus its ranges, passes, volcanoes, plateaus, rivers and lakes. Seas, regions, biomes, climate, straits, sites, roads and places are refused (MAP_LANDMASS_UNREPRESENTABLE). With maskImage, declare no land. Give exactly one of geography and geographyPath.'),
22
+ geographyPath: geographyPathSchema
23
+ .optional()
24
+ .describe('Workspace-relative .json geography model; give exactly one of geography and geographyPath.'),
25
+ maskImage: z
26
+ .object({
27
+ path: workspaceRelativePathSchema.describe('Workspace-relative PNG, TGA, DDS or BMP: every pixel that is neither black nor fully transparent is land.'),
28
+ x: pixel.describe('Map pixel of the image left edge.'),
29
+ y: pixel.describe('Map pixel of the image top edge.'),
30
+ })
31
+ .strict()
32
+ .optional()
33
+ .describe('A drawn island outline instead of the geography land polygon.'),
34
+ seed: z.number().int().min(0).max(2_147_483_647).default(1),
35
+ relief: z
36
+ .object({
37
+ scale: z.enum(['vanilla', 'low', 'dramatic']).optional(),
38
+ detail: z.number().min(0).max(1).optional(),
39
+ })
40
+ .strict()
41
+ .optional(),
42
+ rivers: z
43
+ .object({
44
+ density: z.number().min(0).max(0.04).optional(),
45
+ count: z.number().int().min(0).max(500).optional(),
46
+ })
47
+ .strict()
48
+ .optional(),
49
+ provinces: z
50
+ .object({
51
+ landProvincePixels: z
52
+ .number()
53
+ .min(20)
54
+ .max(1_000_000)
55
+ .optional()
56
+ .describe('Target land province size in pixels; default the mean land province of the map.'),
57
+ })
58
+ .strict()
59
+ .optional(),
60
+ continent: z
61
+ .string()
62
+ .min(1)
63
+ .max(128)
64
+ .optional()
65
+ .describe('Continent from continent.txt; default the continent of the nearest land province.'),
66
+ states: z
67
+ .object({
68
+ provincesPerState: z.number().int().min(1).max(500).optional(),
69
+ owner: countryTag.optional().describe('Owner and core holder; the tag must exist.'),
70
+ category: z.string().min(1).max(128).optional(),
71
+ manpower: z.number().min(0).max(1e9).optional(),
72
+ buildings: z.record(z.string().min(1).max(128), z.number().min(0).max(1e6)).optional(),
73
+ capitalVictoryPoints: z.number().min(0).max(1000).optional(),
74
+ names: z
75
+ .array(nameText)
76
+ .max(1000)
77
+ .optional()
78
+ .describe('English state names in state order; default the region name, numbered.'),
79
+ })
80
+ .strict()
81
+ .default({}),
82
+ region: z
83
+ .object({
84
+ name: nameText.optional().describe('English region name; default Island.'),
85
+ weatherFromRegion: z.number().int().min(1).optional(),
86
+ })
87
+ .strict()
88
+ .default({}),
89
+ supply: z
90
+ .object({
91
+ nodes: z.boolean().default(false),
92
+ railways: z.boolean().default(false),
93
+ railwayLevel: z.number().int().min(1).max(5).optional(),
94
+ })
95
+ .strict()
96
+ .optional(),
97
+ crossings: z
98
+ .array(z
99
+ .object({
100
+ fromX: pixel,
101
+ fromY: pixel,
102
+ toProvince: provinceId,
103
+ throughProvince: provinceId,
104
+ rule: z.string().min(1).max(128).optional(),
105
+ })
106
+ .strict())
107
+ .max(100)
108
+ .default([]),
109
+ look: z.enum(['vanilla-temperate', 'fertile', 'arid']).optional(),
110
+ absorbCoveredSeaProvinces: z
111
+ .boolean()
112
+ .optional()
113
+ .describe('Opt-in, off by default. A sea province the island covers whole becomes one of its land provinces, keeping its id and colour, in the island’s new strategic region; its old region file loses that id. Refused when anything uses it as sea (adjacencies, supply nodes, railways, naval building positions, states, fleets or other script references: MAP_LANDMASS_SEA_REFERENCED, each listed), when its old region would be empty (MAP_LANDMASS_REGION_EMPTY) or split (MAP_LANDMASS_REGION_SPLIT). Without it, a covered sea province is refused (MAP_LANDMASS_SEA_SPLIT).'),
114
+ localisation: z
115
+ .object({
116
+ file: z
117
+ .string()
118
+ .min(1)
119
+ .max(1000)
120
+ .optional()
121
+ .describe('English localisation file for the state, victory point and region names (STATE_<id>, VICTORY_POINTS_<province>, STRATEGICREGION_<id>); default localisation/english/map_landmass_<id>_l_english.yml.'),
122
+ })
123
+ .strict()
124
+ .optional(),
125
+ })
126
+ .strict()
127
+ .refine((value) => (value.geography === undefined) !== (value.geographyPath === undefined), {
128
+ message: 'Give exactly one of geography and geographyPath',
129
+ });
@@ -27,7 +27,8 @@ export const localisationEntrySchema = z
27
27
  .max(2000)
28
28
  .refine((value) => !FORBIDDEN_TEXT.test(value), {
29
29
  message: 'text must be one line; write a line break as \\n',
30
- }),
30
+ })
31
+ .describe('The value only, without the key and the surrounding quotes.'),
31
32
  })
32
33
  .strict();
33
34
  export const localisationWriteRequestSchema = z
@@ -70,6 +71,14 @@ export const localisationWriteRequestSchema = z
70
71
  message: `${entry.key} appears twice in entries`,
71
72
  });
72
73
  seen.add(entry.key);
74
+ // A whole line of the file in text would be written inside a second pair of quotes.
75
+ const line = /^\s*([A-Za-z0-9_.-]+):[0-9]*\s*".*"\s*$/u.exec(entry.text);
76
+ if (line?.[1] === entry.key)
77
+ context.addIssue({
78
+ code: 'custom',
79
+ path: ['entries', index, 'text'],
80
+ message: `text is a whole localisation line; pass only what is between the quotes of ${entry.key}`,
81
+ });
73
82
  }
74
83
  }
75
84
  if (value.paths !== undefined)
@@ -199,7 +199,7 @@ export const mapRewriteRequestSchema = z
199
199
  .string()
200
200
  .regex(MAP_BASELINE_FINGERPRINT_PATTERN)
201
201
  .optional()
202
- .describe('Opt-in: baselineFingerprint from a full hoi4.map_inspect of the untouched map. Pre-existing errors outside the write stop blocking; a changed map is refused.'),
202
+ .describe('Use when the map already has many validation errors (a new mod on the vanilla map): baselineFingerprint from a full hoi4.map_inspect of the untouched map. Pre-existing errors outside the write stop blocking; a changed map is refused.'),
203
203
  requestKey: backgroundRequestKeySchema.optional(),
204
204
  })
205
205
  .strict();
@@ -3,6 +3,7 @@ import { renderDimensionViolation, RENDER_MAX_DIMENSION } from '../core/render-b
3
3
  import { MAP_MASK_CELL_LIMIT, MAP_SELECTED_PIXEL_LIMIT, NATURAL_LAND_ID_PATTERN, NATURAL_TERRAIN_CLASSES, } from '../map/limits.js';
4
4
  import { workspaceRelativePathSchema } from './common.js';
5
5
  import { geographyModelSchema, geographyPathSchema } from './geography.js';
6
+ import { addLandmassOperationSchema } from './landmass.js';
6
7
  import { referenceSheetsDocumentSchema, referenceSheetsPathSchema } from './reference-sheets.js';
7
8
  const identifier = z.string().min(1).max(256);
8
9
  // eslint-disable-next-line no-control-regex -- portable JSON Schema pattern rejects grammar-breaking controls.
@@ -1468,6 +1469,7 @@ export const mapOperationSchema = z.discriminatedUnion('kind', [
1468
1469
  position: z.tuple([z.number(), z.number(), z.number()]),
1469
1470
  })
1470
1471
  .strict(),
1472
+ addLandmassOperationSchema,
1471
1473
  ]);
1472
1474
  export const mapAllocationRequestSchema = z.discriminatedUnion('kind', [
1473
1475
  z.object({ kind: z.literal('state'), requestedId: stateId.optional() }).strict(),