hoi4-agent-tools 4.11.1 → 4.13.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 +21 -0
- package/README.md +3 -3
- package/dist/bin/setup.js +38 -0
- package/dist/bin/stdio.js +12 -10
- package/dist/hoi4_agent_tools/core/configuration.js +29 -0
- package/dist/hoi4_agent_tools/core/domain-tools.js +4 -0
- package/dist/hoi4_agent_tools/core/engine-check.js +87 -0
- package/dist/hoi4_agent_tools/core/engine-client.js +1 -1
- package/dist/hoi4_agent_tools/core/engine.js +18 -2
- package/dist/hoi4_agent_tools/core/job-operation-registration.js +2 -0
- package/dist/hoi4_agent_tools/core/job-store.js +1 -1
- package/dist/hoi4_agent_tools/focus/native-effects.js +1 -1
- package/dist/hoi4_agent_tools/localisation/job-operations.js +42 -0
- package/dist/hoi4_agent_tools/localisation/write-diff.js +96 -0
- package/dist/hoi4_agent_tools/localisation/write-format.js +329 -0
- package/dist/hoi4_agent_tools/localisation/write-operations.js +213 -0
- package/dist/hoi4_agent_tools/localisation/write-plan.js +557 -0
- package/dist/hoi4_agent_tools/map/gameplay/crossing-validation.js +17 -0
- package/dist/hoi4_agent_tools/map/model.js +31 -1
- package/dist/hoi4_agent_tools/map/operations.js +37 -8
- package/dist/hoi4_agent_tools/map/references.js +87 -0
- package/dist/hoi4_agent_tools/map/relief/hydrology.js +7 -2
- package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +1 -0
- package/dist/hoi4_agent_tools/map/service.js +13 -4
- package/dist/hoi4_agent_tools/map/tool-operations.js +6 -0
- package/dist/hoi4_agent_tools/map/world-edge.js +0 -25
- package/dist/hoi4_agent_tools/map/world.js +181 -64
- package/dist/hoi4_agent_tools/mcp/plugins.js +74 -0
- package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +5 -0
- package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +15 -21
- package/dist/hoi4_agent_tools/mcp/server/create.js +5 -1
- package/dist/hoi4_agent_tools/mcp/server/request-lifecycle.js +10 -2
- package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +2 -0
- package/dist/hoi4_agent_tools/mcp/server/tool-profiles.js +83 -0
- package/dist/hoi4_agent_tools/mcp/tools/localisation-write.js +21 -0
- package/dist/hoi4_agent_tools/mcp/tools/reference.js +34 -0
- package/dist/hoi4_agent_tools/mcp/transports/http.js +6 -1
- package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +64 -6
- package/dist/hoi4_agent_tools/probability/model.js +4 -4
- package/dist/hoi4_agent_tools/reference/compat-patch.js +555 -0
- package/dist/hoi4_agent_tools/reference/compat.js +255 -0
- package/dist/hoi4_agent_tools/reference/docs-pack.js +164 -0
- package/dist/hoi4_agent_tools/reference/docs-pack.json +339 -0
- package/dist/hoi4_agent_tools/reference/documented-commands.js +26 -0
- package/dist/hoi4_agent_tools/reference/error-explain.js +235 -0
- package/dist/hoi4_agent_tools/reference/error-explanations.json +262 -0
- package/dist/hoi4_agent_tools/reference/error-log.js +30 -10
- package/dist/hoi4_agent_tools/reference/mod-health.js +255 -0
- package/dist/hoi4_agent_tools/reference/mod-index.js +63 -65
- package/dist/hoi4_agent_tools/reference/operations.js +435 -21
- package/dist/hoi4_agent_tools/reference/script-guard.js +109 -0
- package/dist/hoi4_agent_tools/reference/service.js +58 -20
- package/dist/hoi4_agent_tools/runtime.js +17 -2
- package/dist/hoi4_agent_tools/schemas/compat.js +153 -0
- package/dist/hoi4_agent_tools/schemas/localisation-write.js +154 -0
- package/dist/hoi4_agent_tools/schemas/map.js +5 -1
- package/dist/hoi4_agent_tools/schemas/mod-tools.js +50 -0
- package/dist/hoi4_agent_tools/schemas/modder-tools.js +191 -0
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +14 -11
- package/docs/development.md +2 -0
- package/docs/jobs.md +3 -1
- package/docs/map.md +8 -4
- package/docs/reference.md +47 -5
- package/docs/research/probability-adapter-evidence.md +11 -1
- package/docs/setup.md +23 -3
- package/docs/tools.md +18 -4
- package/docs/troubleshooting.md +1 -1
- 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 +8 -8
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/schemas/configuration.schema.json +181 -138
- 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 +153 -139
- 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/dist/hoi4_agent_tools/mcp/tools/chaosx.js +0 -509
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,27 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 4.13.0 - 2026-11-08
|
|
6
|
+
|
|
7
|
+
- `create_world` with `edge.mode` `"wall"` or `"rim"` no longer writes `impassable` adjacency rows across the wrapping seam. The game does not wrap adjacencies and drew each of these rows as a crossing line between the two province centres, through the whole map: 596 red dashed lines on a 5,120-pixel ZIN world written with 4.11.1. Every land province on the first or last column now becomes an impassable state instead, linked and owned like the wall's states, so the seam stays closed without any row; in `rim` mode this makes the rim's seam provinces impassable states. Validation reports any adjacency row between provinces that touch only across the seam as `MAP_ADJACENCY_ACROSS_SEAM` (error), and `MAP_EDGE_RIM_ADJACENCIES` is no longer reported (ADR 0061 amendment).
|
|
8
|
+
- List the core tools by default (maintainer decisions R-4 and R-1). A session lists the `core` profile: documentation search and reading, source lookup, script validation, the invented-command guard, the error log and its explanations, the mod health check, the mod index, localisation and kit skills. The `map` profile adds the world map tools and `advanced` the focus, GUI, event, technology, decision and probability editors and the other inspect tools; the job controls come with either. `HOI4_AGENT_TOOLS_PROFILES` (`core,map`, `all`) or the new `profiles` configuration key lists more, and the server instructions say how when a profile is left out. A tool outside the listed profiles still answers a call. The stdio server (`hoi4-agent-tools`) lists `core` by default; the HTTP server and a server built in code list every tool, as before. Tools of configured plugins are listed in every profile. A test keeps the core listing within the R-1 ceiling of 8,000 tokens, estimated at 3.5 bytes per token of the listed JSON. The core listing is 13 tools and 23,757 bytes (about 6,800 tokens by that estimate), against 89,950 bytes for all 39 tools, which every session listed before.
|
|
9
|
+
- Add `hoi4.script_guard` (maintainer decision R-5). It checks every effect, trigger and modifier in the files an agent wrote against the installed game's documentation and the scripted helpers and modifiers the loaded files define, and reports each invented name with its file, line and closest real name. It takes `paths`, or the mod's script files changed in the last `sinceMinutes` (120 by default), chosen by file time so no Git command runs in the mod. The engine's whole-mod check judges each `name = value` command, and script validation adds the names it cannot resolve, such as a trigger compared with `>`. On a scratch mod against game 1.19.4.2 it found all three invented names (`add_politcal_power`, `has_stabilty`, `stabilty_factor`) with the right suggestions, and on two Chaos Redux event files it found none.
|
|
10
|
+
- Add `hoi4.explain_error` and `hoi4.mod_health` (maintainer decision R-5). `explain_error` takes up to 10 `error.log` lines and explains each message in them: the rule it breaks, the fix, the source file and line with the lines around it, and the next call. The rules and fixes come from a reviewed catalogue of 32 message shapes the game's own log writes (`error-explanations.json`), each with its evidence, then the reviewed known mistakes, then the message's category. For a command it names, it says whether the installed documentation lists it as an effect, trigger or modifier, whether a loaded file defines it as a scripted helper, and the closest documented names, with a value's `has_` trigger first (`stability` gives `has_stability`, `clear_country_flag` gives `clr_country_flag`). A line from the game's own files says so. `mod_health` runs the error log, the engine's whole-mod check (`hoi4-engine check`), script validation, and the localisation, sprite and flag audits, and returns the 10 problems that matter most, each counted with two examples, its fix and the tool to call next. Script validation checks the files the other audits named first, within 30 seconds. An audit that cannot run is reported with the reason, and the verdict is then `incomplete`, never `healthy`. On Ireland Total Overhaul with game 1.19.4.2 it took 40 s. `error_log` now reads the line of `line : 12` and `file.txt:12:` messages, and no longer takes the words before a bare path as part of it.
|
|
11
|
+
- Add `hoi4.localisation_write` (maintainer decision R-5). One tool adds localisation keys and fixes localisation files. With `apply` false (the default) it writes nothing and returns the unified diff of every file it would change. With `apply` true it makes the same change atomically and returns the same diff. There is no plan id between the two. `mode: "add"` appends `entries` to the mod's English (or other `language`) file with the most keys, or creates `localisation/<language>/<mod folder>_l_<language>.yml`. It keeps the file's indent, `:0` style, newline style and final newline. New files use what most game files use: UTF-8 with a BOM, `l_<language>:`, one leading space and no version number. A key the mod already defines with the same text is skipped as unchanged, with other text it is skipped unless `replace` is true, then its line is rewritten in place. A key that only the game or a dependency defines is written to `localisation/<language>/replace/`, which the game loads with priority, and the result says it is an override. `mode: "fix"` repairs a missing BOM (UTF-16 is re-encoded to UTF-8 with BOM), unambiguous quotes (a missing closing quote, typographic quotes used as delimiters) and keys that a supported language lacks (the English text is copied). Anything ambiguous, and keys that script uses and no language defines, is listed in `unfixable`. The tool never writes outside the mod's `localisation/` folder and refuses absolute paths and `..`. Keys the script uses without a definition need the engine and are reported only when it is available.
|
|
12
|
+
- Add `hoi4.compat_check` (maintainer decision R-5), read-only, on the shared Rust engine. `mode: "mod"` checks the mod against another mod, named by folder or workspace id and readable by the caller, in both load orders. It reports the files both ship at the same path and which one wins, the ids both define, the definitions, on_actions hooks and references the winner drops or breaks, the files one mod's `replace_path` unloads from the other, a verdict, and which load order loses less as error and warning counts. Findings about one mod and the game are left out. `mode: "patch"` stores the SHA-256 of every game and DLC file the mod overrides, with copies of text files up to 4 MiB (at most 128 MiB, the newest three snapshots kept), in the workspace cache folder, and lists the overrides that a newer game build changed, added or removed, with line counts and the first hunk of the diff. The first call only records the baseline. `from` and `to` compare two stored builds without the engine. Results stay under the 32 KiB limit and count what they leave out. The engine client now passes command-line `args` to a command.
|
|
13
|
+
- Search the documentation with no mod open (maintainer decision R-4). `hoi4-agent-tools-setup --fetch-docs` downloads the docs pack once: the modding kit's 64 HOI4 wiki pages with their licence and sources (about 3.6 MB) at the kit commit this version pins, each checked against its pinned SHA-256, and installs it in one step in `docsRoot` (a new configuration key, by default the user's data folder). A failed or mismatched download installs nothing. With no mod selected, `reference_search`, `reference_read` and `reference_context` answer from the installed game documentation and the pack, with the workspace ID `docs` and the information `REFERENCE_DOCUMENTATION_ONLY`, instead of failing with `WORKSPACE_CONTEXT_NOT_FOUND`. `"workspaceId":"docs"` asks for that explicitly. A mod without its own wiki copy reads the pack as its wiki. When no wiki is available, `REFERENCE_WIKI_UNAVAILABLE` names the fetch step. `--diagnose` reports whether the pack is installed, and `scripts/update-docs-pack.ts` moves the pin.
|
|
14
|
+
|
|
15
|
+
## 4.12.0 - 2026-11-08
|
|
16
|
+
|
|
17
|
+
- `create_world.synthesisCheck` reports every blocking problem it can find in one preview. A ZIN map write on 6 November needed six attempts, one blocked problem each; four of the six never appeared in a preview, and the check stopped at its first error. The check now lists, together and each as a blocker: realm points that cannot be placed, cities and capitals on impassable land (found from the impassable mask before the synthesis instead of after the partition), rivers that cannot reach their mouths, and passes that are not lower than their crest, which are now checked even when a river fails. A write still stops at its first blocking problem, and a city on impassable land is now refused before the synthesis instead of after the partition, with the same code and message. Leaks through a wall still need the partition, so only a write reports them.
|
|
18
|
+
- Release workflow: the npm and GHCR publication checks call the GitHub API with the job's token, check the release tag once before they wait for the registry, and wait up to 20 minutes for npm instead of 5. The 4.11.1 run published to npm, but npm held the version for processing longer than 5 minutes; the check retried the anonymous tag lookup every 5 seconds until GitHub refused it (403) and the release stopped before the image, GitHub release and MCP Registry steps.
|
|
19
|
+
- Answer the stdio handshake before startup recovery. The server checked every retained rewrite journal before it answered `initialize`, and each applied `create_world` leaves a journal of about 7 MB, so a mod with eight map writes took 4 to 5 seconds to connect (7.5 seconds with five clients starting at once, 8.7 seconds cold) and clients that allow 30 seconds gave up under load. The stdio server now answers `initialize`, `ping`, `server/discover`, `tools/list`, `prompts/list` and `logging/setLevel` at once, recovers in the background, and holds every other request, in arrival order, until recovery ends, so no call reads or writes a workspace before its interrupted rewrite is recovered. Measured on a configuration with six mods and 28 MB of map journals, the handshake takes 1.1 to 1.2 seconds (1.8 to 1.9 seconds for five at once); the first tool call waits for the rest. More than 128 held requests, or a failed recovery, closes the connection without answering them. The HTTP server still recovers before it listens.
|
|
20
|
+
- Add `create_world.inheritedContinents` (`keep` by default, or `drop`). With `drop`, `continent.txt` lists only the generated continents instead of also every continent of the active `continent.txt`, so a total conversion no longer shows the base game's continents in the trade window. Each active script reference to a dropped continent is reported with its file and line as `MAP_CONTINENT_DROPPED_REFERENCED` (warning): `is_on_continent`, `continent =` in `any_state_in` and its effects, AI areas' `continents` lists and portrait pools' `continent = { name = ... }`. Requests without the field are unchanged.
|
|
21
|
+
- Impassable land no longer joins landmasses, strategic regions or countries in `create_world`. The `wall` edge connected a landmass at the east edge with one at the west edge across the seam into one continent, and a strategic region could run over the wall from one edge to the other; land that only a painted or regional impassable strip connected was one continent too. Continents and land regions are now grouped over passable land. Each piece of impassable land takes the continent of the largest landmass it borders (or of the nearest one, when it borders only water), and joins the passable region it borders most when it is no larger than a region, or forms regions of its own. Generated countries and workspace realms also grow over passable land only, so a realm seeded at the east edge no longer takes land at the west edge over the wall; land reached only that way follows the island rule. Impassable provinces take no owner while countries grow, and their states take the owner of the passable state they link to (`force_link_ownership_to`). Worlds without impassable land are unchanged.
|
|
22
|
+
- Move the probability adapters' pin to game 1.19.4.2. The six documentation files they rest on and every vanilla example are unchanged from the 1.19.4.1 review, so no adapter rule changed: the target is `Operation Postern 1.19.4.2 (0bdb)` and the adapter version `hoi4-1.19.4.2.v1`. The native-effects fallback list is regenerated from the same documentation (identical list). A result on another build still carries `PROBABILITY_GAME_BUILD_UNVERIFIED`.
|
|
23
|
+
- Run `hoi4.mod_index` on the shared Rust engine (`hoi4-engine mod-index`, ADR 0080; M-8 step 1). The engine's new shared symbol index (`symbol_index`) reproduces the TypeScript index's kinds, definition rules and `overridden` rule, so the answers do not change: on vanilla 1.19.4.2, Chaos Redux, ZIN, Ireland Total Overhaul, Atlantis, Kaiserreich and Old World Blues, for the mod layer and every layer, each (kind, id, overridden) record, file count, completeness flag, folder total and namespace matches the TypeScript scan, and so do 203 `next_id` answers (`scripts/mod-index-parity.ts`). A first overview of Chaos Redux takes 5 s instead of 23 s, and a repeated one 1 s instead of 5 s. Without a usable engine the tool answers `ENGINE_UNAVAILABLE`; nothing is counted in TypeScript instead. `hoi4-engine symbol-index` prints every record of the index. The tests now need a cargo build of the engine, which CI and the release workflow build first. The benchmark gains warm `mod_index` cases for every corpus and an every-layer case for the game.
|
|
24
|
+
- Move the two ChaosX tools out of the public package (maintainer decision M-14, #110, ADR 0081). `chaosx.visual_revision` and `chaosx.focus_country_assets` are gone, and `HOI4_AGENT_TOOLS_CHAOSX` does nothing. The stdio server instead loads plugins from the absolute paths the new configuration key `plugins` lists, never from a mod folder or the environment; a plugin adds tools named `<plugin>.<tool>` (never `hoi4.`), and the HTTP server never loads one. A listed plugin file that does not exist is skipped with a warning on stderr.
|
|
25
|
+
|
|
5
26
|
## 4.11.1 - 2026-11-07
|
|
6
27
|
|
|
7
28
|
- Close impassable walls in generated maps, and keep pass saddles and point river mouths that a 4.10.0 `create_world` lost.
|
package/README.md
CHANGED
|
@@ -35,9 +35,7 @@ Make focus trees, events and decisions. Edit maps and generate a new world. Prev
|
|
|
35
35
|
|
|
36
36
|
## What it does
|
|
37
37
|
|
|
38
|
-
Your agent can build and edit focus trees, events, decisions and maps, and generate a new world.
|
|
39
|
-
|
|
40
|
-
For a new map, give it a cleaned local reference image and preview the interpreted geography before writing. The [map workflow](docs/map.md#generate-a-world-from-one-image) creates provinces, states, terrain, cities, countries, supply and a provisional starting scenario. Reviewed names and masks refine ambiguous artwork; offline validation is separate from [native campaign acceptance](https://github.com/klimPaskov/hoi4-agent-tools/blob/v4.1.0/docs/evaluations/worldgen_acceptance_2026-10-15.md).
|
|
38
|
+
Your agent can build and edit focus trees, events, decisions and maps, and generate a new world from a reference image ([map guide](docs/map.md)).
|
|
41
39
|
It previews focus trees, technology folders, windows and maps, finds the right rule in the game's documentation, fixes broken script and tunes AI choices.
|
|
42
40
|
You describe what you want; the agent picks the right tools.
|
|
43
41
|
|
|
@@ -85,6 +83,8 @@ The server gives your agent previews, documentation, script analysis and editing
|
|
|
85
83
|
The agent combines them with its file editor to build events and decisions, repair scripts and adjust AI weights.
|
|
86
84
|
The [tool reference](docs/tools.md) lists exact names, arguments and results for integrations.
|
|
87
85
|
|
|
86
|
+
A session lists the core tools by default: documentation search, source lookup, script validation, the error log, the mod health check and localisation. They fit in about 8,000 tokens of the agent's context. Set `HOI4_AGENT_TOOLS_PROFILES` to `core,map`, `core,advanced` or `all` in the client's server entry for the world map tools or the focus, GUI, event, technology and probability editors ([tool profiles](docs/setup.md#choose-tool-profiles)).
|
|
87
|
+
|
|
88
88
|
## FAQ
|
|
89
89
|
|
|
90
90
|
**Where do edits go?** Changes are written to your mod folder; use Git to review or undo them.
|
package/dist/bin/setup.js
CHANGED
|
@@ -11,6 +11,7 @@ import { CoreEngine } from '../hoi4_agent_tools/core/engine.js';
|
|
|
11
11
|
import { WorkspaceResolver } from '../hoi4_agent_tools/core/workspace.js';
|
|
12
12
|
import { configurationPath, defaultConfigurationPath } from '../hoi4_agent_tools/runtime.js';
|
|
13
13
|
import { PACKAGE_VERSION } from '../hoi4_agent_tools/version.js';
|
|
14
|
+
import { defaultDocsRoot, docsPackManifest, fetchDocsPack, installedDocsPackWiki, } from '../hoi4_agent_tools/reference/docs-pack.js';
|
|
14
15
|
function argument(name) {
|
|
15
16
|
const index = process.argv.indexOf(name);
|
|
16
17
|
return index < 0 ? undefined : process.argv[index + 1];
|
|
@@ -112,6 +113,11 @@ Usage:
|
|
|
112
113
|
hoi4-agent-tools-setup --discover
|
|
113
114
|
hoi4-agent-tools-setup --diagnose [--config PATH]
|
|
114
115
|
hoi4-agent-tools-setup --print-client-config [--config PATH]
|
|
116
|
+
hoi4-agent-tools-setup --fetch-docs [--config PATH] [--docs-root PATH]
|
|
117
|
+
|
|
118
|
+
--fetch-docs downloads the HOI4 wiki pages that documentation search reads with no mod open
|
|
119
|
+
(about 3.6 MB, checked against pinned SHA-256 hashes) into the configured docsRoot, or the user's
|
|
120
|
+
data folder.
|
|
115
121
|
|
|
116
122
|
This utility writes only the explicitly requested server config. It never edits an MCP client's settings.`;
|
|
117
123
|
}
|
|
@@ -171,8 +177,29 @@ async function initializeConfig(target) {
|
|
|
171
177
|
await writeFile(absolute, `${JSON.stringify(config, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
|
|
172
178
|
process.stdout.write(`${absolute}\n`);
|
|
173
179
|
}
|
|
180
|
+
/** The docs root: the flag, the configuration's `docsRoot`, or the user's data folder. */
|
|
181
|
+
async function docsRootFor(configPath) {
|
|
182
|
+
const requested = argument('--docs-root');
|
|
183
|
+
if (requested !== undefined)
|
|
184
|
+
return path.resolve(requested);
|
|
185
|
+
try {
|
|
186
|
+
await stat(configPath);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return defaultDocsRoot();
|
|
190
|
+
}
|
|
191
|
+
return (await loadConfiguration(configPath)).docsRoot ?? defaultDocsRoot();
|
|
192
|
+
}
|
|
193
|
+
async function fetchDocs(configPath) {
|
|
194
|
+
const docsRoot = await docsRootFor(configPath);
|
|
195
|
+
const result = await fetchDocsPack({ docsRoot });
|
|
196
|
+
process.stdout.write(`${JSON.stringify({ status: 'ok', ...result, license: docsPackManifest.license }, null, 2)}
|
|
197
|
+
`);
|
|
198
|
+
}
|
|
174
199
|
async function diagnose(configPath) {
|
|
175
200
|
const configuration = await loadConfiguration(configPath);
|
|
201
|
+
const docsRoot = configuration.docsRoot ?? defaultDocsRoot();
|
|
202
|
+
const docsPackWiki = await installedDocsPackWiki(docsRoot);
|
|
176
203
|
const resolver = await WorkspaceResolver.create(configuration);
|
|
177
204
|
const engine = new CoreEngine(resolver);
|
|
178
205
|
const serverState = resolver.serverState();
|
|
@@ -206,6 +233,12 @@ async function diagnose(configPath) {
|
|
|
206
233
|
...(serverState === undefined
|
|
207
234
|
? {}
|
|
208
235
|
: { serverState: { root: serverState.root, readable: true, writable: true } }),
|
|
236
|
+
docsPack: {
|
|
237
|
+
root: docsRoot,
|
|
238
|
+
installed: docsPackWiki !== undefined,
|
|
239
|
+
commit: docsPackManifest.commit,
|
|
240
|
+
...(docsPackWiki === undefined ? { fix: 'Run hoi4-agent-tools-setup --fetch-docs' } : {}),
|
|
241
|
+
},
|
|
209
242
|
workspaces,
|
|
210
243
|
}, null, 2)}\n`);
|
|
211
244
|
}
|
|
@@ -261,6 +294,11 @@ async function main() {
|
|
|
261
294
|
await diagnose(config);
|
|
262
295
|
return;
|
|
263
296
|
}
|
|
297
|
+
if (process.argv.includes('--fetch-docs')) {
|
|
298
|
+
assertKnownArguments(['--fetch-docs'], ['--config', '--docs-root']);
|
|
299
|
+
await fetchDocs(config);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
264
302
|
if (process.argv.includes('--print-client-config')) {
|
|
265
303
|
assertKnownArguments(['--print-client-config'], ['--config']);
|
|
266
304
|
printClientConfig(config);
|
package/dist/bin/stdio.js
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import path from 'node:path';
|
|
2
3
|
import { canonicalJson } from '../hoi4_agent_tools/core/canonical.js';
|
|
3
4
|
import { StdioFrameLimitError, StdioInvalidMessageError, StdioInvalidUtf8Error, } from '../hoi4_agent_tools/mcp/transports/bounded-stdio.js';
|
|
4
5
|
import { serveNegotiatedStdio } from '../hoi4_agent_tools/mcp/transports/negotiated-stdio.js';
|
|
5
6
|
import { ServerRegistry } from '../hoi4_agent_tools/core/server-registry.js';
|
|
6
7
|
import { StdioLifetime } from '../hoi4_agent_tools/mcp/transports/stdio-lifetime.js';
|
|
8
|
+
import { loadPlugins } from '../hoi4_agent_tools/mcp/plugins.js';
|
|
9
|
+
import { PACKAGE_VERSION } from '../hoi4_agent_tools/version.js';
|
|
10
|
+
import { DEFAULT_PROFILES } from '../hoi4_agent_tools/mcp/server/tool-profiles.js';
|
|
7
11
|
import { createEngine } from '../hoi4_agent_tools/runtime.js';
|
|
8
12
|
/**
|
|
9
13
|
* A client registration can set its own idle limit, because the server configuration is shared
|
|
@@ -20,10 +24,13 @@ function idleExitMinutes(configured) {
|
|
|
20
24
|
return minutes;
|
|
21
25
|
}
|
|
22
26
|
async function main() {
|
|
23
|
-
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
:
|
|
27
|
+
// The handshake must not wait for journal recovery; the transport holds workspace requests.
|
|
28
|
+
const engine = await createEngine(undefined, {
|
|
29
|
+
recovery: 'background',
|
|
30
|
+
defaultProfiles: DEFAULT_PROFILES,
|
|
31
|
+
});
|
|
32
|
+
// Plugins load only from the paths the server configuration lists (M-14).
|
|
33
|
+
const plugins = await loadPlugins(engine.resolver.config().plugins, PACKAGE_VERSION, (file, reason) => process.stderr.write(`${canonicalJson({ level: 'warn', event: 'plugin_skipped', plugin: path.basename(file), reason })}\n`));
|
|
27
34
|
const onerror = (error) => {
|
|
28
35
|
const fatalInputError = error instanceof StdioFrameLimitError || error instanceof StdioInvalidUtf8Error;
|
|
29
36
|
const rejectedMessage = error instanceof StdioInvalidMessageError;
|
|
@@ -65,12 +72,7 @@ async function main() {
|
|
|
65
72
|
: {}),
|
|
66
73
|
})}\n`);
|
|
67
74
|
},
|
|
68
|
-
...(
|
|
69
|
-
? {}
|
|
70
|
-
: {
|
|
71
|
-
createModernPrivateTools: chaosxTools.createChaosxToolOperations,
|
|
72
|
-
registerLegacy: (server) => chaosxTools.registerChaosxTools(server, engine, {}),
|
|
73
|
-
}),
|
|
75
|
+
...(plugins === undefined ? {} : { plugins }),
|
|
74
76
|
});
|
|
75
77
|
closeTransport = () => transport.close();
|
|
76
78
|
lifetime.start();
|
|
@@ -151,6 +151,19 @@ export const serverConfigurationSchema = z
|
|
|
151
151
|
jobDeadlineSeconds: z.number().int().min(1).max(86_400).default(1_800),
|
|
152
152
|
/** A read-only job that has not stopped this long after cancellation is stopped. */
|
|
153
153
|
jobCancelGraceSeconds: z.number().int().min(1).max(600).default(10),
|
|
154
|
+
/**
|
|
155
|
+
* Absolute paths of plugin modules (.mjs or .js) the stdio server loads (M-14). A plugin adds
|
|
156
|
+
* its own tools; the server loads nothing from a mod folder or the environment. A listed file
|
|
157
|
+
* that does not exist is skipped, so a shared configuration can name a private plugin.
|
|
158
|
+
*/
|
|
159
|
+
plugins: z
|
|
160
|
+
.array(z
|
|
161
|
+
.string()
|
|
162
|
+
.min(1)
|
|
163
|
+
.max(1024)
|
|
164
|
+
.refine((value) => path.isAbsolute(value), 'A plugin path must be absolute'))
|
|
165
|
+
.max(8)
|
|
166
|
+
.default([]),
|
|
154
167
|
/** A stdio server with no client traffic or open request for this long exits; 0 never. */
|
|
155
168
|
stdioIdleExitMinutes: z.number().int().min(0).max(10_080).default(0),
|
|
156
169
|
/** V8 heap ceiling for each job worker in MiB; unset keeps Node's default. */
|
|
@@ -189,7 +202,23 @@ export const serverConfigurationSchema = z
|
|
|
189
202
|
gameRoot: z.string().min(1).optional(),
|
|
190
203
|
/** The game's user-data folder holding logs/ and mod/; derived from the mod folder when unset. */
|
|
191
204
|
gameUserRoot: z.string().min(1).optional(),
|
|
205
|
+
/**
|
|
206
|
+
* Where `hoi4-agent-tools-setup --fetch-docs` installs the docs pack, the HOI4 wiki pages the
|
|
207
|
+
* reference tools read with no mod open and in a mod without its own copy. The command-line
|
|
208
|
+
* servers default it to the user's data folder; unset elsewhere, no pack is read.
|
|
209
|
+
*/
|
|
210
|
+
docsRoot: z.string().min(1).optional(),
|
|
192
211
|
workspaceStorageRoot: z.string().min(1).optional(),
|
|
212
|
+
/**
|
|
213
|
+
* The tool profiles a session lists (maintainer decision R-4): `core`, `map`, `advanced` or
|
|
214
|
+
* `all`. The stdio server lists `core` when this is unset; the HTTP server and a server
|
|
215
|
+
* built in code list every tool. `HOI4_AGENT_TOOLS_PROFILES` overrides it for one client registration.
|
|
216
|
+
*/
|
|
217
|
+
profiles: z
|
|
218
|
+
.array(z.enum(['core', 'map', 'advanced', 'all']))
|
|
219
|
+
.min(1)
|
|
220
|
+
.max(4)
|
|
221
|
+
.optional(),
|
|
193
222
|
storageRoots: z.array(z.string().min(1)).max(WORKSPACE_MAX_SOURCE_ROOTS).default([]),
|
|
194
223
|
workspaces: z.array(workspaceRegistrationSchema).max(WORKSPACE_MAX_REGISTRATIONS).default([]),
|
|
195
224
|
/**
|
|
@@ -2,6 +2,7 @@ import { decisionInspectRequestSchema, impactInspectRequestSchema } from '../sch
|
|
|
2
2
|
import { eventInspectRequestSchema, eventRenderRequestSchema } from '../schemas/event.js';
|
|
3
3
|
import { focusInspectRequestSchema, focusRenderRequestSchema, focusRewriteRequestSchema, } from '../schemas/focus-requests.js';
|
|
4
4
|
import { guiInspectRequestSchema, guiRenderRequestSchema, guiRewriteRequestSchema, } from '../schemas/gui-requests.js';
|
|
5
|
+
import { localisationWriteRequestSchema } from '../schemas/localisation-write.js';
|
|
5
6
|
import { mapInspectRequestSchema, mapRewriteRequestSchema } from '../schemas/map-requests.js';
|
|
6
7
|
import { probabilityAnalyzeRequestSchema, probabilityInspectRequestSchema, } from '../schemas/probability-requests.js';
|
|
7
8
|
import { mechanicTestRequestSchema, packageCheckRequestSchema, scenarioTestRequestSchema, } from '../schemas/scenarios.js';
|
|
@@ -25,6 +26,7 @@ export const DOMAIN_TOOL_NAMES = [
|
|
|
25
26
|
'hoi4.probability_analyze',
|
|
26
27
|
'hoi4.map_inspect',
|
|
27
28
|
'hoi4.map_rewrite',
|
|
29
|
+
'hoi4.localisation_write',
|
|
28
30
|
'hoi4.gui_inspect',
|
|
29
31
|
'hoi4.gui_render',
|
|
30
32
|
'hoi4.gui_rewrite',
|
|
@@ -46,6 +48,7 @@ export const DOMAIN_TOOL_ARGUMENT_SCHEMAS = {
|
|
|
46
48
|
'hoi4.probability_analyze': probabilityAnalyzeRequestSchema,
|
|
47
49
|
'hoi4.map_inspect': mapInspectRequestSchema,
|
|
48
50
|
'hoi4.map_rewrite': mapRewriteRequestSchema,
|
|
51
|
+
'hoi4.localisation_write': localisationWriteRequestSchema,
|
|
49
52
|
'hoi4.gui_inspect': guiInspectRequestSchema,
|
|
50
53
|
'hoi4.gui_render': guiRenderRequestSchema,
|
|
51
54
|
'hoi4.gui_rewrite': guiRewriteRequestSchema,
|
|
@@ -61,5 +64,6 @@ export function isDomainToolName(name) {
|
|
|
61
64
|
export const MUTATION_TOOL_NAMES = new Set([
|
|
62
65
|
'hoi4.gui_rewrite',
|
|
63
66
|
'hoi4.map_rewrite',
|
|
67
|
+
'hoi4.localisation_write',
|
|
64
68
|
'hoi4.focus_rewrite',
|
|
65
69
|
]);
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
import { runEngineCommand } from './engine-client.js';
|
|
3
|
+
import { ServiceError } from './result.js';
|
|
4
|
+
/**
|
|
5
|
+
* `hoi4-engine check` (ADR 0074) for the tools that judge a whole mod: one run reads every layer
|
|
6
|
+
* in load order and reports references, lints and the override audit. The tools read the fields
|
|
7
|
+
* below and ignore the rest, so the engine can add fields without breaking them.
|
|
8
|
+
*/
|
|
9
|
+
export const ENGINE_CHECK_SCHEMA = 'hoi4-engine-report/1';
|
|
10
|
+
/** A whole-mod check of a large mod reads every file of every layer. */
|
|
11
|
+
export const ENGINE_CHECK_TIMEOUT_MS = 180_000;
|
|
12
|
+
export const engineCheckFindingSchema = z.looseObject({
|
|
13
|
+
code: z.string().max(128),
|
|
14
|
+
severity: z.enum(['error', 'warning', 'info']),
|
|
15
|
+
message: z.string().max(4096),
|
|
16
|
+
/** Relative to the layer root, with forward slashes. */
|
|
17
|
+
path: z.string().max(4096),
|
|
18
|
+
/** The name of the layer that owns the file. */
|
|
19
|
+
layer: z.string().max(512),
|
|
20
|
+
line: z.number().int().min(0),
|
|
21
|
+
column: z.number().int().min(0),
|
|
22
|
+
subject: z.string().max(1024).optional(),
|
|
23
|
+
context: z.string().max(1024).optional(),
|
|
24
|
+
suggestion: z.string().max(1024).optional(),
|
|
25
|
+
fingerprint: z.string().max(128).optional(),
|
|
26
|
+
});
|
|
27
|
+
export const engineCheckLayerSchema = z.looseObject({
|
|
28
|
+
kind: z.string().max(32),
|
|
29
|
+
name: z.string().max(512),
|
|
30
|
+
path: z.string().max(4096),
|
|
31
|
+
replace_paths: z.array(z.string().max(1024)).max(4096),
|
|
32
|
+
});
|
|
33
|
+
export const engineCheckReportSchema = z.looseObject({
|
|
34
|
+
schema: z.literal(ENGINE_CHECK_SCHEMA),
|
|
35
|
+
engine_version: z.string().max(64),
|
|
36
|
+
verdict: z.string().max(32),
|
|
37
|
+
inputs: z.looseObject({
|
|
38
|
+
layers: z.array(engineCheckLayerSchema).max(512),
|
|
39
|
+
game_version: z.string().max(64).nullable().optional(),
|
|
40
|
+
}),
|
|
41
|
+
summary: z.looseObject({
|
|
42
|
+
errors: z.number().int().min(0),
|
|
43
|
+
warnings: z.number().int().min(0),
|
|
44
|
+
infos: z.number().int().min(0),
|
|
45
|
+
by_code: z.record(z.string(), z.number().int().min(0)),
|
|
46
|
+
}),
|
|
47
|
+
stats: z.looseObject({ elapsed_ms: z.number().min(0).optional() }),
|
|
48
|
+
overrides: z
|
|
49
|
+
.array(z.looseObject({
|
|
50
|
+
path: z.string().max(4096),
|
|
51
|
+
winner: z.string().max(512),
|
|
52
|
+
replaced: z.array(z.string().max(4096)).max(512),
|
|
53
|
+
}))
|
|
54
|
+
.max(100_000),
|
|
55
|
+
findings: z.array(engineCheckFindingSchema).max(1_000_000),
|
|
56
|
+
});
|
|
57
|
+
/**
|
|
58
|
+
* Run `hoi4-engine check --format json --fail-on never` on one mod. A missing engine is
|
|
59
|
+
* `ENGINE_UNAVAILABLE`; nothing falls back to TypeScript.
|
|
60
|
+
*/
|
|
61
|
+
export async function runEngineCheck(request, options = {}) {
|
|
62
|
+
const args = [
|
|
63
|
+
'--mod',
|
|
64
|
+
request.mod,
|
|
65
|
+
...(request.game === undefined ? [] : ['--game', request.game]),
|
|
66
|
+
...(request.dependencies ?? []).flatMap((dependency) => ['--dependency', dependency]),
|
|
67
|
+
...(request.includeDlc === false ? ['--no-dlc'] : []),
|
|
68
|
+
'--format',
|
|
69
|
+
'json',
|
|
70
|
+
'--fail-on',
|
|
71
|
+
'never',
|
|
72
|
+
];
|
|
73
|
+
const result = await runEngineCommand('check', null, engineCheckReportSchema, {
|
|
74
|
+
timeoutMs: ENGINE_CHECK_TIMEOUT_MS,
|
|
75
|
+
...options,
|
|
76
|
+
args,
|
|
77
|
+
});
|
|
78
|
+
if (!result.available)
|
|
79
|
+
throw new ServiceError('ENGINE_UNAVAILABLE', result.message, { reason: result.reason });
|
|
80
|
+
if (result.outcome === 'invalid_request')
|
|
81
|
+
throw new ServiceError(result.error.code, result.error.message);
|
|
82
|
+
return result.response;
|
|
83
|
+
}
|
|
84
|
+
/** The checked mod's own layer: the last one in load order that is not the game or a DLC. */
|
|
85
|
+
export function checkedLayerName(report) {
|
|
86
|
+
return report.inputs.layers.at(-1)?.name;
|
|
87
|
+
}
|
|
@@ -234,7 +234,7 @@ export async function runEngineCommand(subcommand, request, responseSchema, opti
|
|
|
234
234
|
binary,
|
|
235
235
|
});
|
|
236
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);
|
|
237
|
+
const outcome = await runProcess(binary.path, [subcommand, ...(options.args ?? [])], JSON.stringify(request), options.env ?? process.env, timeoutMs, options.maxOutputBytes ?? ENGINE_DEFAULT_MAX_OUTPUT_BYTES, options.signal);
|
|
238
238
|
if (outcome.kind === 'spawn_failed')
|
|
239
239
|
return unavailable('spawn_failed', `hoi4-engine could not start: ${clip(outcome.error ?? '')}`);
|
|
240
240
|
if (outcome.kind === 'timeout')
|
|
@@ -35,7 +35,8 @@ function under(roots, glob) {
|
|
|
35
35
|
function englishLocalisationPatterns(roots) {
|
|
36
36
|
return [...under(roots, 'english/**/*.{yml,yaml}'), ...under(roots, '*.{yml,yaml}')];
|
|
37
37
|
}
|
|
38
|
-
|
|
38
|
+
/** The glob patterns of the shared scan, relative to each root. `hoi4.mod_index` passes them to the engine. */
|
|
39
|
+
export function defaultPatterns(workspace) {
|
|
39
40
|
const roots = workspace.registration.roots;
|
|
40
41
|
return [
|
|
41
42
|
...new Set([
|
|
@@ -101,6 +102,7 @@ export class CoreEngine {
|
|
|
101
102
|
#scanGenerations = new Map();
|
|
102
103
|
#scanAdmissionQueue = [];
|
|
103
104
|
#activeScanAdmissions = new Set();
|
|
105
|
+
#recovery;
|
|
104
106
|
constructor(resolver, services = {}) {
|
|
105
107
|
this.resolver = resolver;
|
|
106
108
|
this.indexSegments = services.indexSegments ?? new IndexSegmentCache();
|
|
@@ -131,7 +133,21 @@ export class CoreEngine {
|
|
|
131
133
|
services.transactions ??
|
|
132
134
|
new TransactionManager(resolver, this.artifacts, RECOVERY_TTL_SECONDS, RECOVERY_MAX_BYTES, RECOVERY_MAX_RECORDS, resolver.serverState());
|
|
133
135
|
}
|
|
134
|
-
|
|
136
|
+
/**
|
|
137
|
+
* Recover interrupted internal rewrites in every workspace. A stdio server starts this in the
|
|
138
|
+
* background and answers the client handshake meanwhile; it holds workspace requests until
|
|
139
|
+
* {@link recovered} settles.
|
|
140
|
+
*/
|
|
141
|
+
initialize() {
|
|
142
|
+
const recovery = this.#recoverWorkspaces();
|
|
143
|
+
this.#recovery = recovery;
|
|
144
|
+
return recovery;
|
|
145
|
+
}
|
|
146
|
+
/** Settles when the latest {@link initialize} has finished, at once when none was started. */
|
|
147
|
+
recovered() {
|
|
148
|
+
return this.#recovery ?? Promise.resolve();
|
|
149
|
+
}
|
|
150
|
+
async #recoverWorkspaces() {
|
|
135
151
|
for (const workspace of this.resolver.list()) {
|
|
136
152
|
// Recovery repairs an interrupted internal rewrite before the workspace is exposed. A
|
|
137
153
|
// journal that cannot be recovered blocks rewrites of its own workspace, not the server.
|
|
@@ -23,6 +23,8 @@ export async function registerWorkerOperations(engine, toolName) {
|
|
|
23
23
|
(await import('../focus/job-operations.js')).registerFocusJobs(operations, engine);
|
|
24
24
|
else if (toolName.startsWith('hoi4.gui_'))
|
|
25
25
|
(await import('../gui/job-operations.js')).registerGuiJobs(operations, engine);
|
|
26
|
+
else if (toolName === 'hoi4.localisation_write')
|
|
27
|
+
(await import('../localisation/job-operations.js')).registerLocalisationJobs(operations, engine);
|
|
26
28
|
else if (toolName.startsWith('hoi4.map_'))
|
|
27
29
|
(await import('../map/job-operations.js')).registerMapJobs(operations, engine);
|
|
28
30
|
else if (toolName.startsWith('hoi4.probability_'))
|
|
@@ -42,7 +42,7 @@ const ownerSchema = z
|
|
|
42
42
|
.strict();
|
|
43
43
|
const requestSchema = z
|
|
44
44
|
.object({
|
|
45
|
-
toolName: z.string().regex(/^
|
|
45
|
+
toolName: z.string().regex(/^hoi4\.[a-z_]+$/u),
|
|
46
46
|
arguments: z.record(z.string(), z.json()),
|
|
47
47
|
mutation: z.boolean(),
|
|
48
48
|
requestKey: z.string().min(1).max(256).optional(),
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Native effect identifiers used to distinguish direct scripted-effect calls
|
|
3
3
|
* from engine effects while importing focus completion rewards.
|
|
4
4
|
*
|
|
5
|
-
* Generated by scripts/generate-native-effects.ts from the HOI4 1.19.4.
|
|
5
|
+
* Generated by scripts/generate-native-effects.ts from the HOI4 1.19.4.2 effects
|
|
6
6
|
* documentation. This is the fallback list; analysis also accepts every effect the installed
|
|
7
7
|
* game documents in documentation/effects_documentation.md, so effects added by later patches
|
|
8
8
|
* are recognized. The nightly game-update watcher regenerates it for review on a new build.
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
import { toolResult } from '../core/operation-result.js';
|
|
3
|
+
import { ServiceError } from '../core/result.js';
|
|
4
|
+
import { localisationWriteRequestSchema } from '../schemas/localisation-write.js';
|
|
5
|
+
import { completeLocalisationWrite, prepareLocalisationWrite, previewLocalisationWrite, } from './write-operations.js';
|
|
6
|
+
const wireResult = z.record(z.string(), z.json());
|
|
7
|
+
function wire(result) {
|
|
8
|
+
return wireResult.parse(JSON.parse(JSON.stringify(toolResult(result))));
|
|
9
|
+
}
|
|
10
|
+
/** Registers `hoi4.localisation_write`: a read-only preview, or one journaled transaction. */
|
|
11
|
+
export function registerLocalisationJobs(operations, engine) {
|
|
12
|
+
operations.registerWrite('hoi4.localisation_write', localisationWriteRequestSchema, async (input, context) => {
|
|
13
|
+
if (input.workspaceId !== 'current' && input.workspaceId !== context.workspaceId)
|
|
14
|
+
throw new ServiceError('JOB_ARGUMENT_SCOPE_MISMATCH', 'The request workspace does not match the authorized job workspace');
|
|
15
|
+
const operationContext = {
|
|
16
|
+
workspaceId: context.workspaceId,
|
|
17
|
+
...(context.principal === undefined ? {} : { principal: context.principal }),
|
|
18
|
+
signal: context.signal,
|
|
19
|
+
progress: (completed, total, message) => context.progress({ completed, total, message }),
|
|
20
|
+
};
|
|
21
|
+
if (!input.apply)
|
|
22
|
+
return {
|
|
23
|
+
readOnlyPreview: wire(await previewLocalisationWrite(engine, input, operationContext)),
|
|
24
|
+
};
|
|
25
|
+
const prepared = await prepareLocalisationWrite(engine, input, operationContext);
|
|
26
|
+
if ('readOnlyPreview' in prepared)
|
|
27
|
+
return { readOnlyPreview: wire(prepared.readOnlyPreview) };
|
|
28
|
+
return { transaction: prepared.transaction, recipe: { ...prepared.recipe } };
|
|
29
|
+
}, async (_input, execution, _reconciled, recipe, context) => {
|
|
30
|
+
const result = completeLocalisationWrite(context.workspaceId, execution, recipe);
|
|
31
|
+
await context.progress({
|
|
32
|
+
completed: 3,
|
|
33
|
+
total: 3,
|
|
34
|
+
message: execution.outcome === 'applied'
|
|
35
|
+
? 'Localisation change complete'
|
|
36
|
+
: execution.outcome === 'unchanged'
|
|
37
|
+
? 'Localisation already satisfied the request'
|
|
38
|
+
: 'Localisation change blocked',
|
|
39
|
+
});
|
|
40
|
+
return wire(result);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
const CONTEXT = 2;
|
|
2
|
+
const NO_NEWLINE = '\';
|
|
3
|
+
/** A byte order mark has no glyph, so a diff shows it as a marker on the first line. */
|
|
4
|
+
const BOM_MARK = '[BOM]';
|
|
5
|
+
/**
|
|
6
|
+
* The unified diff of a document against the file as it was read. Edits only replace a line in
|
|
7
|
+
* place or insert lines, so each line carries what it was and the diff needs no search. Context is
|
|
8
|
+
* two lines. `budgetBytes` cuts the diff at a line boundary and says how many lines it omitted.
|
|
9
|
+
*/
|
|
10
|
+
export function documentDiff(document, relativePath, budgetBytes) {
|
|
11
|
+
const created = document.encoding === 'new';
|
|
12
|
+
const bomChanged = created || document.target !== document.encoding;
|
|
13
|
+
const rows = [];
|
|
14
|
+
const oldNumbers = [];
|
|
15
|
+
const newNumbers = [];
|
|
16
|
+
let oldNumber = 0;
|
|
17
|
+
let newNumber = 0;
|
|
18
|
+
for (const [index, line] of document.lines.entries()) {
|
|
19
|
+
const mark = index === 0 && bomChanged ? BOM_MARK : '';
|
|
20
|
+
newNumber += 1;
|
|
21
|
+
if (line.orig === null) {
|
|
22
|
+
rows.push({ type: '+', text: mark + line.content, noEol: line.eol === '' });
|
|
23
|
+
oldNumbers.push(oldNumber);
|
|
24
|
+
newNumbers.push(newNumber);
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
oldNumber += 1;
|
|
28
|
+
const changed = line.content !== line.origContent || line.eol !== line.origEol || mark !== '';
|
|
29
|
+
if (!changed) {
|
|
30
|
+
rows.push({ type: ' ', text: line.content, noEol: line.eol === '' });
|
|
31
|
+
oldNumbers.push(oldNumber);
|
|
32
|
+
newNumbers.push(newNumber);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
rows.push({ type: '-', text: line.origContent, noEol: line.origEol === '' });
|
|
36
|
+
oldNumbers.push(oldNumber);
|
|
37
|
+
newNumbers.push(newNumber);
|
|
38
|
+
rows.push({ type: '+', text: mark + line.content, noEol: line.eol === '' });
|
|
39
|
+
oldNumbers.push(oldNumber);
|
|
40
|
+
newNumbers.push(newNumber);
|
|
41
|
+
}
|
|
42
|
+
const header = created
|
|
43
|
+
? ['--- /dev/null', `+++ b/${relativePath}`]
|
|
44
|
+
: [
|
|
45
|
+
`--- a/${relativePath}${document.encoding.startsWith('utf16') ? ` (${document.encoding})` : ''}`,
|
|
46
|
+
`+++ b/${relativePath}${document.target !== document.encoding ? ' (utf-8 with BOM)' : ''}`,
|
|
47
|
+
];
|
|
48
|
+
const changedAt = rows.flatMap((row, index) => (row.type === ' ' ? [] : [index]));
|
|
49
|
+
const output = [...header];
|
|
50
|
+
let bytes = header.join('\n').length;
|
|
51
|
+
let truncated = false;
|
|
52
|
+
let omitted = 0;
|
|
53
|
+
let cursor = 0;
|
|
54
|
+
for (let at = 0; at < changedAt.length;) {
|
|
55
|
+
let last = changedAt[at];
|
|
56
|
+
let next = at + 1;
|
|
57
|
+
while (next < changedAt.length && changedAt[next] - last <= CONTEXT * 2 + 1) {
|
|
58
|
+
last = changedAt[next];
|
|
59
|
+
next += 1;
|
|
60
|
+
}
|
|
61
|
+
const start = Math.max(cursor, changedAt[at] - CONTEXT);
|
|
62
|
+
const end = Math.min(rows.length - 1, last + CONTEXT);
|
|
63
|
+
const slice = rows.slice(start, end + 1);
|
|
64
|
+
const oldCount = slice.filter(({ type }) => type !== '+').length;
|
|
65
|
+
const newCount = slice.filter(({ type }) => type !== '-').length;
|
|
66
|
+
const firstOld = slice.findIndex(({ type }) => type !== '+');
|
|
67
|
+
const firstNew = slice.findIndex(({ type }) => type !== '-');
|
|
68
|
+
const oldStart = oldCount === 0 ? oldNumbers[start] : oldNumbers[start + firstOld];
|
|
69
|
+
const newStart = newCount === 0 ? newNumbers[start] : newNumbers[start + firstNew];
|
|
70
|
+
const lines = [`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`];
|
|
71
|
+
for (const row of slice) {
|
|
72
|
+
lines.push(`${row.type}${row.text}`);
|
|
73
|
+
if (row.noEol)
|
|
74
|
+
lines.push(NO_NEWLINE);
|
|
75
|
+
}
|
|
76
|
+
for (const [offset, line] of lines.entries()) {
|
|
77
|
+
bytes += Buffer.byteLength(line, 'utf8') + 1;
|
|
78
|
+
if (bytes > budgetBytes) {
|
|
79
|
+
omitted += lines.length - offset;
|
|
80
|
+
truncated = true;
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
output.push(line);
|
|
84
|
+
}
|
|
85
|
+
if (truncated) {
|
|
86
|
+
for (let rest = next; rest < changedAt.length; rest += 1)
|
|
87
|
+
omitted += 1;
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
cursor = end + 1;
|
|
91
|
+
at = next;
|
|
92
|
+
}
|
|
93
|
+
if (truncated)
|
|
94
|
+
output.push(`... diff truncated, about ${omitted} more lines`);
|
|
95
|
+
return { diff: output.join('\n'), truncated };
|
|
96
|
+
}
|