hoi4-agent-tools 4.6.5 → 4.7.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 +16 -5
- package/dist/hoi4_agent_tools/core/engine-client.js +273 -0
- package/dist/hoi4_agent_tools/core/operation-result.js +24 -5
- 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/job-operations.js +3 -1
- package/dist/hoi4_agent_tools/focus/layout.js +3 -2
- 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 +202 -0
- package/dist/hoi4_agent_tools/focus/quality/positions.js +41 -0
- package/dist/hoi4_agent_tools/focus/quality/schematic.js +241 -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/tool-operations.js +206 -22
- package/dist/hoi4_agent_tools/focus/tool-support.js +1 -1
- package/dist/hoi4_agent_tools/mcp/server/instructions.js +1 -1
- package/dist/hoi4_agent_tools/mcp/tools/focus.js +76 -4
- package/dist/hoi4_agent_tools/reference/game-text.js +109 -0
- package/dist/hoi4_agent_tools/reference/ranking.js +60 -2
- package/dist/hoi4_agent_tools/reference/service.js +92 -21
- package/dist/hoi4_agent_tools/schemas/focus-requests.js +64 -7
- package/dist/hoi4_agent_tools/schemas/focus.js +121 -6
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +17 -17
- package/docs/focus.md +100 -4
- package/docs/reference.md +1 -1
- package/docs/research/reference-benchmark.md +111 -1
- package/docs/setup.md +1 -1
- package/docs/tools.md +5 -5
- package/npm-shrinkwrap.json +2 -2
- package/package.json +2 -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,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 4.7.0 - 2026-11-02
|
|
4
|
+
|
|
5
|
+
- 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.
|
|
6
|
+
- 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.
|
|
7
|
+
- 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.
|
|
8
|
+
- 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.
|
|
9
|
+
- 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).
|
|
10
|
+
- 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.
|
|
11
|
+
- 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.
|
|
12
|
+
- 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.
|
|
13
|
+
- 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.
|
|
14
|
+
- 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`.
|
|
15
|
+
- 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.
|
|
16
|
+
- 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).
|
|
17
|
+
- 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.
|
|
18
|
+
|
|
3
19
|
## 4.6.5 - 2026-11-01
|
|
4
20
|
|
|
5
21
|
- 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 +35,6 @@
|
|
|
19
35
|
|
|
20
36
|
- 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
37
|
|
|
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
38
|
## 4.6.1 - 2026-10-26
|
|
28
39
|
|
|
29
40
|
- Stop flagging `constant:<category>.<key>` script-constant reads as scoped temporary-variable reads (`KNOWN_MISTAKE_TEMP_VARIABLE_SCOPE_PREFIX`).
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { statSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { z } from 'zod/v4';
|
|
6
|
+
/**
|
|
7
|
+
* Client for the shared Rust engine (`hoi4-engine`, ADR 0074). It runs the binary with a JSON
|
|
8
|
+
* request on stdin and validates the JSON it prints. A missing binary, a crash, a timeout or
|
|
9
|
+
* output that does not match the schema is reported as `available: false` with a reason; the
|
|
10
|
+
* caller decides what to tell the agent. Nothing here falls back to a TypeScript implementation.
|
|
11
|
+
*/
|
|
12
|
+
export const ENGINE_BINARY_ENV = 'HOI4_ENGINE';
|
|
13
|
+
export const ENGINE_DEFAULT_TIMEOUT_MS = 30_000;
|
|
14
|
+
export const ENGINE_DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
|
|
15
|
+
const ENGINE_STDERR_TAIL_BYTES = 4096;
|
|
16
|
+
const ENGINE_REASON_TEXT_LIMIT = 300;
|
|
17
|
+
function defaultPackageRoot() {
|
|
18
|
+
// src/hoi4_agent_tools/core and dist/hoi4_agent_tools/core both sit three levels below the root.
|
|
19
|
+
return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
|
|
20
|
+
}
|
|
21
|
+
function isFile(candidate) {
|
|
22
|
+
try {
|
|
23
|
+
return statSync(candidate).isFile();
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** The bundled binary's path for this platform, whether or not it exists. */
|
|
30
|
+
export function packagedEngineBinaryPath(packageRoot = defaultPackageRoot(), platform = process.platform, arch = process.arch) {
|
|
31
|
+
return path.join(packageRoot, 'engine', 'bin', `${platform}-${arch}`, platform === 'win32' ? 'hoi4-engine.exe' : 'hoi4-engine');
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* `HOI4_ENGINE` (an absolute path) wins; a set but unusable `HOI4_ENGINE` is reported instead of
|
|
35
|
+
* silently using the bundled binary. Otherwise the package's own `engine/bin` binary, if present.
|
|
36
|
+
*/
|
|
37
|
+
export function locateEngineBinary(options = {}) {
|
|
38
|
+
const configured = (options.env ?? process.env)[ENGINE_BINARY_ENV];
|
|
39
|
+
if (configured !== undefined && configured !== '') {
|
|
40
|
+
if (!path.isAbsolute(configured))
|
|
41
|
+
return {
|
|
42
|
+
reason: 'binary_path_invalid',
|
|
43
|
+
message: `${ENGINE_BINARY_ENV} must be an absolute path to the hoi4-engine binary`,
|
|
44
|
+
};
|
|
45
|
+
if (!isFile(configured))
|
|
46
|
+
return {
|
|
47
|
+
reason: 'binary_not_found',
|
|
48
|
+
message: `${ENGINE_BINARY_ENV} names a file that does not exist`,
|
|
49
|
+
};
|
|
50
|
+
return { path: configured, source: 'environment' };
|
|
51
|
+
}
|
|
52
|
+
const packaged = packagedEngineBinaryPath(options.packageRoot ?? defaultPackageRoot());
|
|
53
|
+
if (isFile(packaged))
|
|
54
|
+
return { path: packaged, source: 'package' };
|
|
55
|
+
return {
|
|
56
|
+
reason: 'binary_not_found',
|
|
57
|
+
message: `No hoi4-engine binary for ${process.platform}-${process.arch} is installed with this package and ${ENGINE_BINARY_ENV} is not set`,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function clip(text) {
|
|
61
|
+
const single = text.replace(/\s+/gu, ' ').trim();
|
|
62
|
+
return single.length <= ENGINE_REASON_TEXT_LIMIT
|
|
63
|
+
? single
|
|
64
|
+
: `${single.slice(0, ENGINE_REASON_TEXT_LIMIT)}…`;
|
|
65
|
+
}
|
|
66
|
+
function runProcess(binary, args, input, env, timeoutMs, maxOutputBytes, signal) {
|
|
67
|
+
// A JavaScript engine (a development wrapper or a test double) runs under this Node, still
|
|
68
|
+
// without a shell, because Windows cannot execute a script file directly.
|
|
69
|
+
const script = /\.(?:c|m)?js$/iu.test(binary);
|
|
70
|
+
const command = script ? process.execPath : binary;
|
|
71
|
+
const commandArgs = script ? [binary, ...args] : [...args];
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
let settled = false;
|
|
74
|
+
let stdoutBytes = 0;
|
|
75
|
+
const stdout = [];
|
|
76
|
+
let stderr = Buffer.alloc(0);
|
|
77
|
+
let ending;
|
|
78
|
+
const child = spawn(command, commandArgs, {
|
|
79
|
+
shell: false,
|
|
80
|
+
windowsHide: true,
|
|
81
|
+
env,
|
|
82
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
83
|
+
});
|
|
84
|
+
const stop = (kind) => {
|
|
85
|
+
ending ??= kind;
|
|
86
|
+
child.kill();
|
|
87
|
+
};
|
|
88
|
+
const timer = setTimeout(() => stop('timeout'), timeoutMs);
|
|
89
|
+
const onAbort = () => {
|
|
90
|
+
if (settled)
|
|
91
|
+
return;
|
|
92
|
+
settled = true;
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
child.kill();
|
|
95
|
+
const reason = signal?.reason;
|
|
96
|
+
reject(reason instanceof Error ? reason : new Error('The engine call was cancelled'));
|
|
97
|
+
};
|
|
98
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
99
|
+
const finish = (outcome) => {
|
|
100
|
+
if (settled)
|
|
101
|
+
return;
|
|
102
|
+
settled = true;
|
|
103
|
+
clearTimeout(timer);
|
|
104
|
+
signal?.removeEventListener('abort', onAbort);
|
|
105
|
+
resolve(outcome);
|
|
106
|
+
};
|
|
107
|
+
child.stdout.on('data', (chunk) => {
|
|
108
|
+
stdoutBytes += chunk.length;
|
|
109
|
+
if (stdoutBytes > maxOutputBytes)
|
|
110
|
+
stop('output_too_large');
|
|
111
|
+
else
|
|
112
|
+
stdout.push(chunk);
|
|
113
|
+
});
|
|
114
|
+
child.stderr.on('data', (chunk) => {
|
|
115
|
+
stderr = Buffer.concat([stderr, chunk]);
|
|
116
|
+
if (stderr.length > ENGINE_STDERR_TAIL_BYTES)
|
|
117
|
+
stderr = stderr.subarray(stderr.length - ENGINE_STDERR_TAIL_BYTES);
|
|
118
|
+
});
|
|
119
|
+
child.on('error', (error) => finish({
|
|
120
|
+
kind: 'spawn_failed',
|
|
121
|
+
code: null,
|
|
122
|
+
signal: null,
|
|
123
|
+
stdout: Buffer.alloc(0),
|
|
124
|
+
stderrTail: '',
|
|
125
|
+
error: error.message,
|
|
126
|
+
}));
|
|
127
|
+
child.on('close', (code, exitSignal) => finish({
|
|
128
|
+
kind: ending ?? 'exited',
|
|
129
|
+
code,
|
|
130
|
+
signal: exitSignal,
|
|
131
|
+
stdout: Buffer.concat(stdout),
|
|
132
|
+
stderrTail: stderr.toString('utf8'),
|
|
133
|
+
}));
|
|
134
|
+
// The engine may exit before reading all of stdin (for example on a usage error).
|
|
135
|
+
child.stdin.on('error', () => undefined);
|
|
136
|
+
child.stdin.end(input, 'utf8');
|
|
137
|
+
if (signal?.aborted === true)
|
|
138
|
+
onAbort();
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
const engineInvalidSchema = z
|
|
142
|
+
.object({
|
|
143
|
+
schema: z.string(),
|
|
144
|
+
status: z.literal('invalid'),
|
|
145
|
+
error: z.object({ code: z.string(), message: z.string() }).strict(),
|
|
146
|
+
})
|
|
147
|
+
.strict();
|
|
148
|
+
/** Run one engine subcommand with a JSON request and validate its JSON response. */
|
|
149
|
+
export async function runEngineCommand(subcommand, request, responseSchema, options = {}) {
|
|
150
|
+
options.signal?.throwIfAborted();
|
|
151
|
+
const located = locateEngineBinary(options);
|
|
152
|
+
if (!('path' in located))
|
|
153
|
+
return {
|
|
154
|
+
available: false,
|
|
155
|
+
outcome: 'unavailable',
|
|
156
|
+
reason: located.reason,
|
|
157
|
+
message: located.message,
|
|
158
|
+
};
|
|
159
|
+
const binary = located;
|
|
160
|
+
const unavailable = (reason, message) => ({
|
|
161
|
+
available: false,
|
|
162
|
+
outcome: 'unavailable',
|
|
163
|
+
reason,
|
|
164
|
+
message,
|
|
165
|
+
binary,
|
|
166
|
+
});
|
|
167
|
+
const timeoutMs = options.timeoutMs ?? ENGINE_DEFAULT_TIMEOUT_MS;
|
|
168
|
+
const outcome = await runProcess(binary.path, [subcommand], JSON.stringify(request), options.env ?? process.env, timeoutMs, options.maxOutputBytes ?? ENGINE_DEFAULT_MAX_OUTPUT_BYTES, options.signal);
|
|
169
|
+
if (outcome.kind === 'spawn_failed')
|
|
170
|
+
return unavailable('spawn_failed', `hoi4-engine could not start: ${clip(outcome.error ?? '')}`);
|
|
171
|
+
if (outcome.kind === 'timeout')
|
|
172
|
+
return unavailable('timeout', `hoi4-engine ${subcommand} did not finish within ${timeoutMs} ms`);
|
|
173
|
+
if (outcome.kind === 'output_too_large')
|
|
174
|
+
return unavailable('output_too_large', `hoi4-engine ${subcommand} printed more than ${options.maxOutputBytes ?? ENGINE_DEFAULT_MAX_OUTPUT_BYTES} bytes`);
|
|
175
|
+
let parsed;
|
|
176
|
+
try {
|
|
177
|
+
parsed = JSON.parse(outcome.stdout.toString('utf8'));
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
parsed = undefined;
|
|
181
|
+
}
|
|
182
|
+
if (outcome.code === 2) {
|
|
183
|
+
const invalid = engineInvalidSchema.safeParse(parsed);
|
|
184
|
+
if (invalid.success)
|
|
185
|
+
return { available: true, outcome: 'invalid_request', binary, error: invalid.data.error };
|
|
186
|
+
}
|
|
187
|
+
if (outcome.code !== 0)
|
|
188
|
+
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)}`}`);
|
|
189
|
+
if (parsed === undefined)
|
|
190
|
+
return unavailable('invalid_output', `hoi4-engine ${subcommand} did not print JSON`);
|
|
191
|
+
const response = responseSchema.safeParse(parsed);
|
|
192
|
+
if (!response.success)
|
|
193
|
+
return unavailable('invalid_output', `hoi4-engine ${subcommand} printed a response that does not match its schema: ${clip(response.error.issues
|
|
194
|
+
.slice(0, 3)
|
|
195
|
+
.map((issue) => `${issue.path.join('.') || '(root)'} ${issue.message}`)
|
|
196
|
+
.join('; '))}`);
|
|
197
|
+
return { available: true, outcome: 'response', binary, response: response.data };
|
|
198
|
+
}
|
|
199
|
+
// ---------------------------------------------------------------------------------------------
|
|
200
|
+
// focus-layout (engine/crates/focus/schemas/*.json)
|
|
201
|
+
export const FOCUS_LAYOUT_REQUEST_SCHEMA = 'hoi4-focus-layout-request/1';
|
|
202
|
+
export const FOCUS_LAYOUT_RESPONSE_SCHEMA = 'hoi4-focus-layout/1';
|
|
203
|
+
const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/u);
|
|
204
|
+
const shiftSchema = z
|
|
205
|
+
.object({
|
|
206
|
+
fromX: z.number().int(),
|
|
207
|
+
columns: z.number().int().min(1),
|
|
208
|
+
direction: z.enum(['right', 'left']),
|
|
209
|
+
focusIds: z.array(z.string()),
|
|
210
|
+
})
|
|
211
|
+
.strict();
|
|
212
|
+
export const focusLayoutEngineResponseSchema = z
|
|
213
|
+
.object({
|
|
214
|
+
schema: z.literal(FOCUS_LAYOUT_RESPONSE_SCHEMA),
|
|
215
|
+
status: z.enum(['ok', 'blocked']),
|
|
216
|
+
operation: z.enum(['layout', 'insert']),
|
|
217
|
+
treeId: z.string().optional(),
|
|
218
|
+
nodes: z.array(z
|
|
219
|
+
.object({
|
|
220
|
+
id: z.string(),
|
|
221
|
+
x: z.number().int(),
|
|
222
|
+
y: z.number().int(),
|
|
223
|
+
laneId: z.string(),
|
|
224
|
+
moved: z.boolean(),
|
|
225
|
+
})
|
|
226
|
+
.strict()),
|
|
227
|
+
source: z.array(z
|
|
228
|
+
.object({
|
|
229
|
+
id: z.string(),
|
|
230
|
+
relativeTo: z.string().optional(),
|
|
231
|
+
x: z.number().int(),
|
|
232
|
+
y: z.number().int(),
|
|
233
|
+
})
|
|
234
|
+
.strict()),
|
|
235
|
+
diagnostics: z.array(z
|
|
236
|
+
.object({
|
|
237
|
+
code: z.string().regex(/^FOCUS_ENGINE_[A-Z_]+$/u),
|
|
238
|
+
severity: z.enum(['error', 'warning', 'info']),
|
|
239
|
+
focusIds: z.array(z.string()),
|
|
240
|
+
message: z.string(),
|
|
241
|
+
details: z.record(z.string(), z.unknown()),
|
|
242
|
+
})
|
|
243
|
+
.strict()),
|
|
244
|
+
metrics: z
|
|
245
|
+
.object({
|
|
246
|
+
columns: z.number().int().min(0),
|
|
247
|
+
rows: z.number().int().min(0),
|
|
248
|
+
orthogonalCrossings: z.number().int().min(0),
|
|
249
|
+
stemsThroughPlaques: z.number().int().min(0),
|
|
250
|
+
mergedBars: z.number().int().min(0),
|
|
251
|
+
durationMicros: z.number().int().min(0),
|
|
252
|
+
})
|
|
253
|
+
.strict()
|
|
254
|
+
.nullable(),
|
|
255
|
+
hashes: z
|
|
256
|
+
.object({
|
|
257
|
+
layout: sha256Schema.nullable(),
|
|
258
|
+
untouched: sha256Schema,
|
|
259
|
+
prerequisites: sha256Schema,
|
|
260
|
+
exclusions: sha256Schema,
|
|
261
|
+
})
|
|
262
|
+
.strict(),
|
|
263
|
+
needsRoom: z
|
|
264
|
+
.object({ shift: z.array(shiftSchema) })
|
|
265
|
+
.strict()
|
|
266
|
+
.optional(),
|
|
267
|
+
shifted: z.array(shiftSchema).optional(),
|
|
268
|
+
})
|
|
269
|
+
.strict();
|
|
270
|
+
/** `hoi4-engine focus-layout` with the request on stdin. */
|
|
271
|
+
export function runFocusLayoutEngine(request, options = {}) {
|
|
272
|
+
return runEngineCommand('focus-layout', request, focusLayoutEngineResponseSchema, options);
|
|
273
|
+
}
|
|
@@ -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,6 +444,7 @@ 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
|
: {}),
|
|
@@ -460,23 +466,36 @@ function buildToolResult(selected) {
|
|
|
460
466
|
...(selected.status === 'error' ? { isError: true } : {}),
|
|
461
467
|
};
|
|
462
468
|
}
|
|
463
|
-
export function toolResult(result) {
|
|
469
|
+
export function toolResult(result, options = {}) {
|
|
470
|
+
let imageCharacters = 0;
|
|
471
|
+
const images = (options.images ?? []).filter((image) => {
|
|
472
|
+
imageCharacters += image.data.length;
|
|
473
|
+
return imageCharacters <= MAX_TOOL_RESULT_IMAGE_CHARACTERS;
|
|
474
|
+
});
|
|
464
475
|
const completeResult = preserveDeferredFilesDiagnostic(result);
|
|
465
476
|
const compact = compactDescriptions(completeResult);
|
|
466
477
|
const estimatedBytes = jsonBytesWithin(compact, MAX_TOOL_RESULT_BYTES)
|
|
467
478
|
? Buffer.byteLength(canonicalJson(compact), 'utf8')
|
|
468
479
|
: MAX_TOOL_RESULT_BYTES + 1;
|
|
469
480
|
const selected = estimatedBytes > MAX_TOOL_RESULT_BYTES ? boundedResult(compact, estimatedBytes) : compact;
|
|
470
|
-
let output = buildToolResult(selected);
|
|
481
|
+
let output = buildToolResult(selected, images.length);
|
|
471
482
|
const wireBytes = Buffer.byteLength(canonicalJson(output), 'utf8');
|
|
472
483
|
if (wireBytes > MAX_TOOL_RESULT_BYTES) {
|
|
473
|
-
output = buildToolResult(boundedResult(compact, wireBytes));
|
|
484
|
+
output = buildToolResult(boundedResult(compact, wireBytes), images.length);
|
|
474
485
|
}
|
|
475
486
|
const finalBytes = Buffer.byteLength(canonicalJson(output), 'utf8');
|
|
476
487
|
if (finalBytes > MAX_TOOL_RESULT_BYTES) {
|
|
477
488
|
throw new Error('Constant MCP response-limit result exceeded its wire budget');
|
|
478
489
|
}
|
|
479
|
-
|
|
490
|
+
if (images.length === 0)
|
|
491
|
+
return output;
|
|
492
|
+
return {
|
|
493
|
+
...output,
|
|
494
|
+
content: [
|
|
495
|
+
...output.content,
|
|
496
|
+
...images.map(({ data, mimeType }) => ({ type: 'image', data, mimeType })),
|
|
497
|
+
],
|
|
498
|
+
};
|
|
480
499
|
}
|
|
481
500
|
/** Paths in a message can name private folders; the file name is enough to act on. */
|
|
482
501
|
function withoutDirectories(message) {
|