hoi4-agent-tools 4.7.0 → 4.9.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.
- package/CHANGELOG.md +34 -0
- package/README.md +32 -13
- package/dist/hoi4_agent_tools/core/engine-client.js +74 -5
- package/dist/hoi4_agent_tools/core/index.js +28 -0
- package/dist/hoi4_agent_tools/core/operation-result.js +9 -0
- package/dist/hoi4_agent_tools/core/resident-engine.js +273 -0
- package/dist/hoi4_agent_tools/core/temporary-directories.js +3 -2
- package/dist/hoi4_agent_tools/decision/service.js +46 -2
- package/dist/hoi4_agent_tools/event/queries.js +25 -2
- package/dist/hoi4_agent_tools/event/service.js +78 -11
- package/dist/hoi4_agent_tools/event/summary.js +9 -0
- package/dist/hoi4_agent_tools/focus/engine-layout.js +1 -1
- package/dist/hoi4_agent_tools/focus/game-render.js +72 -0
- package/dist/hoi4_agent_tools/focus/game-view-output.js +160 -0
- package/dist/hoi4_agent_tools/focus/native-effects.js +4 -4
- package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +241 -241
- package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +30 -19
- package/dist/hoi4_agent_tools/focus/quality/schematic.js +5 -3
- package/dist/hoi4_agent_tools/focus/quality/scorecard.js +1 -1
- package/dist/hoi4_agent_tools/focus/render.js +21 -9
- package/dist/hoi4_agent_tools/focus/tool-operations.js +158 -3
- package/dist/hoi4_agent_tools/gui/assets.js +18 -0
- package/dist/hoi4_agent_tools/gui/dds.js +38 -5
- package/dist/hoi4_agent_tools/gui/engine-textures.js +48 -0
- package/dist/hoi4_agent_tools/gui/source-graph.js +7 -0
- package/dist/hoi4_agent_tools/gui/tool-operations.js +23 -4
- package/dist/hoi4_agent_tools/gui/validators.js +31 -2
- package/dist/hoi4_agent_tools/ideas/inspect.js +43 -0
- package/dist/hoi4_agent_tools/impact/service.js +15 -0
- package/dist/hoi4_agent_tools/localisation/inspect.js +34 -0
- package/dist/hoi4_agent_tools/map/appearance-validation.js +14 -2
- package/dist/hoi4_agent_tools/map/geography/resolve.js +3 -2
- package/dist/hoi4_agent_tools/map/tool-operations.js +41 -0
- package/dist/hoi4_agent_tools/map/world-edge.js +117 -15
- package/dist/hoi4_agent_tools/map/world.js +158 -34
- package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +59 -9
- package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
- package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +1 -1
- package/dist/hoi4_agent_tools/mcp/tools/analysis.js +4 -2
- package/dist/hoi4_agent_tools/mcp/tools/event.js +15 -0
- package/dist/hoi4_agent_tools/mcp/tools/focus.js +1 -1
- package/dist/hoi4_agent_tools/mcp/tools/gui.js +1 -1
- package/dist/hoi4_agent_tools/mcp/tools/reference.js +43 -0
- package/dist/hoi4_agent_tools/probability/operations.js +27 -1
- package/dist/hoi4_agent_tools/probability/service.js +91 -11
- package/dist/hoi4_agent_tools/probability/source-analysis.js +2 -2
- package/dist/hoi4_agent_tools/probability/sweep.js +20 -6
- package/dist/hoi4_agent_tools/reference/command-phrases.json +11065 -0
- package/dist/hoi4_agent_tools/reference/error-log.js +59 -1
- package/dist/hoi4_agent_tools/reference/known-mistakes.js +8 -5
- package/dist/hoi4_agent_tools/reference/known-mistakes.json +4 -4
- package/dist/hoi4_agent_tools/reference/operations.js +205 -12
- package/dist/hoi4_agent_tools/reference/ranking.js +32 -0
- package/dist/hoi4_agent_tools/reference/script-validation.js +159 -8
- package/dist/hoi4_agent_tools/reference/service.js +33 -0
- package/dist/hoi4_agent_tools/reference/source-lookup.js +8 -0
- package/dist/hoi4_agent_tools/schemas/focus-requests.js +4 -0
- package/dist/hoi4_agent_tools/schemas/ideas.js +142 -0
- package/dist/hoi4_agent_tools/schemas/localisation.js +94 -0
- package/dist/hoi4_agent_tools/schemas/map.js +32 -4
- package/dist/hoi4_agent_tools/schemas/mod-tools.js +11 -0
- package/dist/hoi4_agent_tools/schemas/script-validation.js +8 -1
- package/dist/hoi4_agent_tools/schemas/system.js +157 -0
- package/dist/hoi4_agent_tools/system/inspect.js +55 -0
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/analysis.md +2 -2
- package/docs/events.md +1 -1
- package/docs/focus.md +9 -5
- package/docs/map.md +19 -8
- package/docs/research/reference-benchmark.md +41 -0
- package/docs/tools.md +49 -39
- package/docs/troubleshooting.md +13 -12
- package/engine/README.md +293 -0
- package/engine/bin/darwin-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-arm64/hoi4-engine +0 -0
- package/engine/bin/linux-x64/hoi4-engine +0 -0
- package/engine/bin/manifest.json +26 -0
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +4 -1
- package/schemas/configuration.schema.json +1 -1
- package/schemas/continuous-focus-palette.schema.json +1 -1
- package/schemas/custom-weighted-pool.schema.json +1 -1
- package/schemas/decision-inspect-input.schema.json +1 -1
- package/schemas/error-log-input.schema.json +1 -1
- package/schemas/event-feature-manifest.schema.json +1 -1
- package/schemas/focus-plan.schema.json +1 -1
- package/schemas/focus-planning-sidecar.schema.json +1 -1
- package/schemas/geography-model.schema.json +1 -1
- package/schemas/gui-animation-source.schema.json +1 -1
- package/schemas/gui-helper.schema.json +1 -1
- package/schemas/gui-scenario.schema.json +1 -1
- package/schemas/helper-expansion-request.schema.json +1 -1
- package/schemas/helper-expansion-summary.schema.json +1 -1
- package/schemas/impact-inspect-input.schema.json +1 -1
- package/schemas/map-operation.schema.json +165 -101
- package/schemas/mechanic-test-input.schema.json +1 -1
- package/schemas/mod-index-input.schema.json +1 -1
- package/schemas/operation-result.schema.json +1 -1
- package/schemas/package-check-input.schema.json +1 -1
- package/schemas/package-manifest.schema.json +1 -1
- package/schemas/probability-analysis-result.schema.json +1 -1
- package/schemas/probability-compare-input.schema.json +1 -1
- package/schemas/probability-evaluate-input.schema.json +1 -1
- package/schemas/probability-inspect-input.schema.json +1 -1
- package/schemas/probability-render-input.schema.json +1 -1
- package/schemas/probability-scenario-set.schema.json +1 -1
- package/schemas/probability-sequence-input.schema.json +1 -1
- package/schemas/probability-simulate-input.schema.json +1 -1
- package/schemas/probability-sweep-input.schema.json +1 -1
- package/schemas/reference-context-input.schema.json +1 -1
- package/schemas/reference-read-input.schema.json +1 -1
- package/schemas/reference-search-input.schema.json +1 -1
- package/schemas/reference-sheets.schema.json +1 -1
- package/schemas/scenario-suite.schema.json +1 -1
- package/schemas/scenario-test-input.schema.json +1 -1
- package/schemas/script-validate-input.schema.json +1 -1
- package/schemas/shared-scenario.schema.json +1 -1
- package/schemas/source-lookup-input.schema.json +1 -1
- package/server.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 4.9.0 - 2026-11-05
|
|
6
|
+
|
|
7
|
+
- Results no longer suggest the wrong conclusion (#65, the parts #82 left open). `error_log` fails a new `error-log-age` check when the mod's script, localisation or interface files changed after the log was written, and names how many, the newest time and an example file, because such a log cannot vouch for the current source. `script_validate` names what made a result partial (`partialReasons`), for example the blocks of a scripted helper file whose scope depends on the caller, by line, so `SCRIPT_CHECK_PARTIAL` with `unresolvedCount: 0` no longer comes without a reason. Every example in a tool description or an argument error is now checked against the tool's own schema in a test. That found and fixed the `gui_rewrite` patch example, which lacked the required `description`, and the `gui_rewrite` and `mechanic_test` examples, which held `...` placeholders. An unknown field in the arguments now lists the fields that object accepts. The tools list budget in the discovery test moves from 80 to 84 KiB for the longer, runnable examples.
|
|
8
|
+
- Apply every selector, and answer unknown ids with an explicit not-found instead of `ok` with nothing (#59). `event_inspect` checks its selector in every mode: an event, namespace, node or source that nothing matches is `EVENT_NOT_FOUND`, `EVENT_NAMESPACE_NOT_FOUND`, `EVENT_NODE_NOT_FOUND` or `EVENT_SOURCE_NOT_FOUND` with close names. `roots` keeps only the selected events, the entry points that start them and the cycles through them. It now counts an event a scripted effect fires as called, so such events are no longer listed as callerless. `state_flow` narrows its issues and summary to the `stateSubject`, puts the subject's producers and readers inline, and answers `EVENT_STATE_NOT_FOUND` for a flag, variable or target nothing uses. A `decision_inspect` inventory with an `id` lists only that category's decisions, or that one decision, with their ids inline, and any other id is `DECISION_NOT_FOUND`. `impact_inspect` answers `IMPACT_SYMBOL_NOT_FOUND` for a symbol nothing defines or uses, instead of dropping it. `map_inspect` answers `MAP_ENTITY_ID_NOT_FOUND` when none of the requested state, province or region ids exists, before any validation or render. A selection with some known ids still reports the unknown ones.
|
|
9
|
+
- `script_validate` checks identifier arguments against the definitions of the mod, its dependencies and the game (#68): ideas (`add_ideas`, `remove_ideas`, `has_idea`, `add_timed_idea`, `modify_timed_idea`), decisions (`activate_decision`, `activate_targeted_decision`), focuses (`has_completed_focus`, `complete_national_focus`, `uncomplete_national_focus`), technologies (`has_tech`) and events (`country_event`, `news_event`, `state_event`, `unit_leader_event`, `operative_leader_event`). An id that nothing defines is `SCRIPT_ARGUMENT_UNKNOWN_ID` with up to three close names, and `parametersChecked` is true. It is a warning, because the game loads the file and the command does nothing, as five dangling ids in vanilla 1.19.4.1 show. Ids match without case, as the game finds them (vanilla fires `NSB_news.2` for `nsb_news.2`). Computed values are not read, and a partial index reports `unresolved` instead. The index now holds shared and joint focuses and the ideas that advisors' `idea_token`s make. The known-good sweeps of vanilla, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues raise no new error.
|
|
10
|
+
- Add `hoi4.asset_inspect` on the shared Rust engine (`hoi4-engine assets`; coverage tools part 5, issue #71). One tool reads sprites, sounds and flags. A sprite comes back with every definition in load order, its texture with layer, container, pixel format, size and mipmaps, and its frames. A sound, sound effect, category or music track comes back with its audio file (relative to its `.asset` file's folder) and the sounds or sound effects it plays. A flag comes back with its three files (82x52, `medium/` 41x26 and `small/` 10x7). Each answer lists the files that mention the asset. `audit: true` checks every sprite, sound or flag the mod defines, and the flag audit also reports country tags of the mod with no flag at all (dynamic tags excepted). Missing and unreadable textures, BC7 textures (`ASSET_TEXTURE_FORMAT_RISKY`, after an in-game crash on 1.19.4.1), missing audio files, unknown sounds and wrong flag sizes are warnings. Uneven frames, sprites without a texture that the game fills itself, empty texture files that hide a picture and flags one pixel off are information. Texture headers are now read by content, so PNG files named `.dds` read as PNG, as the game reads them. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues every warning was checked by hand. Vanilla's are real: six sound files saved under other names, three flags of the wrong size and a placeholder flag with one size.
|
|
11
|
+
- Add `hoi4.unit_inspect` on the shared Rust engine (`hoi4-engine units`; coverage tools part 4, issue #71). One tool reads orders of battle (`history/units` files), sub-units, equipment and equipment modules, and equipment variants. One id comes back with every definition in load order, its parts (templates, fleets, module slots), each name it uses with whether something defines it, its name and description in every language, and the files that mention it. `audit: true` checks every one the mod makes. An order of battle's templates must fit the division designer's grid, read from the `MAX_DIVISION_` defines so a mod that changes the grid is judged by its own, and no two sub-units may share a slot. Its divisions, fleets and air wings must name templates (from any order of battle or the `division_template` effect), sub-units, equipment, variants, provinces, states or carriers that load. Equipment must name known archetypes, parents, upgrades, resources, module categories and default modules, and a variant known equipment, modules and upgrades. Equipment that a `duplicate_archetypes` copy derives counts as defined. The audit of orders of battle also reports `oob`, `set_oob` and `load_oob` names that no `history/units` file has. A missing name is information. An unknown id is `UNIT_DEFINITION_NOT_FOUND` with close ids. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues every finding was checked by hand. Vanilla still has real ones: two regiments in one slot in `CZE_1936`, `oob` names of countries without a file, and division name groups lost to unbalanced quotes in `FIN_names_divisions.txt`. An audit takes 5 to 40 s with a cold file cache.
|
|
12
|
+
- Add `hoi4.system_inspect` on the shared Rust engine (`hoi4-engine system`; coverage tools part 3, issue #71). One tool reads the newer systems: on_actions hooks, military-industrial organizations and their policies, balances of power, special projects with their prototype rewards, specializations and project tags, operations with their phases and tokens, and raids with their categories. One id comes back with every definition in load order, its fields as written, its parts (traits, ranges, sides, options, phases), each reference it makes with whether something defines the target, its name and description in every language, and the files that mention it. `audit: true` checks every definition of that system the mod makes. The checks follow the documentation in each game folder, corrected where the shipped files differ: an organization's include, removed and overridden traits and trait parents, duplicate trait tokens, pictures, and modifiers; a balance of power's sides and ranges; a project's specialization, tags, parents, rewards and the equipment, modules and sub-units it enables; an operation's phases, tokens and equipment; a raid's category, sub-units and target buildings; the events an on_actions hook fires; and the hooks a mod drops by replacing an on_actions file. A hook that neither the documentation, the game's own files nor its executable uses, and a missing name, are information. A balance of power's `decision_category` creates its category, so it is not checked. An unknown id is `SYSTEM_DEFINITION_NOT_FOUND` with close ids. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues no warning remains and every finding was checked by hand. An audit takes 2 to 12 s with a warm file cache.
|
|
13
|
+
- Close the world seam for fleets as well as armies: `create_world.edge.mode: "wall"` (ADR 0061, amended). A `rim` blocks land provinces across the seam but leaves the sea there sailable, so ships crossed from the far west to the far east. A wall fills `rimPx` (default 48) at the east and west edges with land over the full height (`MAP_EDGE_WALL_FILLED`), with a ragged inner edge, the rim's heights and seam rows, and the look of the land it meets row by row (or caller `wallTerrain` segments), and puts its provinces in impassable `enclave` states linked by `force_link_ownership_to` to the nearest passable state, as the base game's impassable states are. Cities and workspace capitals in the wall are refused, and validation reports water on the seam columns of a wall world as `MAP_EDGE_WALL_OPEN`. `polarPx: 0` lets land run off the top and bottom edges.
|
|
14
|
+
|
|
15
|
+
## 4.8.0 - 2026-11-05
|
|
16
|
+
|
|
17
|
+
- Ship `hoi4-engine` inside the npm package and the container image (ADR 0074, amended): the release builds it for Windows x64, macOS arm64 and Linux x64 and arm64 (glibc 2.35 or later) and bundles every platform under `engine/bin/` with a SHA-256 manifest, so `layoutMode: "engine"`, `placement` and the engine checks work after a plain install. The bundled binary runs only when its SHA-256 matches `engine/bin/manifest.json`; otherwise the call reports `binary_checksum_mismatch` and nothing runs. `HOI4_ENGINE` still wins, and other platforms report the engine unavailable as before. Each image holds the binary for its own architecture. The package grows by about 4 MB.
|
|
18
|
+
- Add `hoi4.idea_inspect` on the shared Rust engine (`hoi4-engine ideas`; coverage tools part 2, issue #71). An idea comes back with its category, every definition in load order, its picture sprite and texture, its modifiers checked against the game's documentation, the mod's `common/modifier_definitions` and the modifiers the game builds from buildings, sub-units, unit categories, idea slots and operations, its conditions and effects as written, its name and description in every language, the character whose advisor `idea_token` it is, and the files that mention it. A character comes back with its name, every role (country leader, advisor, general, field marshal, admiral, operative) with its traits checked, and its portraits checked. `audit: true` checks every idea or character of the mod. Hidden ideas and ideas with `visible = { always = no }` need no picture or name. Sprites and textures of the game itself are not judged, because a DLC that is not installed may supply them. A missing name is information. An unknown id is `IDEA_NOT_FOUND` or `CHARACTER_NOT_FOUND` with close ids. On vanilla, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich and Old World Blues every reported problem was checked by hand: vanilla has none.
|
|
19
|
+
- Add `hoi4.localisation_inspect` on the shared Rust engine (`hoi4-engine localisation`; issue #71, plan `docs/plans/coverage-tools.md`). It reads every localisation file of the game, DLC, dependencies and mod in every language. `key` returns one key's text per language with file, line and layer, the supported languages that lack it and the script files that mention it; an unknown key is `LOCALISATION_KEY_NOT_FOUND` with close keys. `audit` counts the mod's problems and keeps a few examples of each: keys the mod's script uses that no language defines, keys of the main language missing from a supported language, keys defined twice in one language, and file problems. Text that scripted localisation shows as written, and a translation that writes a name out instead of keeping `$key$`, are information, not problems. `coverage` counts keys per language. A language is supported when it holds at least a quarter of the main language's keys. Without the engine the tool answers `ENGINE_UNAVAILABLE`. On vanilla 1.19.4.1, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich 1.7 and Old World Blues 5.1.12 every reported problem was checked by hand. A key lookup takes about 2.5 s and an audit 3 to 15 s.
|
|
20
|
+
- Find more documentation answers first from plain-word questions (ADR 0078). Each documented effect, trigger and modifier now also matches four plain-word phrasings of what it does (`command-phrases.json`, written once from its documentation and in-game text), and a question that grants something prefers `add_` and `create_` commands over their `remove_` and `end_` counterparts, and the other way round. On 40 blind test questions on HOI4 1.19.4.1, 25 rather than 21 answers rank first and 31 rather than 27 within three. On a second blind set written for this change, 17 rather than 9 of 38 rank first. Add that set as `--fresh` to the discovery benchmark.
|
|
21
|
+
- Make the focus preview fast (#74). `hoi4.focus_render` no longer rasterizes the schematic SVG for its PNG, which took 118 to 129 seconds of every call on vanilla Germany: the resident engine draws the game view instead. New input `view: "game"` returns the game view alone (PNG, a JSON report that records the render request, an SVG hover map and a self-contained HTML viewer with zoom, drag and hover titles, and one inline overview of at most about 700 KB), without the schematic or the presentation pass, for a preview that renders after every edit. The engine caches each workspace's parsed `.gfx` files, folder listings, textures and fonts for the server's life, checks each folder once per render and remembers sprites within a render. On the largest trees of the game and six mods, a warm `view: "game"` call takes 3 to 12 s and the engine's own warm render 0.1 to 0.5 s, against 15 to 136 s per call before; numbers per mod are in the pull request. `scripts/bench/preview-timing.ts` and `preview-engine-timing.ts` measure them, and `bench/corpus.json` gains Atlantis.
|
|
22
|
+
- Draw the national focus view as the game does (#75). `hoi4.focus_render`'s PNG is now the game view whenever the engine binary is available; without it, the PNG stays the schematic with decoded icons. Assets the view cannot draw are listed as `FOCUS_GAME_VIEW_ASSET_MISSING` and a failed engine render as `FOCUS_GAME_VIEW_UNAVAILABLE`. The new engine crate `hoi4-preview` renders a focus tree from the game's own assets in load order: the tree window background, the "can start" and "unavailable" plaques, icons, titles in the game's bitmap font (`hoi_16mbs`, with `§` colour codes), the solid and dotted connector tiles with their junction tiles, and the exclusive mark. Its geometry is read from `interface/nationalfocusview.gui`, so a mod that changes the view is drawn its way. On the in-game screenshots of game 1.19.4.1 at the default UI scale (run27), plaques, icons, titles and connectors land on the same pixels: the mean difference per region is 0.0 for titles and at most 2.8 of 255 for plaques, icons and connectors. Missing sprites, textures, fonts and glyphs are reported per focus, never drawn as something else. `hoi4-engine focus-render` draws one tree, and `hoi4-engine serve` answers `focus.render` with a cache per workspace. Not modelled: focus states other than "can start" and "unavailable", `available` and `bypass` triggers, joint-focus plaques, scripted localisation, animations, and exclusive marks between focuses on different rows or more than two columns apart.
|
|
23
|
+
- Decode every DDS format the game draws (#76). The GUI, sprite and icon renders now read DX10-header textures in any 8-bit RGBA or BGRA layout (DXGI 27 to 30 and 87 to 93) and BC1 to BC3 themselves, and hand BC4, BC5, BC7, packed 16-bit and 10-bit formats, luminance and alpha-only DDS to the Rust engine's new `hoi4-texture` crate (`engine/crates/texture`). Its decodes match a reference decode on 35 synthetic fixtures, bit for bit for BC7 (every mode and partition) and the 8-bit formats. It decodes all 34,923 DDS and TGA files of game 1.19.4.1 and all 219 DX10 files of Chaos Redux, and reads a file by its content, so the 456 PNG files Kaiserreich and Old World Blues ship with a `.dds` name decode too. A format nothing decodes, such as BC6H, still reports `GUI_TEXTURE_UNSUPPORTED`, now naming the format, and without the engine binary the reason says how to get it. A sprite whose texture is BC7 gets the warning `GUI_TEXTURE_FORMAT_RISKY`: in an in-game check on 1.19.4.1 a BC7 texture failed to load and the game crashed.
|
|
24
|
+
- Keep one engine process for the server's life (ADR 0077). `hoi4-engine serve` answers framed requests (a JSON line, then raw bytes) in parallel over stdin and stdout, with no idle eviction, a restart after a crash and a timeout per request. `hoi4-engine texture` decodes or checks texture files and folders.
|
|
25
|
+
- Correct the in-game focus connector model: the bar runs just under the parent's row and the long vertical drops in the child's column into the child's icon, as an in-game run on 1.19.4.1 showed at the default UI scale and zoom. The TypeScript scorecard, the schematic render and the Rust engine (`insert` crossing costs included) share it, with a parity test of seven hand-counted trees. The vanilla calibration is recomputed for game 1.19.4.1 and the corrected model, so the H4, H5 and S9 limits change.
|
|
26
|
+
- Add the benchmark harness (`bench/`, `npm run bench`; decisions Q-1, M-6, M-12). Each case is one tool call over the real stdio server with a hand-checked expected answer and its evidence. Sweeps count false positives over known-good files. Runs report correctness, inline answers, latency and result size per surface, against a stored baseline. The synthetic suite runs in CI on every platform (`tests/integration/bench-synthetic.test.ts`) and fails on any regression. The real suite runs on the installed game, Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich 1.7 and Old World Blues 5.1.12 on the maintainer's machine (`scripts/bench/nightly.sh`). It pins each corpus by game build, Git commit, Workshop manifest and content hash, and keeps its results there. `scripts/bench/hoi4-mcp/` holds the one-time isolated head-to-head with cpntodd/HOI4-MCP. CI gains a macOS arm64 job. The npm package is unchanged. The test setup runs in the temporary folder's real path, so the suite also passes on macOS.
|
|
27
|
+
- Remove 104 of the 110 false errors `script_validate` raised on known-good vanilla 1.19.4.1, Chaos Redux, Kaiserreich and Old World Blues files (benchmark sweeps of 1,027 files); the other 6 are real errors the game confirms. An in-game check (2026-11-02) settled each rule. A unit leader event runs with the general as ROOT and THIS, and accepts country commands as well, as vanilla options use them. `controller` is accepted in country scope and `capital_scope` in state scope. Event namespaces match in any letter case. An event id with a text suffix (vanilla `BBA_italy_missiolinis.02_north`) is no longer reported, only a number of 100000 or more, which the game confirms collides with the next namespace. `owner = ROOT` and other links used as triggers are still errors, which the game drops at load, now reported as `SCRIPT_SCOPE_LINK_AS_TRIGGER` naming `is_owned_by` or `is_controlled_by` (#67).
|
|
28
|
+
- `error_log` reads the active mods of the logged launch from `logs/system.log` (`data.launch`) and fails its check when that launch did not load the mod, instead of reporting no errors (#65). Every tool's text answer now lists the messages of failed checks (`failedChecks`), for clients that show only the text.
|
|
29
|
+
- `source_lookup` and `decision_inspect` answer an id that nothing defines with `SYMBOL_NOT_FOUND` or `DECISION_NOT_FOUND` and the close names, instead of an empty `ok` (#59).
|
|
30
|
+
- Evaluate the probability request that was asked. A sweep of a decision with `days_remove = -1` no longer runs as a mission, a sweep path with only a current value now spreads the requested `steps` over zero to twice that value (reported as `PROBABILITY_SWEEP_RANGE_DEFAULTED`), an adapter that matches nothing is refused with the adapters that do match instead of being replaced silently, a requested metric that cannot be computed gets a `PROBABILITY_METRIC_NOT_COMPUTED` reason (for example `cumulative_chance` without `horizonDays`), and `probability_inspect` with an event id and no adapter now evaluates the event's options. (#63)
|
|
31
|
+
- Stop `gui_inspect` reporting working GUI as defective. Sprite names returned by `defined_text` (`localization_key = GFX_...`) now resolve against the sprite inventory instead of raising `GUI_REFERENCE_UNRESOLVED`. A plain background, frame or fill image under an element it wholly contains is no longer a `GUI_VISIBLE_OVERLAP`. A meter fill image parked beyond the leading edge of its clip window is no longer `GUI_ACCIDENTAL_CLIPPING`. Inline diagnostics put errors before warnings when the list is truncated, so a flood of warnings cannot hide an error (#62)
|
|
32
|
+
- `gui_inspect` answers an unknown `windowName` with `GUI_WINDOW_NOT_FOUND`, naming the window, and writes no artifact. It used to return `ok` with a 116 MB inspection artifact on Chaos Redux (#59).
|
|
33
|
+
- Fix `event_inspect` focused routes (trace, explain_path, and selector-scoped scan, roots and lint) scanning only `events/` and `common/on_actions/`: scripted effects defined in `common/scripted_effects/` were reported as `EVENT_HELPER_UNRESOLVED`, and callers in scripted effects, decisions, focuses, ideas and the other event-bearing folders were never found, so upstream traces returned no callers and events looked callerless. Focused routes now scan every event-bearing folder and skip only localisation, and a trace summary names the entry points and scripted effects it passes through (#57, #58).
|
|
34
|
+
- `event_inspect` traces of an event that no scanned file defines or fires now fail with `EVENT_NOT_FOUND` and the close event ids, instead of an empty `ok` trace (#59).
|
|
35
|
+
- Check duplicate ids of every definition kind in the shared Rust engine (`hoi4-engine check`). `LINT_DUPLICATE_DEFINITION` now covers focuses (shared and joint ones included), ideas, decisions, characters and technologies as errors, the same localisation key twice in one language as a warning, and the same sprite twice as information. Advisor `idea_token`s repeated across a character's instances and keys under `localisation/replace/` are not duplicates. The new `LINT_DUPLICATE_ACROSS_LAYERS` reports an id that a dependency or the game also defines in a file the mod does not replace: an error for events, whose ids collide, and a warning otherwise. On Chaos Redux, ZIN, Ireland Total Overhaul, Kaiserreich 1.7 and Old World Blues 5.1.12 it raises no new error.
|
|
36
|
+
|
|
3
37
|
## 4.7.0 - 2026-11-02
|
|
4
38
|
|
|
5
39
|
- Lay out focus trees with the shared Rust engine. `hoi4.focus_rewrite` takes `layoutMode: "engine"`, which places the tree's automatic focuses with `hoi4-engine focus-layout` and writes lane roots with x and y and every other placed focus with `relative_position_id`, and `placement` (`focusIds`, `anchorId`, `preferSide`, `allowShift`), which fits new focuses in while every other focus keeps its coordinates. The result adds the engine's metrics and hashes (`hashes.untouched` proves the other focuses did not move) to the layout verdict and delta. A blocked layout is refused with `needsRoom` and a missing engine with `FOCUS_ENGINE_UNAVAILABLE`, and nothing is written; there is no fallback to the TypeScript solver. The engine is found through `HOI4_ENGINE` or a binary shipped under `engine/bin`. `authored` and `compact` are unchanged.
|
package/README.md
CHANGED
|
@@ -1,17 +1,36 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/klimPaskov/hoi4-agent-tools/main/docs/images/logo.png" width="96" height="96" alt="HOI4 Agent Tools">
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<h1 align="center">HOI4 Agent Tools</h1>
|
|
6
|
+
|
|
7
|
+
<p align="center">
|
|
8
|
+
An <a href="https://modelcontextprotocol.io/">MCP</a> server that helps coding agents build and edit <em>Hearts of Iron IV</em> mods.
|
|
9
|
+
</p>
|
|
10
|
+
|
|
11
|
+
<p align="center">
|
|
12
|
+
<a href="https://www.npmjs.com/package/hoi4-agent-tools"><img alt="npm" src="https://img.shields.io/npm/v/hoi4-agent-tools"></a>
|
|
13
|
+
<a href="https://nodejs.org/"><img alt="Node.js" src="https://img.shields.io/node/v/hoi4-agent-tools"></a>
|
|
14
|
+
<a href="LICENSE"><img alt="License" src="https://img.shields.io/npm/l/hoi4-agent-tools"></a>
|
|
15
|
+
<a href="https://github.com/klimPaskov/hoi4-agent-tools/releases/latest"><img alt="Release" src="https://img.shields.io/github/v/release/klimPaskov/hoi4-agent-tools?label=Release&logo=github&color=2ea44f"></a>
|
|
16
|
+
<a href="https://discord.gg/rAXesGcT2t"><img alt="Discord" src="https://img.shields.io/badge/Discord-Join%20Community-7289da?logo=discord&logoColor=white"></a>
|
|
17
|
+
<a href="https://www.youtube.com/@ChaosRedux"><img alt="YouTube" src="https://img.shields.io/badge/YouTube-Chaos%20Redux-ff0000?logo=youtube&logoColor=white"></a>
|
|
18
|
+
<a href="https://ko-fi.com/klimpaskov"><img alt="Ko-fi" src="https://img.shields.io/badge/Ko--fi-Support%20the%20Project-ff5e5b?logo=kofi&logoColor=white"></a>
|
|
19
|
+
<a href="https://github.com/klimPaskov/hoi4-agent-tools/issues"><img alt="Issues" src="https://img.shields.io/badge/Bugs%20%26%20Ideas-Issues-24292f?logo=github&logoColor=white"></a>
|
|
20
|
+
</p>
|
|
21
|
+
|
|
22
|
+
<p align="center">
|
|
23
|
+
<a href="#quick-start">Quick start</a> ·
|
|
24
|
+
<a href="https://www.npmjs.com/package/hoi4-agent-tools">npm</a> ·
|
|
25
|
+
<a href="CHANGELOG.md">Changelog</a> ·
|
|
26
|
+
<a href="CONTRIBUTING.md">Contributing</a> ·
|
|
27
|
+
<a href="SECURITY.md">Security</a>
|
|
28
|
+
</p>
|
|
29
|
+
|
|
30
|
+
<p align="center">
|
|
31
|
+
<a href="https://www.youtube.com/watch?v=Dd36E_NK4rQ"><img src="https://raw.githubusercontent.com/klimPaskov/hoi4-agent-tools/main/docs/images/agent-tools-demo-thumbnail.png" alt="Watch the HOI4 Agent Tools demo"></a>
|
|
32
|
+
</p>
|
|
2
33
|
|
|
3
|
-
[](https://www.youtube.com/watch?v=Dd36E_NK4rQ)
|
|
4
|
-
|
|
5
|
-
[](https://www.npmjs.com/package/hoi4-agent-tools)
|
|
6
|
-
[](https://nodejs.org/)
|
|
7
|
-
[](LICENSE)
|
|
8
|
-
[](https://discord.gg/rAXesGcT2t)
|
|
9
|
-
[](https://www.youtube.com/@ChaosRedux)
|
|
10
|
-
[](https://ko-fi.com/klimpaskov)
|
|
11
|
-
[](https://github.com/klimPaskov/hoi4-agent-tools/releases/latest)
|
|
12
|
-
[](https://github.com/klimPaskov/hoi4-agent-tools/issues)
|
|
13
|
-
|
|
14
|
-
An [MCP](https://modelcontextprotocol.io/) server that helps coding agents build and edit Hearts of Iron IV mods.
|
|
15
34
|
Make focus trees, events and decisions. Edit maps and generate a new world. Preview windows, trees and maps, find the right rule in the docs, fix broken script and balance AI choices.
|
|
16
35
|
|
|
17
36
|
## What it does
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import {
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
import { fileURLToPath } from 'node:url';
|
|
5
6
|
import { z } from 'zod/v4';
|
|
@@ -26,13 +27,78 @@ function isFile(candidate) {
|
|
|
26
27
|
return false;
|
|
27
28
|
}
|
|
28
29
|
}
|
|
30
|
+
export const ENGINE_BUNDLE_MANIFEST_SCHEMA = 'hoi4-engine-bundle/1';
|
|
31
|
+
/** `engine/bin/manifest.json`: the SHA-256 and size of every bundled binary, keyed by `<platform>-<arch>`. */
|
|
32
|
+
export const engineBundleManifestSchema = z.strictObject({
|
|
33
|
+
schema: z.literal(ENGINE_BUNDLE_MANIFEST_SCHEMA),
|
|
34
|
+
engineVersion: z.string().min(1),
|
|
35
|
+
binaries: z.record(z.string().regex(/^[a-z0-9]+-[a-z0-9]+$/u), z.strictObject({
|
|
36
|
+
file: z.string().regex(/^[a-z0-9]+-[a-z0-9]+\/hoi4-engine(?:\.exe)?$/u),
|
|
37
|
+
sha256: z.string().regex(/^[0-9a-f]{64}$/u),
|
|
38
|
+
size: z.number().int().positive(),
|
|
39
|
+
})),
|
|
40
|
+
});
|
|
41
|
+
export function engineBundleManifestPath(packageRoot = defaultPackageRoot()) {
|
|
42
|
+
return path.join(packageRoot, 'engine', 'bin', 'manifest.json');
|
|
43
|
+
}
|
|
44
|
+
/** Hashes already checked in this process, keyed by path; a changed size or time is hashed again. */
|
|
45
|
+
const verifiedBinaries = new Map();
|
|
46
|
+
function sha256OfFile(file) {
|
|
47
|
+
const stat = statSync(file);
|
|
48
|
+
const known = verifiedBinaries.get(file);
|
|
49
|
+
if (known?.size === stat.size && known.mtimeMs === stat.mtimeMs)
|
|
50
|
+
return known.sha256;
|
|
51
|
+
const sha256 = createHash('sha256').update(readFileSync(file)).digest('hex');
|
|
52
|
+
verifiedBinaries.set(file, { size: stat.size, mtimeMs: stat.mtimeMs, sha256 });
|
|
53
|
+
return sha256;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A bundled binary runs only when the package's manifest lists it with the same SHA-256, so a
|
|
57
|
+
* damaged or replaced file is reported instead of run.
|
|
58
|
+
*/
|
|
59
|
+
function verifyPackagedBinary(packageRoot, binary) {
|
|
60
|
+
const key = `${process.platform}-${process.arch}`;
|
|
61
|
+
let manifest;
|
|
62
|
+
try {
|
|
63
|
+
manifest = engineBundleManifestSchema.parse(JSON.parse(readFileSync(engineBundleManifestPath(packageRoot), 'utf8')));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return {
|
|
67
|
+
reason: 'binary_checksum_mismatch',
|
|
68
|
+
message: `The bundled hoi4-engine for ${key} has no valid engine/bin/manifest.json to check it against`,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
const entry = manifest.binaries[key];
|
|
72
|
+
if (entry === undefined)
|
|
73
|
+
return {
|
|
74
|
+
reason: 'binary_checksum_mismatch',
|
|
75
|
+
message: `engine/bin/manifest.json lists no hoi4-engine for ${key}`,
|
|
76
|
+
};
|
|
77
|
+
let sha256;
|
|
78
|
+
try {
|
|
79
|
+
sha256 = sha256OfFile(binary);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return {
|
|
83
|
+
reason: 'binary_not_found',
|
|
84
|
+
message: `The bundled hoi4-engine for ${key} cannot be read`,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
if (sha256 !== entry.sha256)
|
|
88
|
+
return {
|
|
89
|
+
reason: 'binary_checksum_mismatch',
|
|
90
|
+
message: `The bundled hoi4-engine for ${key} does not match the SHA-256 in engine/bin/manifest.json; reinstall hoi4-agent-tools`,
|
|
91
|
+
};
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
29
94
|
/** The bundled binary's path for this platform, whether or not it exists. */
|
|
30
95
|
export function packagedEngineBinaryPath(packageRoot = defaultPackageRoot(), platform = process.platform, arch = process.arch) {
|
|
31
96
|
return path.join(packageRoot, 'engine', 'bin', `${platform}-${arch}`, platform === 'win32' ? 'hoi4-engine.exe' : 'hoi4-engine');
|
|
32
97
|
}
|
|
33
98
|
/**
|
|
34
99
|
* `HOI4_ENGINE` (an absolute path) wins; a set but unusable `HOI4_ENGINE` is reported instead of
|
|
35
|
-
* silently using the bundled binary. Otherwise the package's own `engine/bin` binary, if present
|
|
100
|
+
* silently using the bundled binary. Otherwise the package's own `engine/bin` binary, if present
|
|
101
|
+
* and matching the SHA-256 in `engine/bin/manifest.json`.
|
|
36
102
|
*/
|
|
37
103
|
export function locateEngineBinary(options = {}) {
|
|
38
104
|
const configured = (options.env ?? process.env)[ENGINE_BINARY_ENV];
|
|
@@ -49,9 +115,12 @@ export function locateEngineBinary(options = {}) {
|
|
|
49
115
|
};
|
|
50
116
|
return { path: configured, source: 'environment' };
|
|
51
117
|
}
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
118
|
+
const packageRoot = options.packageRoot ?? defaultPackageRoot();
|
|
119
|
+
const packaged = packagedEngineBinaryPath(packageRoot);
|
|
120
|
+
if (isFile(packaged)) {
|
|
121
|
+
const rejected = verifyPackagedBinary(packageRoot, packaged);
|
|
122
|
+
return rejected ?? { path: packaged, source: 'package' };
|
|
123
|
+
}
|
|
55
124
|
return {
|
|
56
125
|
reason: 'binary_not_found',
|
|
57
126
|
message: `No hoi4-engine binary for ${process.platform}-${process.arch} is installed with this package and ${ENGINE_BINARY_ENV} is not set`,
|
|
@@ -594,6 +594,20 @@ export class SymbolIndex {
|
|
|
594
594
|
for (const assignment of assignments(block)) {
|
|
595
595
|
const key = assignment.key.value;
|
|
596
596
|
if (assignment.value.type !== 'block') {
|
|
597
|
+
// An advisor's `idea_token` is the idea that `add_ideas` and `has_idea` name.
|
|
598
|
+
if (key === 'idea_token' &&
|
|
599
|
+
sourcePath.startsWith('common/characters/') &&
|
|
600
|
+
ancestors.at(-1) === 'advisor') {
|
|
601
|
+
this.addSymbol({
|
|
602
|
+
kind: 'idea',
|
|
603
|
+
id: assignment.value.value,
|
|
604
|
+
path: file.displayPath,
|
|
605
|
+
rootKind: file.rootKind,
|
|
606
|
+
loadOrder: file.loadOrder,
|
|
607
|
+
location: nodeLocation(document, assignment, assignment.value.value),
|
|
608
|
+
metadata: { advisor: true },
|
|
609
|
+
});
|
|
610
|
+
}
|
|
597
611
|
if (sourcePath.startsWith('common/script_constants/') &&
|
|
598
612
|
key !== 'schema' &&
|
|
599
613
|
!ancestors.includes('schema')) {
|
|
@@ -918,6 +932,20 @@ export class SymbolIndex {
|
|
|
918
932
|
location: nodeLocation(document, icon, id),
|
|
919
933
|
});
|
|
920
934
|
}
|
|
935
|
+
else if ((key === 'shared_focus' || key === 'joint_focus') &&
|
|
936
|
+
id !== undefined &&
|
|
937
|
+
ancestors.length === 0) {
|
|
938
|
+
// Shared and joint focuses sit outside any tree; trees add them with `shared_focus = <id>`.
|
|
939
|
+
this.addSymbol({
|
|
940
|
+
kind: 'focus',
|
|
941
|
+
id,
|
|
942
|
+
path: file.displayPath,
|
|
943
|
+
rootKind: file.rootKind,
|
|
944
|
+
loadOrder: file.loadOrder,
|
|
945
|
+
location: nodeLocation(document, assignment, id),
|
|
946
|
+
metadata: { shared: key },
|
|
947
|
+
});
|
|
948
|
+
}
|
|
921
949
|
else if (key === 'focus' && id !== undefined && ancestors.at(-1) === 'focus_tree') {
|
|
922
950
|
this.addSymbol({
|
|
923
951
|
kind: 'focus',
|
|
@@ -448,6 +448,15 @@ function buildToolResult(selected, imageCount = 0) {
|
|
|
448
448
|
...(selected.artifacts.length > shown.length
|
|
449
449
|
? { artifactsListedInStructuredContent: selected.artifacts.length }
|
|
450
450
|
: {}),
|
|
451
|
+
// Clients that show only the text still see why a check failed.
|
|
452
|
+
...(selected.validation.checks.some(({ passed }) => !passed)
|
|
453
|
+
? {
|
|
454
|
+
failedChecks: selected.validation.checks
|
|
455
|
+
.filter(({ passed }) => !passed)
|
|
456
|
+
.slice(0, 3)
|
|
457
|
+
.map(({ message }) => message.slice(0, 300)),
|
|
458
|
+
}
|
|
459
|
+
: {}),
|
|
451
460
|
...(selected.status === 'ok' || selected.blockers.length === 0
|
|
452
461
|
? {}
|
|
453
462
|
: {
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { locateEngineBinary, } from './engine-client.js';
|
|
3
|
+
/**
|
|
4
|
+
* The resident engine (`hoi4-engine serve`, ADR 0074): one long-lived engine process per server
|
|
5
|
+
* that keeps its caches between calls. Requests and responses are frames: a JSON line, then the
|
|
6
|
+
* raw bytes its `payload` field counts. Requests run in parallel inside the engine and are matched
|
|
7
|
+
* to responses by id.
|
|
8
|
+
*
|
|
9
|
+
* The process is started on first use and kept until the server exits, with no idle eviction. A
|
|
10
|
+
* crash fails the requests in flight and the next request starts a fresh process; after
|
|
11
|
+
* `RESIDENT_ENGINE_MAX_RESTARTS` crashes in a row the engine is reported unavailable.
|
|
12
|
+
*/
|
|
13
|
+
export const RESIDENT_ENGINE_PROTOCOL = 1;
|
|
14
|
+
export const RESIDENT_ENGINE_TIMEOUT_MS = 120_000;
|
|
15
|
+
export const RESIDENT_ENGINE_MAX_RESTARTS = 3;
|
|
16
|
+
/** The largest response header line; payloads are bounded by `maxPayloadBytes`. */
|
|
17
|
+
const RESIDENT_ENGINE_MAX_HEADER_BYTES = 1024 * 1024;
|
|
18
|
+
const RESIDENT_ENGINE_MAX_PAYLOAD_BYTES = 512 * 1024 * 1024;
|
|
19
|
+
const STDERR_TAIL_BYTES = 4096;
|
|
20
|
+
export class ResidentEngine {
|
|
21
|
+
options;
|
|
22
|
+
child;
|
|
23
|
+
binary;
|
|
24
|
+
pending = new Map();
|
|
25
|
+
nextId = 1;
|
|
26
|
+
buffered = [];
|
|
27
|
+
bufferedBytes = 0;
|
|
28
|
+
header;
|
|
29
|
+
stderrTail = '';
|
|
30
|
+
crashes = 0;
|
|
31
|
+
closed = false;
|
|
32
|
+
constructor(options = {}) {
|
|
33
|
+
this.options = options;
|
|
34
|
+
}
|
|
35
|
+
/** The binary in use, once a request has started the process. */
|
|
36
|
+
get location() {
|
|
37
|
+
return this.binary;
|
|
38
|
+
}
|
|
39
|
+
/** Whether a binary can be found, without starting it. */
|
|
40
|
+
available() {
|
|
41
|
+
return 'path' in locateEngineBinary(this.options);
|
|
42
|
+
}
|
|
43
|
+
async request(op, body = {}, payload, options = {}) {
|
|
44
|
+
options.signal?.throwIfAborted();
|
|
45
|
+
if (this.closed)
|
|
46
|
+
return { ok: false, kind: 'unavailable', reason: 'spawn_failed', message: 'closed' };
|
|
47
|
+
const started = this.ensureStarted();
|
|
48
|
+
if (started !== undefined)
|
|
49
|
+
return started;
|
|
50
|
+
const child = this.child;
|
|
51
|
+
const id = this.nextId++;
|
|
52
|
+
const timeoutMs = options.timeoutMs ?? RESIDENT_ENGINE_TIMEOUT_MS;
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
const entry = {
|
|
55
|
+
resolve,
|
|
56
|
+
timer: setTimeout(() => {
|
|
57
|
+
this.settle(id, {
|
|
58
|
+
ok: false,
|
|
59
|
+
kind: 'unavailable',
|
|
60
|
+
reason: 'timeout',
|
|
61
|
+
message: `hoi4-engine ${op} did not answer within ${timeoutMs} ms`,
|
|
62
|
+
});
|
|
63
|
+
}, timeoutMs),
|
|
64
|
+
};
|
|
65
|
+
if (options.signal !== undefined) {
|
|
66
|
+
const signal = options.signal;
|
|
67
|
+
entry.signal = signal;
|
|
68
|
+
entry.onAbort = () => {
|
|
69
|
+
const current = this.pending.get(id);
|
|
70
|
+
if (current === undefined)
|
|
71
|
+
return;
|
|
72
|
+
clearTimeout(current.timer);
|
|
73
|
+
this.pending.delete(id);
|
|
74
|
+
this.updateRef();
|
|
75
|
+
const reason = signal.reason;
|
|
76
|
+
reject(reason instanceof Error ? reason : new Error('The engine request was cancelled'));
|
|
77
|
+
};
|
|
78
|
+
signal.addEventListener('abort', entry.onAbort, { once: true });
|
|
79
|
+
}
|
|
80
|
+
this.pending.set(id, entry);
|
|
81
|
+
this.updateRef();
|
|
82
|
+
const line = `${JSON.stringify({ ...body, id, op, payload: payload?.length ?? 0 })}\n`;
|
|
83
|
+
child.stdin.write(line);
|
|
84
|
+
if (payload !== undefined && payload.length > 0)
|
|
85
|
+
child.stdin.write(payload);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** Stops the process; requests in flight fail as unavailable. */
|
|
89
|
+
close() {
|
|
90
|
+
this.closed = true;
|
|
91
|
+
this.stop('the resident engine was closed');
|
|
92
|
+
}
|
|
93
|
+
ensureStarted() {
|
|
94
|
+
if (this.child !== undefined)
|
|
95
|
+
return undefined;
|
|
96
|
+
if (this.crashes >= RESIDENT_ENGINE_MAX_RESTARTS)
|
|
97
|
+
return {
|
|
98
|
+
ok: false,
|
|
99
|
+
kind: 'unavailable',
|
|
100
|
+
reason: 'exit_status',
|
|
101
|
+
message: `hoi4-engine serve stopped ${this.crashes} times in a row: ${this.stderrTail.trim().slice(-300)}`,
|
|
102
|
+
};
|
|
103
|
+
const located = locateEngineBinary(this.options);
|
|
104
|
+
if (!('path' in located))
|
|
105
|
+
return { ok: false, kind: 'unavailable', reason: located.reason, message: located.message };
|
|
106
|
+
this.binary = located;
|
|
107
|
+
// A JavaScript engine (a development wrapper or a test double) runs under this Node.
|
|
108
|
+
const script = /\.(?:c|m)?js$/iu.test(located.path);
|
|
109
|
+
let child;
|
|
110
|
+
try {
|
|
111
|
+
child = spawn(script ? process.execPath : located.path, script ? [located.path, 'serve'] : ['serve'], {
|
|
112
|
+
shell: false,
|
|
113
|
+
windowsHide: true,
|
|
114
|
+
env: this.options.env ?? process.env,
|
|
115
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
return {
|
|
120
|
+
ok: false,
|
|
121
|
+
kind: 'unavailable',
|
|
122
|
+
reason: 'spawn_failed',
|
|
123
|
+
message: error instanceof Error ? error.message : String(error),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
this.child = child;
|
|
127
|
+
this.buffered = [];
|
|
128
|
+
this.bufferedBytes = 0;
|
|
129
|
+
this.header = undefined;
|
|
130
|
+
child.stdout.on('data', (chunk) => this.onData(child, chunk));
|
|
131
|
+
child.stderr.on('data', (chunk) => {
|
|
132
|
+
this.stderrTail = `${this.stderrTail}${chunk.toString('utf8')}`.slice(-STDERR_TAIL_BYTES);
|
|
133
|
+
});
|
|
134
|
+
child.stdin.on('error', () => undefined);
|
|
135
|
+
child.on('error', (error) => this.onExit(child, `hoi4-engine serve failed: ${error.message}`));
|
|
136
|
+
child.on('close', (code, signal) => this.onExit(child, `hoi4-engine serve exited with ${code === null ? `signal ${signal ?? 'unknown'}` : `code ${code}`}`));
|
|
137
|
+
this.updateRef();
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
/** Keeps Node alive only while a request waits, so an idle engine never holds the server open. */
|
|
141
|
+
updateRef() {
|
|
142
|
+
const child = this.child;
|
|
143
|
+
if (child === undefined)
|
|
144
|
+
return;
|
|
145
|
+
const waiting = this.pending.size > 0;
|
|
146
|
+
if (waiting)
|
|
147
|
+
child.ref();
|
|
148
|
+
else
|
|
149
|
+
child.unref();
|
|
150
|
+
// The pipes are sockets at run time, which Node's stream types do not say.
|
|
151
|
+
for (const stream of [child.stdout, child.stderr, child.stdin]) {
|
|
152
|
+
const socket = stream;
|
|
153
|
+
if (waiting)
|
|
154
|
+
socket.ref?.();
|
|
155
|
+
else
|
|
156
|
+
socket.unref?.();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
take(bytes) {
|
|
160
|
+
const all = this.buffered.length === 1 ? this.buffered[0] : Buffer.concat(this.buffered);
|
|
161
|
+
const head = all.subarray(0, bytes);
|
|
162
|
+
const rest = all.subarray(bytes);
|
|
163
|
+
this.buffered = rest.length === 0 ? [] : [rest];
|
|
164
|
+
this.bufferedBytes = rest.length;
|
|
165
|
+
return head;
|
|
166
|
+
}
|
|
167
|
+
onData(child, chunk) {
|
|
168
|
+
if (child !== this.child)
|
|
169
|
+
return;
|
|
170
|
+
this.buffered.push(chunk);
|
|
171
|
+
this.bufferedBytes += chunk.length;
|
|
172
|
+
for (;;) {
|
|
173
|
+
if (this.header === undefined) {
|
|
174
|
+
const all = this.buffered.length === 1 ? this.buffered[0] : Buffer.concat(this.buffered);
|
|
175
|
+
this.buffered = all.length === 0 ? [] : [all];
|
|
176
|
+
const newline = all.indexOf(0x0a);
|
|
177
|
+
if (newline < 0) {
|
|
178
|
+
if (all.length > RESIDENT_ENGINE_MAX_HEADER_BYTES)
|
|
179
|
+
this.stop('hoi4-engine serve printed an oversized response header');
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const line = this.take(newline + 1).toString('utf8');
|
|
183
|
+
let body;
|
|
184
|
+
try {
|
|
185
|
+
body = JSON.parse(line);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
this.stop('hoi4-engine serve printed a response that is not JSON');
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
const id = typeof body.id === 'number' ? body.id : -1;
|
|
192
|
+
const payload = body.ok === true && typeof body.payload === 'number' ? body.payload : 0;
|
|
193
|
+
if (!Number.isSafeInteger(payload) ||
|
|
194
|
+
payload < 0 ||
|
|
195
|
+
payload > RESIDENT_ENGINE_MAX_PAYLOAD_BYTES) {
|
|
196
|
+
this.stop('hoi4-engine serve announced an invalid payload size');
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
this.header = { id, body, payload };
|
|
200
|
+
}
|
|
201
|
+
const header = this.header;
|
|
202
|
+
if (this.bufferedBytes < header.payload)
|
|
203
|
+
return;
|
|
204
|
+
const payload = header.payload === 0 ? Buffer.alloc(0) : Buffer.from(this.take(header.payload));
|
|
205
|
+
this.header = undefined;
|
|
206
|
+
this.crashes = 0;
|
|
207
|
+
const body = header.body;
|
|
208
|
+
if (body.ok === true) {
|
|
209
|
+
const result = typeof body.result === 'object' && body.result !== null
|
|
210
|
+
? body.result
|
|
211
|
+
: {};
|
|
212
|
+
this.settle(header.id, { ok: true, response: { result, payload } });
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
const error = typeof body.error === 'object' && body.error !== null
|
|
216
|
+
? body.error
|
|
217
|
+
: {};
|
|
218
|
+
const { code, message, ...details } = error;
|
|
219
|
+
this.settle(header.id, {
|
|
220
|
+
ok: false,
|
|
221
|
+
kind: 'error',
|
|
222
|
+
code: typeof code === 'string' ? code : 'error',
|
|
223
|
+
message: typeof message === 'string' ? message : 'the engine reported an error',
|
|
224
|
+
details,
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
settle(id, outcome) {
|
|
230
|
+
const entry = this.pending.get(id);
|
|
231
|
+
if (entry === undefined)
|
|
232
|
+
return;
|
|
233
|
+
clearTimeout(entry.timer);
|
|
234
|
+
if (entry.onAbort !== undefined)
|
|
235
|
+
entry.signal?.removeEventListener('abort', entry.onAbort);
|
|
236
|
+
this.pending.delete(id);
|
|
237
|
+
this.updateRef();
|
|
238
|
+
entry.resolve(outcome);
|
|
239
|
+
}
|
|
240
|
+
onExit(child, message) {
|
|
241
|
+
if (child !== this.child)
|
|
242
|
+
return;
|
|
243
|
+
this.child = undefined;
|
|
244
|
+
if (!this.closed)
|
|
245
|
+
this.crashes += 1;
|
|
246
|
+
this.failAll(`${message}${this.stderrTail.trim() === '' ? '' : `: ${this.stderrTail.trim().slice(-300)}`}`);
|
|
247
|
+
}
|
|
248
|
+
stop(message) {
|
|
249
|
+
const child = this.child;
|
|
250
|
+
this.child = undefined;
|
|
251
|
+
if (child !== undefined) {
|
|
252
|
+
if (!this.closed)
|
|
253
|
+
this.crashes += 1;
|
|
254
|
+
child.kill();
|
|
255
|
+
}
|
|
256
|
+
this.failAll(message);
|
|
257
|
+
}
|
|
258
|
+
failAll(message) {
|
|
259
|
+
for (const id of [...this.pending.keys()])
|
|
260
|
+
this.settle(id, { ok: false, kind: 'unavailable', reason: 'exit_status', message });
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
let shared;
|
|
264
|
+
/** The server-wide resident engine (one process per server). */
|
|
265
|
+
export function sharedResidentEngine() {
|
|
266
|
+
shared ??= new ResidentEngine();
|
|
267
|
+
return shared;
|
|
268
|
+
}
|
|
269
|
+
/** Test hook: replaces the shared engine and closes the old one. */
|
|
270
|
+
export function replaceSharedResidentEngine(engine) {
|
|
271
|
+
shared?.close();
|
|
272
|
+
shared = engine;
|
|
273
|
+
}
|
|
@@ -167,7 +167,7 @@ export async function sweepTemporaryDirectories(parent, options = {}) {
|
|
|
167
167
|
continue;
|
|
168
168
|
await lock.close();
|
|
169
169
|
lock = undefined;
|
|
170
|
-
await rm(entry.directory, { recursive: true, force: true });
|
|
170
|
+
await rm(entry.directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
|
|
171
171
|
retainedBytes -= entry.bytes;
|
|
172
172
|
removed += 1;
|
|
173
173
|
}
|
|
@@ -265,7 +265,8 @@ export class TemporaryDirectoryLifetime {
|
|
|
265
265
|
}
|
|
266
266
|
if ((await lstat(directory)).isSymbolicLink() || (await realpath(directory)) !== directory)
|
|
267
267
|
throw new Error('Temporary directory changed before cleanup');
|
|
268
|
-
|
|
268
|
+
// Windows can hold a file a closed process wrote for a moment (ENOTEMPTY, EBUSY).
|
|
269
|
+
await rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
|
|
269
270
|
this.#owned.delete(directory);
|
|
270
271
|
this.#forgetFiles(directory);
|
|
271
272
|
}
|