hoi4-agent-tools 4.20.3 → 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 (140) hide show
  1. package/CHANGELOG.md +40 -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/characters/write-operations.js +2 -2
  6. package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
  7. package/dist/hoi4_agent_tools/common-write/documented-lists.js +62 -0
  8. package/dist/hoi4_agent_tools/common-write/limits.js +35 -0
  9. package/dist/hoi4_agent_tools/common-write/paths.js +17 -0
  10. package/dist/hoi4_agent_tools/common-write/write-job-operations.js +42 -0
  11. package/dist/hoi4_agent_tools/common-write/write-operations.js +360 -0
  12. package/dist/hoi4_agent_tools/common-write/write-plan.js +34 -0
  13. package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
  14. package/dist/hoi4_agent_tools/core/configuration.js +6 -0
  15. package/dist/hoi4_agent_tools/core/domain-tools.js +8 -0
  16. package/dist/hoi4_agent_tools/core/engine.js +67 -21
  17. package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
  18. package/dist/hoi4_agent_tools/core/job-controls.js +12 -2
  19. package/dist/hoi4_agent_tools/core/job-executor.js +8 -7
  20. package/dist/hoi4_agent_tools/core/job-operation-registration.js +4 -0
  21. package/dist/hoi4_agent_tools/core/job-store.js +97 -5
  22. package/dist/hoi4_agent_tools/core/job-worker-host.js +2 -2
  23. package/dist/hoi4_agent_tools/core/operation-result.js +118 -33
  24. package/dist/hoi4_agent_tools/core/operation-tasks.js +4 -2
  25. package/dist/hoi4_agent_tools/core/transactions.js +6 -0
  26. package/dist/hoi4_agent_tools/core/workspace.js +25 -2
  27. package/dist/hoi4_agent_tools/country/job-operations.js +42 -0
  28. package/dist/hoi4_agent_tools/country/write-operations.js +646 -0
  29. package/dist/hoi4_agent_tools/country/write-plan.js +28 -0
  30. package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
  31. package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
  32. package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
  33. package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
  34. package/dist/hoi4_agent_tools/event/graph.js +3 -3
  35. package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
  36. package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
  37. package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
  38. package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
  39. package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
  40. package/dist/hoi4_agent_tools/gui/assets.js +3 -13
  41. package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
  42. package/dist/hoi4_agent_tools/gui/layout.js +2 -4
  43. package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
  44. package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
  45. package/dist/hoi4_agent_tools/gui/studio.js +31 -0
  46. package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
  47. package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
  48. package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
  49. package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
  50. package/dist/hoi4_agent_tools/map/landmass-source.js +42 -0
  51. package/dist/hoi4_agent_tools/map/landmass.js +190 -0
  52. package/dist/hoi4_agent_tools/map/model.js +17 -3
  53. package/dist/hoi4_agent_tools/map/operations.js +20 -6
  54. package/dist/hoi4_agent_tools/map/references.js +6 -3
  55. package/dist/hoi4_agent_tools/map/service.js +88 -8
  56. package/dist/hoi4_agent_tools/map/validation.js +12 -18
  57. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  58. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  59. package/dist/hoi4_agent_tools/mcp/server/create.js +4 -0
  60. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +4 -0
  61. package/dist/hoi4_agent_tools/mcp/tools/common-write.js +21 -0
  62. package/dist/hoi4_agent_tools/mcp/tools/country-write.js +21 -0
  63. package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -1
  64. package/dist/hoi4_agent_tools/mcp/transports/http.js +2 -0
  65. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
  66. package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
  67. package/dist/hoi4_agent_tools/runtime.js +83 -3
  68. package/dist/hoi4_agent_tools/schemas/character-write.js +5 -1
  69. package/dist/hoi4_agent_tools/schemas/common-write.js +74 -0
  70. package/dist/hoi4_agent_tools/schemas/country-write.js +206 -0
  71. package/dist/hoi4_agent_tools/schemas/decision-write.js +5 -1
  72. package/dist/hoi4_agent_tools/schemas/doctrine-write.js +5 -1
  73. package/dist/hoi4_agent_tools/schemas/event-write.js +5 -1
  74. package/dist/hoi4_agent_tools/schemas/idea-write.js +5 -1
  75. package/dist/hoi4_agent_tools/schemas/landmass.js +129 -0
  76. package/dist/hoi4_agent_tools/schemas/localisation-write.js +10 -1
  77. package/dist/hoi4_agent_tools/schemas/map-requests.js +1 -1
  78. package/dist/hoi4_agent_tools/schemas/map.js +2 -0
  79. package/dist/hoi4_agent_tools/schemas/tech-write.js +5 -1
  80. package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
  81. package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
  82. package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
  83. package/dist/hoi4_agent_tools/technology/operations.js +1 -2
  84. package/dist/hoi4_agent_tools/technology/service.js +30 -59
  85. package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
  86. package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
  87. package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
  88. package/dist/hoi4_agent_tools/version.js +1 -1
  89. package/docs/configuration.md +11 -10
  90. package/docs/jobs.md +2 -2
  91. package/docs/setup.md +1 -0
  92. package/docs/tools.md +16 -2
  93. package/docs/troubleshooting.md +11 -11
  94. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  95. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  96. package/engine/bin/linux-x64/hoi4-engine +0 -0
  97. package/engine/bin/manifest.json +8 -8
  98. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  99. package/npm-shrinkwrap.json +43 -19
  100. package/package.json +2 -2
  101. package/schemas/configuration.schema.json +143 -134
  102. package/schemas/continuous-focus-palette.schema.json +1 -1
  103. package/schemas/custom-weighted-pool.schema.json +1 -1
  104. package/schemas/decision-inspect-input.schema.json +1 -1
  105. package/schemas/error-log-input.schema.json +1 -1
  106. package/schemas/event-feature-manifest.schema.json +1 -1
  107. package/schemas/focus-plan.schema.json +1 -1
  108. package/schemas/focus-planning-sidecar.schema.json +1 -1
  109. package/schemas/geography-model.schema.json +1 -1
  110. package/schemas/gui-animation-source.schema.json +1 -1
  111. package/schemas/gui-helper.schema.json +1 -1
  112. package/schemas/gui-scenario.schema.json +1 -1
  113. package/schemas/helper-expansion-request.schema.json +1 -1
  114. package/schemas/helper-expansion-summary.schema.json +1 -1
  115. package/schemas/impact-inspect-input.schema.json +1 -1
  116. package/schemas/map-operation.schema.json +354 -1
  117. package/schemas/mechanic-test-input.schema.json +1 -1
  118. package/schemas/mod-index-input.schema.json +1 -1
  119. package/schemas/operation-result.schema.json +1 -1
  120. package/schemas/package-check-input.schema.json +1 -1
  121. package/schemas/package-manifest.schema.json +1 -1
  122. package/schemas/probability-analysis-result.schema.json +1 -1
  123. package/schemas/probability-compare-input.schema.json +1 -1
  124. package/schemas/probability-evaluate-input.schema.json +1 -1
  125. package/schemas/probability-inspect-input.schema.json +1 -1
  126. package/schemas/probability-render-input.schema.json +1 -1
  127. package/schemas/probability-scenario-set.schema.json +1 -1
  128. package/schemas/probability-sequence-input.schema.json +1 -1
  129. package/schemas/probability-simulate-input.schema.json +1 -1
  130. package/schemas/probability-sweep-input.schema.json +1 -1
  131. package/schemas/reference-context-input.schema.json +1 -1
  132. package/schemas/reference-read-input.schema.json +1 -1
  133. package/schemas/reference-search-input.schema.json +1 -1
  134. package/schemas/reference-sheets.schema.json +1 -1
  135. package/schemas/scenario-suite.schema.json +1 -1
  136. package/schemas/scenario-test-input.schema.json +1 -1
  137. package/schemas/script-validate-input.schema.json +1 -1
  138. package/schemas/shared-scenario.schema.json +1 -1
  139. package/schemas/source-lookup-input.schema.json +1 -1
  140. package/server.json +2 -2
