hoi4-agent-tools 4.6.5 → 4.8.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 +40 -5
- package/README.md +32 -13
- package/dist/hoi4_agent_tools/core/engine-client.js +342 -0
- package/dist/hoi4_agent_tools/core/operation-result.js +33 -5
- 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 +7 -0
- package/dist/hoi4_agent_tools/event/service.js +18 -6
- package/dist/hoi4_agent_tools/event/summary.js +9 -0
- package/dist/hoi4_agent_tools/focus/compact.js +197 -18
- package/dist/hoi4_agent_tools/focus/engine-layout.js +201 -0
- 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/job-operations.js +3 -1
- package/dist/hoi4_agent_tools/focus/layout.js +3 -2
- package/dist/hoi4_agent_tools/focus/native-effects.js +4 -4
- package/dist/hoi4_agent_tools/focus/quality/branches.js +32 -0
- package/dist/hoi4_agent_tools/focus/quality/calibration.js +364 -0
- package/dist/hoi4_agent_tools/focus/quality/delta.js +85 -0
- package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +2265 -0
- package/dist/hoi4_agent_tools/focus/quality/graph.js +170 -0
- package/dist/hoi4_agent_tools/focus/quality/index.js +24 -0
- package/dist/hoi4_agent_tools/focus/quality/inline-images.js +132 -0
- package/dist/hoi4_agent_tools/focus/quality/metrics.js +424 -0
- package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +213 -0
- package/dist/hoi4_agent_tools/focus/quality/positions.js +41 -0
- package/dist/hoi4_agent_tools/focus/quality/schematic.js +243 -0
- package/dist/hoi4_agent_tools/focus/quality/scorecard.js +549 -0
- package/dist/hoi4_agent_tools/focus/quality/stored-calibration.js +7 -0
- package/dist/hoi4_agent_tools/focus/quality/tool-output.js +113 -0
- package/dist/hoi4_agent_tools/focus/quality/types.js +5 -0
- package/dist/hoi4_agent_tools/focus/render.js +21 -9
- package/dist/hoi4_agent_tools/focus/tool-operations.js +364 -25
- package/dist/hoi4_agent_tools/focus/tool-support.js +1 -1
- 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/localisation/inspect.js +34 -0
- package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
- package/dist/hoi4_agent_tools/mcp/server/instructions.js +1 -1
- package/dist/hoi4_agent_tools/mcp/tools/event.js +2 -0
- package/dist/hoi4_agent_tools/mcp/tools/focus.js +76 -4
- package/dist/hoi4_agent_tools/mcp/tools/reference.js +18 -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 +24 -0
- package/dist/hoi4_agent_tools/reference/game-text.js +109 -0
- 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 +68 -2
- package/dist/hoi4_agent_tools/reference/ranking.js +92 -2
- package/dist/hoi4_agent_tools/reference/script-validation.js +46 -6
- package/dist/hoi4_agent_tools/reference/service.js +125 -21
- package/dist/hoi4_agent_tools/reference/source-lookup.js +8 -0
- package/dist/hoi4_agent_tools/schemas/focus-requests.js +68 -7
- package/dist/hoi4_agent_tools/schemas/focus.js +121 -6
- 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/mod-tools.js +11 -0
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +17 -17
- package/docs/focus.md +104 -4
- package/docs/reference.md +1 -1
- package/docs/research/reference-benchmark.md +152 -1
- package/docs/setup.md +1 -1
- package/docs/tools.md +48 -44
- package/docs/troubleshooting.md +13 -12
- package/engine/README.md +284 -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 +5 -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 +146 -120
- package/schemas/focus-planning-sidecar.schema.json +15 -7
- 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 +1 -1
- 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,45 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 4.8.0 - 2026-11-05
|
|
6
|
+
|
|
7
|
+
- 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.
|
|
8
|
+
- 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.
|
|
9
|
+
- 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.
|
|
10
|
+
- 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.
|
|
11
|
+
- 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.
|
|
12
|
+
- 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.
|
|
13
|
+
- 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.
|
|
14
|
+
- 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.
|
|
15
|
+
- 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.
|
|
16
|
+
- 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.
|
|
17
|
+
- 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).
|
|
18
|
+
- `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.
|
|
19
|
+
- `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).
|
|
20
|
+
- 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)
|
|
21
|
+
- 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)
|
|
22
|
+
- `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).
|
|
23
|
+
- 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).
|
|
24
|
+
- `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).
|
|
25
|
+
- 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.
|
|
26
|
+
|
|
27
|
+
## 4.7.0 - 2026-11-02
|
|
28
|
+
|
|
29
|
+
- 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.
|
|
30
|
+
- Add the Rust focus-tree layout engine `hoi4-focus-layout` (`engine/crates/focus`) and `hoi4-engine focus-layout`: JSON in, JSON out. `layout` places `auto` focuses with a layered median layout, symmetric sibling spreads, an order-preserving least-squares row projection, exclusive partners side by side and lanes packed as bands; `insert` places a new branch among focuses that keep their coordinates exactly, choosing the offset with the fewest new crossings in the orthogonal connector model, and proposes or applies the smallest corridor shift when boxed in. Integer-only placement, hashes over the layout, the untouched focuses and the relations, and golden responses identical on every platform. No MCP tool uses it yet, and the npm package is unchanged.
|
|
31
|
+
- Add a sprite index and a content-to-sprite trace to the shared Rust engine (`engine/`), and the `hoi4-engine sprites` command. The index covers every `spriteType`, `frameAnimatedSpriteType`, `corneredTileSpriteType` and `textSpriteType` in `interface/**/*.gfx` across the game, DLC folders and mods in load order (name, texturefile, `noOfFrames`, `effectFile`, `legacy_lazy_load`, `loadType`, animation blocks, location), resolves each texture without regard to case with mod overrides and `replace_path`, and reads DDS (including DX10), TGA and PNG headers without decoding pixels. The trace names the sprite and asset family (41 family ids) that focus, idea, character, decision, dynamic modifier, MIO, balance of power, special project, operation, intelligence agency, raid, medal, faction, doctrine, technology and event content shows, with the implicit prefixing rules checked against the installed 1.19.4.1 game. New findings `GFX-FAMILY-REUSE`, `GFX-TEXTURE-MISSING`, `GFX-SPRITE-UNDEFINED` and `GFX-FOCUS-SHINE-MISSING`, with a per-mod allowlist. HOI4 Factory's image tools and the planned GFX validation can depend on the crates from Git. No MCP tool uses it yet and the npm package is unchanged.
|
|
32
|
+
- Find more documentation answers first from plain-word questions (ADR 0076). Command entries also match the words of their in-game tooltip or modifier name, read from the installed game's English localisation, and a question that starts with "check" prefers triggers while one that starts with an action verb prefers effects over triggers, on actions and dynamic variables. On 40 blind test questions on HOI4 1.19.4.1, 21 rather than 16 answers rank first; exact names stay first. A warm `hoi4.reference_search` no longer rereads and hashes every documentation file whose size and times are unchanged.
|
|
33
|
+
- Score the reference discovery benchmark on the refreshed wiki snapshot, whose pages are now named `event_modding.md`; the old names made every wiki answer a miss. Add held-out (`--held-out`) and blind test (`--test`) question sets. A trial of added player vocabulary did not help held-out questions and was reverted (amendment to ADR 0040).
|
|
34
|
+
- Read the kit's wiki from `hoi4_wiki/` in a mod, falling back to the older `paradox_wiki/` for a mod the kit has not updated (`hoi4_wiki/` wins when both exist). The reference tools label its hits "HOI4 wiki (kit)" instead of "Offline Paradox Wiki snapshot". An explicit `wikiRoot` is unchanged.
|
|
35
|
+
- Add the shared Rust HOI4 engine in `engine/` (ADR 0074): a lossless parser that round-trips all 7,717 vanilla 1.19.3.0 script and localisation files byte for byte, a symbol index over the game, DLC folders, dependencies and the mod in load order, a reference closure that reports every reference as resolved, unresolved or unknown with coverage per kind, lints whose vocabulary is read from the installed game's documentation, an override and `replace_path` audit that reports dropped definitions and `on_actions` hooks, a findings baseline that fails only on new findings, and the `hoi4-engine` command for the modding kit's `check.py`. Harvested from Hagane Studio with written permission: span repair plans, finding deltas, the dead-flag and DLC rules and a draw.io focus importer (`engine/PROVENANCE.md`). The CWTools MD Edition spike is in `docs/research/cwtools-md-edition-spike.md`. No MCP tool uses the engine yet, and the npm package is unchanged.
|
|
36
|
+
- Add a layout verdict to `hoi4.focus_inspect`, `hoi4.focus_render` and `hoi4.focus_rewrite` (ADR 0075). Each result now carries `layoutQuality`: a verdict (`pass`, `review`, `revise`, `blocked`), a score, a scorecard of hard defects (H1 to H5), soft metrics (S1 to S11) and design flags (D1 to D4) with limits calibrated on the installed game's 67 national focus trees, a fix for each failing row, `nextActions` and what was not evaluated. `validation.passed` stays the structural answer; the new check `focus-layout-verdict` and the diagnostic `FOCUS_LAYOUT_VERDICT_*` carry the layout one, and the structural message no longer says the layout is fine. `hoi4.focus_rewrite` and `previous` on `hoi4.focus_inspect` add `layoutDelta` (verdicts, scores, moved focuses, an unmoved hash, prerequisite and exclusion hashes). The metrics work for fixed, relative and automatic positions alike. Limits live in `src/hoi4_agent_tools/focus/quality/focus-quality-calibration.json`; `npm run focus:calibrate` recomputes them and a local test fails when they drift from the installed game.
|
|
37
|
+
- Count crossings, connectors through plaques and shared bars in the in-game right-angle connector model, with all-to-all bundles and OR groups as one bar, instead of the curved model of the icon render (advisory until confirmed in the game). The inline results no longer list `FOCUS_LAYOUT_CONNECTOR_CROSSING_UNSATISFIED`, `FOCUS_AVOIDABLE_CONNECTOR_CROSSING` or `FOCUS_LAYOUT_CONNECTOR_THROUGH_NODE`; the linked artifact keeps them.
|
|
38
|
+
- Make the compact gate compare with the layout in place. A reflow that is no worse in the in-game model (hard errors, spacing, crossings, connectors through plaques, centring, layout verdict) is accepted, so a tree with an all-to-all bundle is no longer refused. When the layout already has the verdict `pass`, or no candidate beats it, `hoi4.focus_rewrite` leaves the source alone and returns `compactOutcome` (`verdict_pass`, `no_better_candidate`, `candidates_regress`, `blockedBy`) with the info diagnostic `FOCUS_COMPACT_NOTHING_TO_IMPROVE`. `FOCUS_COMPACT_QUALITY_BLOCKED` for a new tree lists the blocking items with values and remedies in `details.blocking`.
|
|
39
|
+
- Return the render inline. `hoi4.focus_render` adds an in-game-style schematic overview and up to five close-ups (the worst places, or `cropBranchIds` and `cropFocusIds`) as image content blocks; `inline: false` skips them. New optional fields `cropBranchIds` and `inline`; `data.inlineImages` lists the images.
|
|
40
|
+
- Rewrite the focus tool descriptions and the server instruction around the workflow (lanes, automatic positions, render and look, verdict, revise one branch) and describe `position.mode`, `preferredX`, `preferredY`, `branchId` and `laneId` in the plan schema. Public schema change: additive output fields and two optional render inputs (minor version at release; the schemas are regenerated).
|
|
41
|
+
- Raise the pinned overrides of three transitive dependencies to their fixed releases, clearing every `npm audit --omit=dev` advisory: `fast-uri` 3.1.9 (GHSA-w74x-v6f9-j3xg, GHSA-xhq7-xmqj-769h, GHSA-wjr9-j795-jxcr, GHSA-333x-w4r6-6crp), `hono` 4.13.13 (GHSA-5r4p-p66f-jhc7) and `ip-address` 10.7.4 (GHSA-rxp7-6hxx-x8q5). No source or schema change.
|
|
42
|
+
|
|
3
43
|
## 4.6.5 - 2026-11-01
|
|
4
44
|
|
|
5
45
|
- Say how much a map rewrite changed when its file list is cut. The inline result lists at most a bounded number of changed files, so a world write of thousands of files could read as if little or nothing changed. Every applied map rewrite now adds `data.changedSummary`: the total of changed files, how many were created, removed and modified, and the same counts for the 40 folders with the most changes (two levels deep, largest first, `omittedFolders` for the rest). The full list stays in the transaction artifacts.
|
|
@@ -19,11 +59,6 @@
|
|
|
19
59
|
|
|
20
60
|
- Check the points of workspace countries together and give each capital a province (ADR 0073). `create_world` now reports every capital or seed that lies outside the world or in water (with the nearest land), in the unowned area, an own exclusion or another realm's claim, or within 10 pixels of a point of another realm, in one error (`MAP_WORLD_REALM_POINTS_INVALID`, `details.problems`; a single problem keeps its own code), before the relief synthesis starts. `create_world.synthesisCheck` runs the same check and lists the points beside the failing rivers (`data.synthesisCheck.realmPoints`). In the feature-aware partition every capital and seed is a province seed of its own, so capitals that are 20 to 40 pixels apart no longer fail with `MAP_WORLD_REALM_POINT_CONFLICT`. Feature-aware worlds with workspace countries get a slightly different province partition; other worlds are unchanged.
|
|
21
61
|
|
|
22
|
-
## Unreleased
|
|
23
|
-
|
|
24
|
-
- Add the shared Rust HOI4 engine in `engine/` (ADR 0074): a lossless parser that round-trips all 7,717 vanilla 1.19.3.0 script and localisation files byte for byte, a symbol index over the game, DLC folders, dependencies and the mod in load order, a reference closure that reports every reference as resolved, unresolved or unknown with coverage per kind, lints whose vocabulary is read from the installed game's documentation, an override and `replace_path` audit that reports dropped definitions and `on_actions` hooks, a findings baseline that fails only on new findings, and the `hoi4-engine` command for the modding kit's `check.py`. Harvested from Hagane Studio with written permission: span repair plans, finding deltas, the dead-flag and DLC rules and a draw.io focus importer (`engine/PROVENANCE.md`). The CWTools MD Edition spike is in `docs/research/cwtools-md-edition-spike.md`. No MCP tool uses the engine yet, and the npm package is unchanged.
|
|
25
|
-
- Raise the pinned overrides of three transitive dependencies to their fixed releases, clearing every `npm audit --omit=dev` advisory: `fast-uri` 3.1.9 (GHSA-w74x-v6f9-j3xg, GHSA-xhq7-xmqj-769h, GHSA-wjr9-j795-jxcr, GHSA-333x-w4r6-6crp), `hono` 4.13.13 (GHSA-5r4p-p66f-jhc7) and `ip-address` 10.7.4 (GHSA-rxp7-6hxx-x8q5). No source or schema change.
|
|
26
|
-
|
|
27
62
|
## 4.6.1 - 2026-10-26
|
|
28
63
|
|
|
29
64
|
- Stop flagging `constant:<category>.<key>` script-constant reads as scoped temporary-variable reads (`KNOWN_MISTAKE_TEMP_VARIABLE_SCOPE_PREFIX`).
|
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
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { z } from 'zod/v4';
|
|
7
|
+
/**
|
|
8
|
+
* Client for the shared Rust engine (`hoi4-engine`, ADR 0074). It runs the binary with a JSON
|
|
9
|
+
* request on stdin and validates the JSON it prints. A missing binary, a crash, a timeout or
|
|
10
|
+
* output that does not match the schema is reported as `available: false` with a reason; the
|
|
11
|
+
* caller decides what to tell the agent. Nothing here falls back to a TypeScript implementation.
|
|
12
|
+
*/
|
|
13
|
+
export const ENGINE_BINARY_ENV = 'HOI4_ENGINE';
|
|
14
|
+
export const ENGINE_DEFAULT_TIMEOUT_MS = 30_000;
|
|
15
|
+
export const ENGINE_DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
|
|
16
|
+
const ENGINE_STDERR_TAIL_BYTES = 4096;
|
|
17
|
+
const ENGINE_REASON_TEXT_LIMIT = 300;
|
|
18
|
+
function defaultPackageRoot() {
|
|
19
|
+
// src/hoi4_agent_tools/core and dist/hoi4_agent_tools/core both sit three levels below the root.
|
|
20
|
+
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
|
|
21
|
+
}
|
|
22
|
+
function isFile(candidate) {
|
|
23
|
+
try {
|
|
24
|
+
return statSync(candidate).isFile();
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return false;
|
|
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
|
+
}
|
|
94
|
+
/** The bundled binary's path for this platform, whether or not it exists. */
|
|
95
|
+
export function packagedEngineBinaryPath(packageRoot = defaultPackageRoot(), platform = process.platform, arch = process.arch) {
|
|
96
|
+
return path.join(packageRoot, 'engine', 'bin', `${platform}-${arch}`, platform === 'win32' ? 'hoi4-engine.exe' : 'hoi4-engine');
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* `HOI4_ENGINE` (an absolute path) wins; a set but unusable `HOI4_ENGINE` is reported instead of
|
|
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`.
|
|
102
|
+
*/
|
|
103
|
+
export function locateEngineBinary(options = {}) {
|
|
104
|
+
const configured = (options.env ?? process.env)[ENGINE_BINARY_ENV];
|
|
105
|
+
if (configured !== undefined && configured !== '') {
|
|
106
|
+
if (!path.isAbsolute(configured))
|
|
107
|
+
return {
|
|
108
|
+
reason: 'binary_path_invalid',
|
|
109
|
+
message: `${ENGINE_BINARY_ENV} must be an absolute path to the hoi4-engine binary`,
|
|
110
|
+
};
|
|
111
|
+
if (!isFile(configured))
|
|
112
|
+
return {
|
|
113
|
+
reason: 'binary_not_found',
|
|
114
|
+
message: `${ENGINE_BINARY_ENV} names a file that does not exist`,
|
|
115
|
+
};
|
|
116
|
+
return { path: configured, source: 'environment' };
|
|
117
|
+
}
|
|
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
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
reason: 'binary_not_found',
|
|
126
|
+
message: `No hoi4-engine binary for ${process.platform}-${process.arch} is installed with this package and ${ENGINE_BINARY_ENV} is not set`,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function clip(text) {
|
|
130
|
+
const single = text.replace(/\s+/gu, ' ').trim();
|
|
131
|
+
return single.length <= ENGINE_REASON_TEXT_LIMIT
|
|
132
|
+
? single
|
|
133
|
+
: `${single.slice(0, ENGINE_REASON_TEXT_LIMIT)}…`;
|
|
134
|
+
}
|
|
135
|
+
function runProcess(binary, args, input, env, timeoutMs, maxOutputBytes, signal) {
|
|
136
|
+
// A JavaScript engine (a development wrapper or a test double) runs under this Node, still
|
|
137
|
+
// without a shell, because Windows cannot execute a script file directly.
|
|
138
|
+
const script = /\.(?:c|m)?js$/iu.test(binary);
|
|
139
|
+
const command = script ? process.execPath : binary;
|
|
140
|
+
const commandArgs = script ? [binary, ...args] : [...args];
|
|
141
|
+
return new Promise((resolve, reject) => {
|
|
142
|
+
let settled = false;
|
|
143
|
+
let stdoutBytes = 0;
|
|
144
|
+
const stdout = [];
|
|
145
|
+
let stderr = Buffer.alloc(0);
|
|
146
|
+
let ending;
|
|
147
|
+
const child = spawn(command, commandArgs, {
|
|
148
|
+
shell: false,
|
|
149
|
+
windowsHide: true,
|
|
150
|
+
env,
|
|
151
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
152
|
+
});
|
|
153
|
+
const stop = (kind) => {
|
|
154
|
+
ending ??= kind;
|
|
155
|
+
child.kill();
|
|
156
|
+
};
|
|
157
|
+
const timer = setTimeout(() => stop('timeout'), timeoutMs);
|
|
158
|
+
const onAbort = () => {
|
|
159
|
+
if (settled)
|
|
160
|
+
return;
|
|
161
|
+
settled = true;
|
|
162
|
+
clearTimeout(timer);
|
|
163
|
+
child.kill();
|
|
164
|
+
const reason = signal?.reason;
|
|
165
|
+
reject(reason instanceof Error ? reason : new Error('The engine call was cancelled'));
|
|
166
|
+
};
|
|
167
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
168
|
+
const finish = (outcome) => {
|
|
169
|
+
if (settled)
|
|
170
|
+
return;
|
|
171
|
+
settled = true;
|
|
172
|
+
clearTimeout(timer);
|
|
173
|
+
signal?.removeEventListener('abort', onAbort);
|
|
174
|
+
resolve(outcome);
|
|
175
|
+
};
|
|
176
|
+
child.stdout.on('data', (chunk) => {
|
|
177
|
+
stdoutBytes += chunk.length;
|
|
178
|
+
if (stdoutBytes > maxOutputBytes)
|
|
179
|
+
stop('output_too_large');
|
|
180
|
+
else
|
|
181
|
+
stdout.push(chunk);
|
|
182
|
+
});
|
|
183
|
+
child.stderr.on('data', (chunk) => {
|
|
184
|
+
stderr = Buffer.concat([stderr, chunk]);
|
|
185
|
+
if (stderr.length > ENGINE_STDERR_TAIL_BYTES)
|
|
186
|
+
stderr = stderr.subarray(stderr.length - ENGINE_STDERR_TAIL_BYTES);
|
|
187
|
+
});
|
|
188
|
+
child.on('error', (error) => finish({
|
|
189
|
+
kind: 'spawn_failed',
|
|
190
|
+
code: null,
|
|
191
|
+
signal: null,
|
|
192
|
+
stdout: Buffer.alloc(0),
|
|
193
|
+
stderrTail: '',
|
|
194
|
+
error: error.message,
|
|
195
|
+
}));
|
|
196
|
+
child.on('close', (code, exitSignal) => finish({
|
|
197
|
+
kind: ending ?? 'exited',
|
|
198
|
+
code,
|
|
199
|
+
signal: exitSignal,
|
|
200
|
+
stdout: Buffer.concat(stdout),
|
|
201
|
+
stderrTail: stderr.toString('utf8'),
|
|
202
|
+
}));
|
|
203
|
+
// The engine may exit before reading all of stdin (for example on a usage error).
|
|
204
|
+
child.stdin.on('error', () => undefined);
|
|
205
|
+
child.stdin.end(input, 'utf8');
|
|
206
|
+
if (signal?.aborted === true)
|
|
207
|
+
onAbort();
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
const engineInvalidSchema = z
|
|
211
|
+
.object({
|
|
212
|
+
schema: z.string(),
|
|
213
|
+
status: z.literal('invalid'),
|
|
214
|
+
error: z.object({ code: z.string(), message: z.string() }).strict(),
|
|
215
|
+
})
|
|
216
|
+
.strict();
|
|
217
|
+
/** Run one engine subcommand with a JSON request and validate its JSON response. */
|
|
218
|
+
export async function runEngineCommand(subcommand, request, responseSchema, options = {}) {
|
|
219
|
+
options.signal?.throwIfAborted();
|
|
220
|
+
const located = locateEngineBinary(options);
|
|
221
|
+
if (!('path' in located))
|
|
222
|
+
return {
|
|
223
|
+
available: false,
|
|
224
|
+
outcome: 'unavailable',
|
|
225
|
+
reason: located.reason,
|
|
226
|
+
message: located.message,
|
|
227
|
+
};
|
|
228
|
+
const binary = located;
|
|
229
|
+
const unavailable = (reason, message) => ({
|
|
230
|
+
available: false,
|
|
231
|
+
outcome: 'unavailable',
|
|
232
|
+
reason,
|
|
233
|
+
message,
|
|
234
|
+
binary,
|
|
235
|
+
});
|
|
236
|
+
const timeoutMs = options.timeoutMs ?? ENGINE_DEFAULT_TIMEOUT_MS;
|
|
237
|
+
const outcome = await runProcess(binary.path, [subcommand], JSON.stringify(request), options.env ?? process.env, timeoutMs, options.maxOutputBytes ?? ENGINE_DEFAULT_MAX_OUTPUT_BYTES, options.signal);
|
|
238
|
+
if (outcome.kind === 'spawn_failed')
|
|
239
|
+
return unavailable('spawn_failed', `hoi4-engine could not start: ${clip(outcome.error ?? '')}`);
|
|
240
|
+
if (outcome.kind === 'timeout')
|
|
241
|
+
return unavailable('timeout', `hoi4-engine ${subcommand} did not finish within ${timeoutMs} ms`);
|
|
242
|
+
if (outcome.kind === 'output_too_large')
|
|
243
|
+
return unavailable('output_too_large', `hoi4-engine ${subcommand} printed more than ${options.maxOutputBytes ?? ENGINE_DEFAULT_MAX_OUTPUT_BYTES} bytes`);
|
|
244
|
+
let parsed;
|
|
245
|
+
try {
|
|
246
|
+
parsed = JSON.parse(outcome.stdout.toString('utf8'));
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
parsed = undefined;
|
|
250
|
+
}
|
|
251
|
+
if (outcome.code === 2) {
|
|
252
|
+
const invalid = engineInvalidSchema.safeParse(parsed);
|
|
253
|
+
if (invalid.success)
|
|
254
|
+
return { available: true, outcome: 'invalid_request', binary, error: invalid.data.error };
|
|
255
|
+
}
|
|
256
|
+
if (outcome.code !== 0)
|
|
257
|
+
return unavailable('exit_status', `hoi4-engine ${subcommand} exited with ${outcome.code === null ? `signal ${outcome.signal ?? 'unknown'}` : `code ${outcome.code}`}${outcome.stderrTail.trim() === '' ? '' : `: ${clip(outcome.stderrTail)}`}`);
|
|
258
|
+
if (parsed === undefined)
|
|
259
|
+
return unavailable('invalid_output', `hoi4-engine ${subcommand} did not print JSON`);
|
|
260
|
+
const response = responseSchema.safeParse(parsed);
|
|
261
|
+
if (!response.success)
|
|
262
|
+
return unavailable('invalid_output', `hoi4-engine ${subcommand} printed a response that does not match its schema: ${clip(response.error.issues
|
|
263
|
+
.slice(0, 3)
|
|
264
|
+
.map((issue) => `${issue.path.join('.') || '(root)'} ${issue.message}`)
|
|
265
|
+
.join('; '))}`);
|
|
266
|
+
return { available: true, outcome: 'response', binary, response: response.data };
|
|
267
|
+
}
|
|
268
|
+
// ---------------------------------------------------------------------------------------------
|
|
269
|
+
// focus-layout (engine/crates/focus/schemas/*.json)
|
|
270
|
+
export const FOCUS_LAYOUT_REQUEST_SCHEMA = 'hoi4-focus-layout-request/1';
|
|
271
|
+
export const FOCUS_LAYOUT_RESPONSE_SCHEMA = 'hoi4-focus-layout/1';
|
|
272
|
+
const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/u);
|
|
273
|
+
const shiftSchema = z
|
|
274
|
+
.object({
|
|
275
|
+
fromX: z.number().int(),
|
|
276
|
+
columns: z.number().int().min(1),
|
|
277
|
+
direction: z.enum(['right', 'left']),
|
|
278
|
+
focusIds: z.array(z.string()),
|
|
279
|
+
})
|
|
280
|
+
.strict();
|
|
281
|
+
export const focusLayoutEngineResponseSchema = z
|
|
282
|
+
.object({
|
|
283
|
+
schema: z.literal(FOCUS_LAYOUT_RESPONSE_SCHEMA),
|
|
284
|
+
status: z.enum(['ok', 'blocked']),
|
|
285
|
+
operation: z.enum(['layout', 'insert']),
|
|
286
|
+
treeId: z.string().optional(),
|
|
287
|
+
nodes: z.array(z
|
|
288
|
+
.object({
|
|
289
|
+
id: z.string(),
|
|
290
|
+
x: z.number().int(),
|
|
291
|
+
y: z.number().int(),
|
|
292
|
+
laneId: z.string(),
|
|
293
|
+
moved: z.boolean(),
|
|
294
|
+
})
|
|
295
|
+
.strict()),
|
|
296
|
+
source: z.array(z
|
|
297
|
+
.object({
|
|
298
|
+
id: z.string(),
|
|
299
|
+
relativeTo: z.string().optional(),
|
|
300
|
+
x: z.number().int(),
|
|
301
|
+
y: z.number().int(),
|
|
302
|
+
})
|
|
303
|
+
.strict()),
|
|
304
|
+
diagnostics: z.array(z
|
|
305
|
+
.object({
|
|
306
|
+
code: z.string().regex(/^FOCUS_ENGINE_[A-Z_]+$/u),
|
|
307
|
+
severity: z.enum(['error', 'warning', 'info']),
|
|
308
|
+
focusIds: z.array(z.string()),
|
|
309
|
+
message: z.string(),
|
|
310
|
+
details: z.record(z.string(), z.unknown()),
|
|
311
|
+
})
|
|
312
|
+
.strict()),
|
|
313
|
+
metrics: z
|
|
314
|
+
.object({
|
|
315
|
+
columns: z.number().int().min(0),
|
|
316
|
+
rows: z.number().int().min(0),
|
|
317
|
+
orthogonalCrossings: z.number().int().min(0),
|
|
318
|
+
stemsThroughPlaques: z.number().int().min(0),
|
|
319
|
+
mergedBars: z.number().int().min(0),
|
|
320
|
+
durationMicros: z.number().int().min(0),
|
|
321
|
+
})
|
|
322
|
+
.strict()
|
|
323
|
+
.nullable(),
|
|
324
|
+
hashes: z
|
|
325
|
+
.object({
|
|
326
|
+
layout: sha256Schema.nullable(),
|
|
327
|
+
untouched: sha256Schema,
|
|
328
|
+
prerequisites: sha256Schema,
|
|
329
|
+
exclusions: sha256Schema,
|
|
330
|
+
})
|
|
331
|
+
.strict(),
|
|
332
|
+
needsRoom: z
|
|
333
|
+
.object({ shift: z.array(shiftSchema) })
|
|
334
|
+
.strict()
|
|
335
|
+
.optional(),
|
|
336
|
+
shifted: z.array(shiftSchema).optional(),
|
|
337
|
+
})
|
|
338
|
+
.strict();
|
|
339
|
+
/** `hoi4-engine focus-layout` with the request on stdin. */
|
|
340
|
+
export function runFocusLayoutEngine(request, options = {}) {
|
|
341
|
+
return runEngineCommand('focus-layout', request, focusLayoutEngineResponseSchema, options);
|
|
342
|
+
}
|
|
@@ -199,6 +199,11 @@ function boundedResult(result, actualBytes) {
|
|
|
199
199
|
data: jsonBytesWithin(compactData, 2_048) ? compactData : {},
|
|
200
200
|
};
|
|
201
201
|
}
|
|
202
|
+
/**
|
|
203
|
+
* Images are outside the 32 KiB structured-result budget; they have their own: a response never
|
|
204
|
+
* carries more than this many base64 characters of images.
|
|
205
|
+
*/
|
|
206
|
+
export const MAX_TOOL_RESULT_IMAGE_CHARACTERS = 3_000_000;
|
|
202
207
|
function jsonStringBytes(value) {
|
|
203
208
|
let bytes = 2 + Buffer.byteLength(value, 'utf8');
|
|
204
209
|
for (let index = 0; index < value.length; index += 1) {
|
|
@@ -416,7 +421,7 @@ function compactDescriptions(unfiltered) {
|
|
|
416
421
|
})),
|
|
417
422
|
};
|
|
418
423
|
}
|
|
419
|
-
function buildToolResult(selected) {
|
|
424
|
+
function buildToolResult(selected, imageCount = 0) {
|
|
420
425
|
const structuredContent = operationResultSchema.parse(selected);
|
|
421
426
|
const shown = selected.artifacts
|
|
422
427
|
.map((artifact, order) => ({ artifact, order }))
|
|
@@ -439,9 +444,19 @@ function buildToolResult(selected) {
|
|
|
439
444
|
code: selected.code,
|
|
440
445
|
workspaceId: selected.workspaceId,
|
|
441
446
|
artifactCount: selected.artifacts.length,
|
|
447
|
+
...(imageCount > 0 ? { inlineImages: imageCount } : {}),
|
|
442
448
|
...(selected.artifacts.length > shown.length
|
|
443
449
|
? { artifactsListedInStructuredContent: selected.artifacts.length }
|
|
444
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
|
+
: {}),
|
|
445
460
|
...(selected.status === 'ok' || selected.blockers.length === 0
|
|
446
461
|
? {}
|
|
447
462
|
: {
|
|
@@ -460,23 +475,36 @@ function buildToolResult(selected) {
|
|
|
460
475
|
...(selected.status === 'error' ? { isError: true } : {}),
|
|
461
476
|
};
|
|
462
477
|
}
|
|
463
|
-
export function toolResult(result) {
|
|
478
|
+
export function toolResult(result, options = {}) {
|
|
479
|
+
let imageCharacters = 0;
|
|
480
|
+
const images = (options.images ?? []).filter((image) => {
|
|
481
|
+
imageCharacters += image.data.length;
|
|
482
|
+
return imageCharacters <= MAX_TOOL_RESULT_IMAGE_CHARACTERS;
|
|
483
|
+
});
|
|
464
484
|
const completeResult = preserveDeferredFilesDiagnostic(result);
|
|
465
485
|
const compact = compactDescriptions(completeResult);
|
|
466
486
|
const estimatedBytes = jsonBytesWithin(compact, MAX_TOOL_RESULT_BYTES)
|
|
467
487
|
? Buffer.byteLength(canonicalJson(compact), 'utf8')
|
|
468
488
|
: MAX_TOOL_RESULT_BYTES + 1;
|
|
469
489
|
const selected = estimatedBytes > MAX_TOOL_RESULT_BYTES ? boundedResult(compact, estimatedBytes) : compact;
|
|
470
|
-
let output = buildToolResult(selected);
|
|
490
|
+
let output = buildToolResult(selected, images.length);
|
|
471
491
|
const wireBytes = Buffer.byteLength(canonicalJson(output), 'utf8');
|
|
472
492
|
if (wireBytes > MAX_TOOL_RESULT_BYTES) {
|
|
473
|
-
output = buildToolResult(boundedResult(compact, wireBytes));
|
|
493
|
+
output = buildToolResult(boundedResult(compact, wireBytes), images.length);
|
|
474
494
|
}
|
|
475
495
|
const finalBytes = Buffer.byteLength(canonicalJson(output), 'utf8');
|
|
476
496
|
if (finalBytes > MAX_TOOL_RESULT_BYTES) {
|
|
477
497
|
throw new Error('Constant MCP response-limit result exceeded its wire budget');
|
|
478
498
|
}
|
|
479
|
-
|
|
499
|
+
if (images.length === 0)
|
|
500
|
+
return output;
|
|
501
|
+
return {
|
|
502
|
+
...output,
|
|
503
|
+
content: [
|
|
504
|
+
...output.content,
|
|
505
|
+
...images.map(({ data, mimeType }) => ({ type: 'image', data, mimeType })),
|
|
506
|
+
],
|
|
507
|
+
};
|
|
480
508
|
}
|
|
481
509
|
/** Paths in a message can name private folders; the file name is enough to act on. */
|
|
482
510
|
function withoutDirectories(message) {
|