package/CHANGELOG.md CHANGED
@@ -2,6 +2,46 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 4.22.0 - 2026-12-04
6
+
7
+ - Updated `cross-spawn`, `@hono/node-server`, `glob` and other locked dependencies to fixed versions, so the `npm audit --omit=dev --audit-level=high` gate passes again (critical cross-spawn advisories GHSA-ghv9-86vm-4v8m and GHSA-m6qr-m48x-3xhh).
8
+ - Added `hoi4.country_write` (advanced profile): add, update or remove one country of the mod in one journaled write. It covers the tag line in the mod's `common/country_tags` file, the `common/countries` file (both graphical cultures and the map colour), the `colors.txt` entry, the `history/countries` file (capital, politics, popularities, research slots, stability, war support, technology, `oob` and `recruit_character`), the names in localisation (`<TAG>`, `<TAG>_ADJ`, `<TAG>_DEF` and per ideology) and, when asked, an entry in a named bookmark or a new bookmark. `apply: false` returns the diffs. A new tag must be an upper-case letter and two upper-case letters or digits; it is refused when it exists, is a dynamic name (`D00` to `D99`), a Windows device name or a three-letter effect or trigger name from the game documentation, and the refusal lists them. An unknown capital state, graphical culture or ideology is refused, and so is a removal while other mod files still name the tag (with the lines). When the mod has no `colors.txt` or edits a bookmark of the game, it gets a copy of the active file with the change, so the other entries stay. Missing flags, characters, order of battle files and text are warnings and the write still happens; the tool never draws flags. The edits are planned in the Rust engine (`country_write.plan`), whose new-file text is `create_world`'s, byte for byte, and whose shared history edit (`set_top_level_scalar`) matches keys in any ASCII case.
9
+ - Fixed tools that run as jobs (every `*_write` tool and the other background operations) dropping a refusal's `details`: a failed job now keeps the refusal's public details, bounded to 64 KiB of canonical JSON (larger details become `{ truncated: true, originalBytes, maximumBytes, omittedKeyCount, omittedKeys, details }`), and returns them unchanged in the tool answer, the task result and `hoi4.job_inspect`, whose output gains an optional `failure.details` (#327).
10
+ - Fixed `hoi4.map_rewrite` on a map that already has more validation errors than the review limit (a new mod on the vanilla map): the `REWRITE_STRUCTURE_LIMIT` refusal now carries a `remedy` detail naming a full `hoi4.map_inspect` and its `baselineFingerprint`, passed back as `baselineFingerprint`, and the field's description says when to use it. The detail is added only when the diagnostics limit was hit and the call stated no fingerprint (and no `create_world`); the code is unchanged, and failed jobs keep the detail.
11
+ - `hoi4.map_rewrite` has a new operation, `add_landmass`: it adds one island with relief to an existing map, in open sea. The island comes from a geography model on the map's frame (one land plus its ranges, passes, volcanoes, plateaus, rivers and lakes) or from a drawn mask image. One operation writes:
12
+ - its land and lake provinces, in `provinces.bmp` and `definition.csv`;
13
+ - the heightmap, rivers, terrain, trees and normal map;
14
+ - the land and water colour maps;
15
+ - its states (optionally owned by an existing country);
16
+ - its own new strategic region, with weather;
17
+ - building, unit and weather positions, and supply nodes and railways when asked;
18
+ - sea crossings when asked.
19
+
20
+ By default the island never changes an existing strategic region (issue 223). With the opt-in `absorbCoveredSeaProvinces`, a sea province the island covers whole becomes its land: it keeps its id and colour, and leaves its old region, which must stay non-empty and connected. The opt-in is refused, with each reference listed, when anything uses that province as sea: adjacencies, supply nodes, railways, naval building positions, states, the `sea_starts` and `lakes` of `default.map`, fleets, or any event, focus, decision or other `common/` script. A province name written for the sea gives a warning. Every sea province it takes pixels from keeps its id, its region and one connected piece, and becomes coastal where it now touches land. The write is refused with a named reason when the mask lies over or beside land, reaches the map edge, is not one piece, would empty or split a sea province, has a lake on its coast, exceeds the province id limit, or names an unknown owner, continent, state category or region. The map rewrite then validates the whole map against its baseline and blocks any new error-level finding, as for every map operation. The island is planned on the shared Rust engine (`map.add_landmass`); the relief, river, terrain and province synthesis of `create_world` is ported there for it and reused unchanged. Public schema addition: a new `add_landmass` member of the map operation schema.
21
+
22
+ - Fixed refusal details stored in job records and shown in tool answers being filtered by a top-level deny-list only: the filter now works at any depth (nested denied keys removed, absolute host paths in text reduced to their last segment, cyclic or too deep details replaced by a marker) (#332).
23
+ - The stdio server now also serves its working folder as an extra workspace when that folder is itself a mod (`descriptor.mod` and the usual mod detection) outside the configured `modRoots` and workspaces; configured ones are unchanged, the configuration file is never written, and a working folder inside a configured root adds nothing (#333, D-176).
24
+ - New `hoi4.common_write` (advanced profile): add, replace or remove one balance of power, AI strategy, AI strategy plan or on_action in the mod's own `common/` files, touching only that block, from raw script bodies that must parse and are written as given. It is one descriptor-driven engine operation (`common.block_write`), so a further kind is a descriptor, not new code. A balance of power whose ranges do not cover -1 to 1 once, or whose sides do not match, is refused; an unknown strategy type, a missing abort, or a missing localisation key, sprite, category or focus is a warning; an on_action name the documentation does not list (and that is not `on_daily_TAG`, `on_weekly_TAG` or `on_monthly_TAG`) is refused with the documented names. on_action blocks merge by key: add appends to the key's block, and `blockIndex` replaces or removes one child block.
25
+
26
+ - Fixed `hoi4.event_write` writing a broken event, reported as applied and passing validation, when `body` was a whole `country_event = { ... }` block (or another event kind): the file got an event nested inside the event. The call is now refused with `EVENT_WRITE_BODY_INVALID`, which says to pass only the text between the braces. `hoi4.decision_write`, `hoi4.idea_write`, `hoi4.character_write`, `hoi4.tech_write`, `hoi4.doctrine_write` and `hoi4.common_write` refuse a body that is the whole definition (`id = { ... }`, with or without the block it sits in) the same way, `hoi4.localisation_write` refuses a `text` that is a whole `key: "..."` line, and the `body` and `text` inputs are now described in the tool schemas.
27
+
28
+ - Clarified that the entries printed by `hoi4-agent-tools-setup --print-client-config` list only the core tools: the output now has a `toolProfiles` line, and the README quick start and the setup guide say how to list every tool with `HOI4_AGENT_TOOLS_PROFILES=all`.
29
+
30
+ ## 4.21.0 - 2026-11-28
31
+
32
+ - Fixed `hoi4.gui_inspect` and `hoi4.gui_render` reporting false unresolved references: a sprite or font of another window in the inspected window's `.gui` file, or one a kept script names, now resolves from its `.gfx` file in the game or the mod instead of being reported as missing because that file was left out of the window graph, and a static GUI text that is not in the form of a localisation key (such as `Title text here!` or `--`) is drawn as written, as the game does, instead of being reported as a missing key. A missing sprite and a missing key in key form are still reported.
33
+ - Fixed `hoi4.gui_render` drawing a masked flag shield (a `maskedShieldType` sprite such as the base game's small flag) as its overlay only, with no flag colours. The mask was applied by brightness when its alpha was uniform, so the game's black, fully opaque mask cut the whole flag away. The renderer now uses only the mask's alpha, as the game's masked flag shader does.
34
+ - The idle release of a server's in-memory analysis caches is now a setting, `idleCacheReleaseSeconds` (issue 296). The scan, index and view caches were already released 30 s after the last tool call, but the 30 s was fixed and undocumented. The default stays 30; `0` releases the caches as soon as a call ends, and the maximum is 3,600. It is listed in the configuration table and in `configuration.schema.json`.
35
+ - The idea, character, decision, doctrine, technology and event writers now plan their edits in the Rust engine (`hoi4-script-write`, packet P10 of ADR 0089). Each is one engine operation, `<writer>_write.plan`, that reads the source bytes it is given and answers with the edit and the bytes of the file after it; it never writes. The tools, their inputs, results, codes and messages are unchanged, and a missing engine is `ENGINE_UNAVAILABLE`. The localisation writer is still on the TypeScript path.
36
+ - Map validation (the checks before and after every map rewrite, and the map validation itself) now runs on the shared Rust engine (`hoi4-map`, ADR 0089 step 6). The engine reads each scanned file by path and refuses one whose size or SHA-256 changed since the scan, and a map whose in-memory files exceed one request is refused with `MAP_ENGINE_PAYLOAD_LIMIT` instead of being validated in part. On seven large maps the findings, their order, `passed` and every check match the earlier TypeScript checks exactly. Building and position records have their own 2,000,000-record ceiling, so a mod with very large position tables is no longer refused (issue 172).
37
+ - The artifact store, unified and binary diffs, the changed-files summary, managed output inventories, the offline PNG comparison and the scratch-directory sweep now exist in the Rust engine (`hoi4-artifacts`, packet P3 of ADR 0089), reachable as the `artifacts.*` and `diff.*` operations. Store layout, names, manifests, URIs, limits, pruning and error codes are the TypeScript ones, so both servers read each other's stores. The text diff is byte-equal to the TypeScript one. The managed-output planner takes its path predicates as data (`PathRule`) instead of functions. The Node server does not call them yet.
38
+ - The minimum Rust version of the engine workspace is now 1.89, for std `File::lock` (the artifact publish lock). The pinned toolchain stays 1.97.1.
39
+ - The engine's artifact store keeps a claim for every put on disk, under its publication lock, until the caller commits (`artifacts.commit`) or releases it, so a rollback or eviction in one engine process never removes what another process reused or has not yet committed; claims expire after ten minutes. A put's stale list of pins is refused after a commit (`retentionEpoch`). `diff.text` carries both texts and the diff as payload, and engine errors carry their fields at the top level like the other operations. Process liveness, file identity and the host name come from the new `hoi4-os` crate, the only crate that may use `unsafe`.
40
+ - `hoi4.tech_inspect` builds its technology graph and answers the modes scan, folders, trace, explain, unlocks, bonus_coverage, lint and impact on the Rust engine (`tech.analyze`, `tech.graph`, `tech.query`), with the same wire shapes, codes and messages; a missing engine is `ENGINE_UNAVAILABLE`. Render, compare and helper_expansion still use the TypeScript analysis until the artifact store and GUI packets land.
41
+ - The Rust `hoi4-event` crate gains the event analysis as engine operations: `event.fragments` (source files to their nodes, edges, state accesses and findings), `event.graph` (the semantic graph with helper projections, state links and findings, built from fragments or straight from files the engine reads itself by path and refuses when they changed since the scan) and the graph algorithms `event.trace`, `event.path`, `event.components` and `event.reachable`. The TypeScript server does not call them yet, so no tool changes behavior. A parity script (`scripts/event-parity.ts`) compares each operation with the TypeScript implementation.
42
+ - An idle stdio server no longer loads or recovers any workspace (issues 292 and 296). Since the handshake fix it still loaded every mod and recovered every workspace's journals in the background right after `initialize`, which is why idle servers held 386 to 669 MB of private memory with a configuration, against about 110 MB without one. Now `initialize`, `tools/list` and `prompts/list` start nothing. The first tool call, resource read or other request that needs a workspace loads the workspaces, and each workspace's interrupted rewrite is recovered once on that workspace's first use: before its first file access through the resolver, before its first job is submitted and before its first rewrite is planned or applied. A failed recovery is still recorded with the `transaction_recovery_blocked` event, reads go on, and rewrites of that workspace are refused with `TRANSACTION_RECOVERY_REQUIRED`, as before. Releasing a workspace's caches after an idle period is not part of this change and stays with issue 296.
43
+ - The shared Rust engine now has the atomic rewrite engine (`hoi4-txn`, packet P2 of ADR 0091), with the engine operations `txn.apply` and `txn.recover`. It writes a rewrite plan whole or refuses it: paths go through the engine's one path resolver, duplicates and aliases are refused, sources are checked against the hashes their writer read under the workspace lock, and the before and after bytes are journaled in the TypeScript journal format, authenticated with the server's journal key and recorded as protected heads. Each file is replaced by rename after a write-ahead intent per batch, the written bytes are verified, and a failure restores every file without overwriting bytes the rewrite did not produce. Interrupted rewrites are recovered before the next one, and either server recovers the other's journal. A rollback that has to refuse removes the backups of files still holding its result and names the rest, as the TypeScript manager does since 4.20.1. The TypeScript transaction manager still serves every rewrite tool until the writers move onto the engine; nothing changes for agents yet.
44
+
5
45
  ## 4.20.3 - 2026-11-27
6
46
 
7
47
  - Fixed recovery of an interrupted rewrite of more than 1,024 files, which failed with `TRANSACTION_MANIFEST_INVALID` and blocked rewrites of that workspace. Such rewrites replace files in batches of up to 256, but the journal check accepted at most 16 pending files per batch.
package/README.md CHANGED
@@ -57,6 +57,8 @@ You describe what you want; the agent picks the right tools.
57
57
 
58
58
  Paste the `globalInstall` block into a JSON client such as Claude Code, Claude Desktop or Cursor, or the `codexTomlGlobal` block into Codex's `config.toml`.
59
59
 
60
+ As printed, the entry lists the 13 core tools (documentation, script checks, localisation and skills). For all 45 tools, including the focus, event, GUI, technology and map editors, add `"env": { "HOI4_AGENT_TOOLS_PROFILES": "all" }` to the JSON server entry, or `HOI4_AGENT_TOOLS_PROFILES = "all"` inside the Codex `env` table ([tool profiles](docs/setup.md#choose-tool-profiles)).
61
+
60
62
  4. Open your mod folder as the agent's workspace and tell it what you want to build or fix.
61
63
 
62
64
  The [setup guide](docs/setup.md) covers several mods, explicit game paths, local wiki snapshots and troubleshooting with `--discover` and `--diagnose`.
package/dist/bin/setup.js CHANGED
@@ -266,6 +266,7 @@ function printClientConfig(configPath) {
266
266
  const globalToml = `[mcp_servers.hoi4_agent_tools]\ncommand = "${installedCommand}"${codexEnv}`;
267
267
  process.stdout.write(`${JSON.stringify({
268
268
  note: 'Review and paste one example into your MCP client; this utility does not edit client settings.',
269
+ toolProfiles: 'As printed, an entry lists only the core tools. To list every tool, add HOI4_AGENT_TOOLS_PROFILES=all to the env of the server entry; see docs/setup.md, Choose tool profiles.',
269
270
  generic: { mcpServers: { hoi4_agent_tools: common } },
270
271
  globalInstall: { mcpServers: { hoi4_agent_tools: installed } },
271
272
  codexToml: npxToml,
package/dist/bin/stdio.js CHANGED
@@ -31,6 +31,7 @@ async function main() {
31
31
  const engine = await createEngine(undefined, {
32
32
  workspaces: 'background',
33
33
  defaultProfiles: DEFAULT_PROFILES,
34
+ workingFolderMod: true,
34
35
  });
35
36
  // Plugins load only from the paths the server configuration lists (M-14).
36
37
  const plugins = await loadPlugins(engine.resolver.config().plugins, PACKAGE_VERSION, (file, reason) => process.stderr.write(`${canonicalJson({ level: 'warn', event: 'plugin_skipped', plugin: path.basename(file), reason })}\n`));
@@ -117,7 +117,7 @@ export async function computeCharacterWrite(engine, input, context, applied) {
117
117
  let plan;
118
118
  if ('file' in target) {
119
119
  file = target.file;
120
- plan = planCharacterWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
120
+ plan = await planCharacterWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
121
121
  }
122
122
  else {
123
123
  const inMod = snapshot.index
@@ -128,7 +128,7 @@ export async function computeCharacterWrite(engine, input, context, applied) {
128
128
  id: input.id,
129
129
  path: inMod.path,
130
130
  });
131
- plan = planNewCharacterFile(target.newPath, planInput);
131
+ plan = await planNewCharacterFile(target.newPath, planInput);
132
132
  }
133
133
  const missing = { localisation: [], portrait: [] };
134
134
  const diagnostics = [];
@@ -1,210 +1,26 @@
1
- import { indentedBody, lineIndent } from '../core/block-edit.js';
2
- import { hasBlockingDiagnostics } from '../core/diagnostics.js';
3
- import { DIFF_CONTEXT_LINES, unifiedTextDiff } from '../core/diff.js';
4
- import { ServiceError } from '../core/result.js';
5
- import { applyReplacements, assignments, parseClausewitz, } from '../core/source/index.js';
6
- const ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]*$/u;
7
- function fail(code, message, details) {
8
- throw new ServiceError(code, message, details);
9
- }
10
- /** Every `characters = { <id> = { ... } }` definition of the document. */
11
- function definitions(document) {
12
- return assignments(document.root, 'characters').flatMap((characters) => characters.value.type === 'block'
13
- ? assignments(characters.value).filter(({ value }) => value.type === 'block')
14
- : []);
15
- }
16
- /** One level of indentation, read from the file's own characters, tabs when it has none. */
17
- function indentUnit(document) {
18
- for (const characters of assignments(document.root, 'characters')) {
19
- if (characters.value.type !== 'block')
20
- continue;
21
- const outer = lineIndent(document.text, characters.start);
22
- for (const character of assignments(characters.value)) {
23
- const inner = lineIndent(document.text, character.start);
24
- if (inner.length > outer.length && inner.startsWith(outer))
25
- return inner.slice(outer.length);
26
- }
27
- }
28
- return '\t';
29
- }
30
- /** The body, checked on its own as the block it will become. */
31
- function assertBodyIsOneBlock(id, body) {
32
- const probe = parseClausewitz(Buffer.from(`${id} = {\n${body}\n}\n`, 'utf8'), 'character-body');
33
- const only = probe.root.entries;
34
- const single = only.length === 1 && only[0]?.type === 'assignment' && only[0].key.value === id;
35
- if (hasBlockingDiagnostics(probe.diagnostics) || !single || only[0]?.type !== 'assignment')
36
- fail('CHARACTER_WRITE_BODY_INVALID', 'The body must be the text between the braces of one character: balanced braces and no definition of its own', { diagnosticCodes: probe.diagnostics.map(({ code }) => code) });
37
- if (only[0].value.type !== 'block' || only[0].value.entries.length === 0)
38
- fail('CHARACTER_WRITE_BODY_INVALID', 'The body of a character cannot be empty');
39
- }
40
- function definitionTexts(document, skip) {
41
- const byKey = new Map();
42
- for (const character of definitions(document)) {
43
- if (character.start === skip?.start)
44
- continue;
45
- const key = character.key.value;
46
- byKey.set(key, [
47
- ...(byKey.get(key) ?? []),
48
- document.text.slice(character.start, character.end),
49
- ]);
50
- }
51
- return byKey;
52
- }
53
- function checkRequest(input) {
54
- if (!ID_PATTERN.test(input.id))
55
- fail('CHARACTER_WRITE_ID_INVALID', `${JSON.stringify(input.id)} is not a valid character id`, {
56
- id: input.id,
57
- });
58
- if (input.operation === 'remove' && input.body !== undefined)
59
- fail('CHARACTER_WRITE_BODY_UNEXPECTED', 'remove takes no body');
60
- if (input.operation !== 'remove' && (input.body === undefined || input.body.trim() === ''))
61
- fail('CHARACTER_WRITE_BODY_REQUIRED', `${input.operation} needs the body of the character`);
1
+ import { z } from 'zod/v4';
2
+ import { callWritePlan, replacementSchema, } from '../script-write/engine-plan.js';
3
+ const planSchema = z.object({
4
+ operation: z.enum(['add', 'replace', 'remove']),
5
+ id: z.string(),
6
+ path: z.string(),
7
+ edit: replacementSchema,
8
+ untouchedDefinitions: z.number().int().nonnegative(),
9
+ });
10
+ async function plan(path, input, source) {
11
+ const answer = await callWritePlan({
12
+ op: 'character_write.plan',
13
+ path,
14
+ input: { ...input },
15
+ ...(source === undefined ? {} : { source }),
16
+ result: planSchema,
17
+ });
18
+ return { ...answer.result, text: answer.text, bytes: answer.bytes, diff: answer.diff };
62
19
  }
63
- /**
64
- * The plan that creates a new `common/characters` file holding one new character, for
65
- * `createFile: true`. The file is UTF-8 without a byte order mark and uses tabs and LF, as the
66
- * game's own character files do.
67
- */
20
+ /** The plan that creates a new file holding one new character, for `createFile: true`. */
68
21
  export function planNewCharacterFile(path, input) {
69
- checkRequest(input);
70
- if (input.operation !== 'add')
71
- fail('CHARACTER_WRITE_FILE_NOT_FOUND', `${path} does not exist, and only add can create a file`);
72
- assertBodyIsOneBlock(input.id, input.body);
73
- const text = [
74
- 'characters = {',
75
- `\t${input.id} = {`,
76
- indentedBody(input.body, '\t\t', '\n'),
77
- '\t}',
78
- '}',
79
- '',
80
- ].join('\n');
81
- const written = parseClausewitz(Buffer.from(text, 'utf8'), path);
82
- if (hasBlockingDiagnostics(written.diagnostics))
83
- fail('CHARACTER_WRITE_RESULT_INVALID', 'The new file would have syntax errors', {
84
- diagnosticCodes: written.diagnostics.map(({ code }) => code),
85
- });
86
- return {
87
- operation: 'add',
88
- id: input.id,
89
- path,
90
- text,
91
- bytes: Buffer.from(text, 'utf8'),
92
- edit: { start: 0, end: 0, text, description: `create ${path} with ${input.id}` },
93
- diff: unifiedTextDiff('', text, `a/${path}`, `b/${path}`, { context: DIFF_CONTEXT_LINES }),
94
- untouchedDefinitions: 0,
95
- };
22
+ return plan(path, input, undefined);
96
23
  }
97
24
  export function planCharacterWrite(source, input) {
98
- checkRequest(input);
99
- const document = parseClausewitz(source.bytes, source.path);
100
- if (hasBlockingDiagnostics(document.diagnostics))
101
- fail('CHARACTER_WRITE_SOURCE_INVALID', 'The source has syntax errors and cannot be edited safely', { path: source.path, diagnosticCodes: document.diagnostics.map(({ code }) => code) });
102
- const text = document.text;
103
- const newline = document.newline;
104
- if (input.body !== undefined)
105
- assertBodyIsOneBlock(input.id, input.body);
106
- const unit = indentUnit(document);
107
- const existing = definitions(document).filter(({ key }) => key.value === input.id);
108
- let edit;
109
- let skip;
110
- if (input.operation === 'add') {
111
- if (existing.length > 0)
112
- fail('CHARACTER_WRITE_DUPLICATE_ID', `${input.id} is already defined in this file`, {
113
- id: input.id,
114
- line: existing[0]?.key.token.line,
115
- });
116
- const blocks = assignments(document.root, 'characters').filter(({ value }) => value.type === 'block');
117
- if (blocks.length !== 1)
118
- fail('CHARACTER_WRITE_LAYOUT_UNSUPPORTED', blocks.length === 0
119
- ? 'The file has no characters block to put the new character in'
120
- : `The file has ${blocks.length} characters blocks, so the new character has no single place`, { blocks: blocks.length });
121
- const characters = blocks[0];
122
- const block = characters.value;
123
- const close = block.close;
124
- if (close === undefined)
125
- fail('CHARACTER_WRITE_LAYOUT_UNSUPPORTED', 'The characters block has no closing brace');
126
- const closeLineStart = text.lastIndexOf('\n', close.start - 1) + 1;
127
- if (!/^[ \t]*$/u.test(text.slice(closeLineStart, close.start)))
128
- fail('CHARACTER_WRITE_LAYOUT_UNSUPPORTED', 'The closing brace of the characters block shares its line with other text, so the new character has no line to go on', { line: close.line });
129
- const characterIndent = lineIndent(text, characters.start) + unit;
130
- const characterText = `${characterIndent}${input.id} = {${newline}${indentedBody(input.body, characterIndent + unit, newline)}${newline}${characterIndent}}${newline}`;
131
- edit = {
132
- start: closeLineStart,
133
- end: closeLineStart,
134
- text: `${block.entries.length > 0 ? newline : ''}${characterText}`,
135
- description: `add ${input.id}`,
136
- };
137
- }
138
- else {
139
- if (existing.length === 0)
140
- fail('CHARACTER_WRITE_NOT_FOUND', `${input.id} is not defined in this file`, {
141
- id: input.id,
142
- });
143
- if (existing.length > 1)
144
- fail('CHARACTER_WRITE_DUPLICATE_ID', `${input.id} is defined ${existing.length} times in this file`, { id: input.id, lines: existing.map(({ key }) => key.token.line) });
145
- const found = existing[0];
146
- skip = found;
147
- const characterIndent = lineIndent(text, found.start);
148
- if (input.operation === 'replace') {
149
- edit = {
150
- start: found.start,
151
- end: found.end,
152
- text: `${input.id} = {${newline}${indentedBody(input.body, characterIndent + unit, newline)}${newline}${characterIndent}}`,
153
- description: `replace ${input.id}`,
154
- };
155
- }
156
- else {
157
- const lineStart = text.lastIndexOf('\n', found.start - 1) + 1;
158
- const lineEndAt = text.indexOf('\n', found.end);
159
- const lineEnd = lineEndAt === -1 ? text.length : lineEndAt + 1;
160
- const alone = /^[ \t]*$/u.test(text.slice(lineStart, found.start)) &&
161
- /^[ \t]*\r?$/u.test(text.slice(found.end, lineEndAt === -1 ? text.length : lineEndAt));
162
- if (!alone) {
163
- edit = { start: found.start, end: found.end, text: '', description: `remove ${input.id}` };
164
- }
165
- else {
166
- // A blank line that only separated this character from the one before it goes with it.
167
- const before = text.slice(0, lineStart);
168
- const blankBefore = /(?:^|\n)[ \t]*\r?\n$/u.test(before) && before.length > 0;
169
- const after = text.slice(lineEnd);
170
- const nextIsBlankOrClose = /^[ \t]*(?:\r?\n|\})/u.test(after) || after === '';
171
- let start = lineStart;
172
- if (blankBefore && nextIsBlankOrClose)
173
- start = before.lastIndexOf('\n', before.length - 2) + 1;
174
- edit = { start, end: lineEnd, text: '', description: `remove ${input.id}` };
175
- }
176
- }
177
- }
178
- const bytes = applyReplacements(document, [edit]);
179
- const after = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
180
- const written = parseClausewitz(bytes, source.path);
181
- if (hasBlockingDiagnostics(written.diagnostics))
182
- fail('CHARACTER_WRITE_RESULT_INVALID', 'The edit would leave the file with syntax errors', {
183
- diagnosticCodes: written.diagnostics.map(({ code }) => code),
184
- });
185
- const before = definitionTexts(document, skip);
186
- const afterTexts = definitionTexts(written, undefined);
187
- let untouched = 0;
188
- for (const [key, texts] of before) {
189
- const now = afterTexts.get(key) ?? [];
190
- for (const textOfCharacter of texts)
191
- if (now.includes(textOfCharacter))
192
- untouched += 1;
193
- else
194
- fail('CHARACTER_WRITE_RESULT_INVALID', `The edit would change ${key}, which it must not touch`, { key });
195
- }
196
- if (written.text !== after)
197
- fail('CHARACTER_WRITE_RESULT_INVALID', 'The written file does not match the planned edit');
198
- return {
199
- operation: input.operation,
200
- id: input.id,
201
- path: source.path,
202
- text: after,
203
- bytes,
204
- edit,
205
- diff: unifiedTextDiff(text, after, `a/${source.path}`, `b/${source.path}`, {
206
- context: DIFF_CONTEXT_LINES,
207
- }),
208
- untouchedDefinitions: untouched,
209
- };
25
+ return plan(source.path, input, source.bytes);
210
26
  }
@@ -0,0 +1,62 @@
1
+ import path from 'node:path';
2
+ import { ReferenceService } from '../reference/service.js';
3
+ const services = new WeakMap();
4
+ const BULLET = /^\s*[-*]\s+`([a-z][a-z0-9_]*)`/u;
5
+ const TOKEN_HEADING = /^##\s+List of available strategy tokens\s*$/iu;
6
+ const STRATEGY_DOC = 'common/ai_strategy/_documentation.md';
7
+ const ON_ACTION_DOC = 'common/on_actions/_documentation.md';
8
+ function referencesOf(engine) {
9
+ const known = services.get(engine);
10
+ if (known !== undefined)
11
+ return known;
12
+ const created = new ReferenceService({ docsRoot: engine.resolver.config().docsRoot });
13
+ services.set(engine, created);
14
+ return created;
15
+ }
16
+ /**
17
+ * The lists from the lines of the two documentation files, by path under the game root. The
18
+ * strategy tokens are the bullets between the heading "List of available strategy tokens" and the
19
+ * next heading of its level or above: the later sections of that file (unit ratios, examples) have
20
+ * bullets of their own that are not tokens. The on_action names are every bullet of its file; the
21
+ * `on_daily_TAG` style entries have an upper-case tag and are not names.
22
+ */
23
+ export function parseDocumentedLists(files) {
24
+ const tokens = new Set();
25
+ const names = new Set();
26
+ let inTokenList = false;
27
+ for (const line of files.get(STRATEGY_DOC) ?? []) {
28
+ if (TOKEN_HEADING.test(line))
29
+ inTokenList = true;
30
+ else if (/^#{1,2}\s/u.test(line))
31
+ inTokenList = false;
32
+ else if (inTokenList) {
33
+ const match = BULLET.exec(line);
34
+ if (match?.[1] !== undefined)
35
+ tokens.add(match[1]);
36
+ }
37
+ }
38
+ for (const line of files.get(ON_ACTION_DOC) ?? []) {
39
+ const match = BULLET.exec(line);
40
+ if (match?.[1] !== undefined)
41
+ names.add(match[1]);
42
+ }
43
+ return {
44
+ tokens: tokens.size === 0 ? undefined : [...tokens].sort(),
45
+ names: names.size === 0 ? undefined : [...names].sort(),
46
+ };
47
+ }
48
+ export async function documentedLists(engine, workspaceId, principal, signal) {
49
+ const workspace = engine.resolver.get(workspaceId, principal);
50
+ const inventory = await referencesOf(engine).inventory(workspace, signal, ['game_doc']);
51
+ const files = new Map();
52
+ const sections = [...inventory.sections].sort((a, b) => a.startLine - b.startLine);
53
+ for (const section of sections) {
54
+ const file = section.relativePath.replaceAll('\\', '/').toLowerCase();
55
+ if (path.posix.basename(file) !== '_documentation.md')
56
+ continue;
57
+ const lines = files.get(file) ?? [];
58
+ lines.push(...section.lines);
59
+ files.set(file, lines);
60
+ }
61
+ return parseDocumentedLists(files);
62
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The caps of `hoi4.common_write` output, applied before the output schema parses, so a large
3
+ * definition (a balance of power with many ranges, a plan with hundreds of focuses) is reported
4
+ * short, with a count of what was left out, and never makes the schema throw.
5
+ */
6
+ export const MAX_DIFF_UNITS = 8_000;
7
+ export const MAX_FINDINGS = 50;
8
+ /** The diagnostics of the envelope; the count left out is in `omitted.diagnostics`. */
9
+ export const MAX_DIAGNOSTICS = 20;
10
+ export const MAX_NAMES = { localisation: 50, sprites: 20, categories: 5, focuses: 100 };
11
+ const MAX_NAME_LENGTH = 256;
12
+ const MAX_MESSAGE_LENGTH = 1_024;
13
+ /** `text` cut to at most `limit` UTF-16 units without splitting a surrogate pair. */
14
+ export function cutText(text, limit) {
15
+ if (text.length <= limit)
16
+ return text;
17
+ const high = text.charCodeAt(limit - 1);
18
+ return text.slice(0, high >= 0xd800 && high <= 0xdbff ? limit - 1 : limit);
19
+ }
20
+ export function capList(items, limit, length = MAX_NAME_LENGTH) {
21
+ return {
22
+ kept: items.slice(0, limit).map((item) => cutText(item, length)),
23
+ omitted: Math.max(0, items.length - limit),
24
+ };
25
+ }
26
+ export function capFindings(findings) {
27
+ return {
28
+ kept: findings.slice(0, MAX_FINDINGS).map((finding) => ({
29
+ ...finding,
30
+ code: cutText(finding.code, 128),
31
+ message: cutText(finding.message, MAX_MESSAGE_LENGTH),
32
+ })),
33
+ omitted: Math.max(0, findings.length - MAX_FINDINGS),
34
+ };
35
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A new file's path, checked before the engine is asked (the engine refuses the same paths): a
3
+ * path segment the mod may hold on every platform has no NTFS stream or drive (`:`), wildcard or
4
+ * control character, no trailing dot or space, and is not a reserved device name.
5
+ */
6
+ const RESERVED = /^(?:con|prn|aux|nul|conin\$|conout\$|(?:com|lpt)\d)$/iu;
7
+ export function isPlainSegment(part) {
8
+ if (part === '' || part === '.' || part === '..' || /[. ]$/u.test(part))
9
+ return false;
10
+ // eslint-disable-next-line no-control-regex -- control characters are the point
11
+ if (/[\u0000-\u001f\u007f:*?"<>|\\]/u.test(part))
12
+ return false;
13
+ return !RESERVED.test(part.split('.')[0] ?? '');
14
+ }
15
+ export function isPlainRelativePath(path) {
16
+ return path.split('/').every(isPlainSegment);
17
+ }
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod/v4';
2
+ import { toolResult } from '../core/operation-result.js';
3
+ import { ServiceError } from '../core/result.js';
4
+ import { commonWriteRequestSchema } from '../schemas/common-write.js';
5
+ import { completeCommonWrite, prepareCommonWrite, previewCommonWrite, } from './write-operations.js';
6
+ const wireResult = z.record(z.string(), z.json());
7
+ function wire(result) {
8
+ return wireResult.parse(JSON.parse(JSON.stringify(toolResult(result))));
9
+ }
10
+ /** Registers `hoi4.common_write`: a read-only preview, or one journaled transaction. */
11
+ export function registerCommonWriteJobs(operations, engine) {
12
+ operations.registerWrite('hoi4.common_write', commonWriteRequestSchema, async (input, context) => {
13
+ if (input.workspaceId !== 'current' && input.workspaceId !== context.workspaceId)
14
+ throw new ServiceError('JOB_ARGUMENT_SCOPE_MISMATCH', 'The request workspace does not match the authorized job workspace');
15
+ const operationContext = {
16
+ workspaceId: context.workspaceId,
17
+ ...(context.principal === undefined ? {} : { principal: context.principal }),
18
+ signal: context.signal,
19
+ progress: (completed, total, message) => context.progress({ completed, total, message }),
20
+ };
21
+ if (!input.apply)
22
+ return {
23
+ readOnlyPreview: wire(await previewCommonWrite(engine, input, operationContext)),
24
+ };
25
+ const prepared = await prepareCommonWrite(engine, input, operationContext);
26
+ if ('readOnlyPreview' in prepared)
27
+ return { readOnlyPreview: wire(prepared.readOnlyPreview) };
28
+ return { transaction: prepared.transaction, recipe: { ...prepared.recipe } };
29
+ }, async (_input, execution, _reconciled, recipe, context) => {
30
+ const result = completeCommonWrite(context.workspaceId, execution, recipe);
31
+ await context.progress({
32
+ completed: 3,
33
+ total: 3,
34
+ message: execution.outcome === 'applied'
35
+ ? 'Definition change complete'
36
+ : execution.outcome === 'unchanged'
37
+ ? 'The definition already matched the request'
38
+ : 'Definition change blocked',
39
+ });
40
+ return wire(result);
41
+ });
42
+ }