hoi4-agent-tools 4.20.3 → 4.21.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 +15 -0
- package/dist/hoi4_agent_tools/characters/write-operations.js +2 -2
- package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
- package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
- package/dist/hoi4_agent_tools/core/configuration.js +6 -0
- package/dist/hoi4_agent_tools/core/engine.js +67 -21
- package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
- package/dist/hoi4_agent_tools/core/operation-tasks.js +3 -1
- package/dist/hoi4_agent_tools/core/transactions.js +6 -0
- package/dist/hoi4_agent_tools/core/workspace.js +14 -1
- package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
- package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
- package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
- package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
- package/dist/hoi4_agent_tools/event/graph.js +3 -3
- package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
- package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
- package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
- package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/gui/assets.js +3 -13
- package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/gui/layout.js +2 -4
- package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
- package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
- package/dist/hoi4_agent_tools/gui/studio.js +31 -0
- package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
- package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
- package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
- package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/map/model.js +17 -3
- package/dist/hoi4_agent_tools/map/validation.js +12 -18
- package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
- package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/runtime.js +4 -2
- package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
- package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
- package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
- package/dist/hoi4_agent_tools/technology/operations.js +1 -2
- package/dist/hoi4_agent_tools/technology/service.js +30 -59
- package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
- package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
- package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/configuration.md +11 -10
- package/docs/troubleshooting.md +11 -11
- 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 +2 -2
- package/schemas/configuration.schema.json +143 -134
- 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 +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
|
@@ -2,6 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 4.21.0 - 2026-11-28
|
|
6
|
+
|
|
7
|
+
- Fixed `hoi4.gui_inspect` and `hoi4.gui_render` reporting false unresolved references: a sprite or font of another window in the inspected window's `.gui` file, or one a kept script names, now resolves from its `.gfx` file in the game or the mod instead of being reported as missing because that file was left out of the window graph, and a static GUI text that is not in the form of a localisation key (such as `Title text here!` or `--`) is drawn as written, as the game does, instead of being reported as a missing key. A missing sprite and a missing key in key form are still reported.
|
|
8
|
+
- Fixed `hoi4.gui_render` drawing a masked flag shield (a `maskedShieldType` sprite such as the base game's small flag) as its overlay only, with no flag colours. The mask was applied by brightness when its alpha was uniform, so the game's black, fully opaque mask cut the whole flag away. The renderer now uses only the mask's alpha, as the game's masked flag shader does.
|
|
9
|
+
- The idle release of a server's in-memory analysis caches is now a setting, `idleCacheReleaseSeconds` (issue 296). The scan, index and view caches were already released 30 s after the last tool call, but the 30 s was fixed and undocumented. The default stays 30; `0` releases the caches as soon as a call ends, and the maximum is 3,600. It is listed in the configuration table and in `configuration.schema.json`.
|
|
10
|
+
- The idea, character, decision, doctrine, technology and event writers now plan their edits in the Rust engine (`hoi4-script-write`, packet P10 of ADR 0089). Each is one engine operation, `<writer>_write.plan`, that reads the source bytes it is given and answers with the edit and the bytes of the file after it; it never writes. The tools, their inputs, results, codes and messages are unchanged, and a missing engine is `ENGINE_UNAVAILABLE`. The localisation writer is still on the TypeScript path.
|
|
11
|
+
- Map validation (the checks before and after every map rewrite, and the map validation itself) now runs on the shared Rust engine (`hoi4-map`, ADR 0089 step 6). The engine reads each scanned file by path and refuses one whose size or SHA-256 changed since the scan, and a map whose in-memory files exceed one request is refused with `MAP_ENGINE_PAYLOAD_LIMIT` instead of being validated in part. On seven large maps the findings, their order, `passed` and every check match the earlier TypeScript checks exactly. Building and position records have their own 2,000,000-record ceiling, so a mod with very large position tables is no longer refused (issue 172).
|
|
12
|
+
- The artifact store, unified and binary diffs, the changed-files summary, managed output inventories, the offline PNG comparison and the scratch-directory sweep now exist in the Rust engine (`hoi4-artifacts`, packet P3 of ADR 0089), reachable as the `artifacts.*` and `diff.*` operations. Store layout, names, manifests, URIs, limits, pruning and error codes are the TypeScript ones, so both servers read each other's stores. The text diff is byte-equal to the TypeScript one. The managed-output planner takes its path predicates as data (`PathRule`) instead of functions. The Node server does not call them yet.
|
|
13
|
+
- The minimum Rust version of the engine workspace is now 1.89, for std `File::lock` (the artifact publish lock). The pinned toolchain stays 1.97.1.
|
|
14
|
+
- The engine's artifact store keeps a claim for every put on disk, under its publication lock, until the caller commits (`artifacts.commit`) or releases it, so a rollback or eviction in one engine process never removes what another process reused or has not yet committed; claims expire after ten minutes. A put's stale list of pins is refused after a commit (`retentionEpoch`). `diff.text` carries both texts and the diff as payload, and engine errors carry their fields at the top level like the other operations. Process liveness, file identity and the host name come from the new `hoi4-os` crate, the only crate that may use `unsafe`.
|
|
15
|
+
- `hoi4.tech_inspect` builds its technology graph and answers the modes scan, folders, trace, explain, unlocks, bonus_coverage, lint and impact on the Rust engine (`tech.analyze`, `tech.graph`, `tech.query`), with the same wire shapes, codes and messages; a missing engine is `ENGINE_UNAVAILABLE`. Render, compare and helper_expansion still use the TypeScript analysis until the artifact store and GUI packets land.
|
|
16
|
+
- The Rust `hoi4-event` crate gains the event analysis as engine operations: `event.fragments` (source files to their nodes, edges, state accesses and findings), `event.graph` (the semantic graph with helper projections, state links and findings, built from fragments or straight from files the engine reads itself by path and refuses when they changed since the scan) and the graph algorithms `event.trace`, `event.path`, `event.components` and `event.reachable`. The TypeScript server does not call them yet, so no tool changes behavior. A parity script (`scripts/event-parity.ts`) compares each operation with the TypeScript implementation.
|
|
17
|
+
- An idle stdio server no longer loads or recovers any workspace (issues 292 and 296). Since the handshake fix it still loaded every mod and recovered every workspace's journals in the background right after `initialize`, which is why idle servers held 386 to 669 MB of private memory with a configuration, against about 110 MB without one. Now `initialize`, `tools/list` and `prompts/list` start nothing. The first tool call, resource read or other request that needs a workspace loads the workspaces, and each workspace's interrupted rewrite is recovered once on that workspace's first use: before its first file access through the resolver, before its first job is submitted and before its first rewrite is planned or applied. A failed recovery is still recorded with the `transaction_recovery_blocked` event, reads go on, and rewrites of that workspace are refused with `TRANSACTION_RECOVERY_REQUIRED`, as before. Releasing a workspace's caches after an idle period is not part of this change and stays with issue 296.
|
|
18
|
+
- The shared Rust engine now has the atomic rewrite engine (`hoi4-txn`, packet P2 of ADR 0091), with the engine operations `txn.apply` and `txn.recover`. It writes a rewrite plan whole or refuses it: paths go through the engine's one path resolver, duplicates and aliases are refused, sources are checked against the hashes their writer read under the workspace lock, and the before and after bytes are journaled in the TypeScript journal format, authenticated with the server's journal key and recorded as protected heads. Each file is replaced by rename after a write-ahead intent per batch, the written bytes are verified, and a failure restores every file without overwriting bytes the rewrite did not produce. Interrupted rewrites are recovered before the next one, and either server recovers the other's journal. A rollback that has to refuse removes the backups of files still holding its result and names the rest, as the TypeScript manager does since 4.20.1. The TypeScript transaction manager still serves every rewrite tool until the writers move onto the engine; nothing changes for agents yet.
|
|
19
|
+
|
|
5
20
|
## 4.20.3 - 2026-11-27
|
|
6
21
|
|
|
7
22
|
- Fixed recovery of an interrupted rewrite of more than 1,024 files, which failed with `TRANSACTION_MANIFEST_INVALID` and blocked rewrites of that workspace. Such rewrites replace files in batches of up to 256, but the journal check accepted at most 16 pending files per batch.
|
|
@@ -117,7 +117,7 @@ export async function computeCharacterWrite(engine, input, context, applied) {
|
|
|
117
117
|
let plan;
|
|
118
118
|
if ('file' in target) {
|
|
119
119
|
file = target.file;
|
|
120
|
-
plan = planCharacterWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
|
|
120
|
+
plan = await planCharacterWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
|
|
121
121
|
}
|
|
122
122
|
else {
|
|
123
123
|
const inMod = snapshot.index
|
|
@@ -128,7 +128,7 @@ export async function computeCharacterWrite(engine, input, context, applied) {
|
|
|
128
128
|
id: input.id,
|
|
129
129
|
path: inMod.path,
|
|
130
130
|
});
|
|
131
|
-
plan = planNewCharacterFile(target.newPath, planInput);
|
|
131
|
+
plan = await planNewCharacterFile(target.newPath, planInput);
|
|
132
132
|
}
|
|
133
133
|
const missing = { localisation: [], portrait: [] };
|
|
134
134
|
const diagnostics = [];
|
|
@@ -1,210 +1,26 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
:
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if (characters.value.type !== 'block')
|
|
20
|
-
continue;
|
|
21
|
-
const outer = lineIndent(document.text, characters.start);
|
|
22
|
-
for (const character of assignments(characters.value)) {
|
|
23
|
-
const inner = lineIndent(document.text, character.start);
|
|
24
|
-
if (inner.length > outer.length && inner.startsWith(outer))
|
|
25
|
-
return inner.slice(outer.length);
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
return '\t';
|
|
29
|
-
}
|
|
30
|
-
/** The body, checked on its own as the block it will become. */
|
|
31
|
-
function assertBodyIsOneBlock(id, body) {
|
|
32
|
-
const probe = parseClausewitz(Buffer.from(`${id} = {\n${body}\n}\n`, 'utf8'), 'character-body');
|
|
33
|
-
const only = probe.root.entries;
|
|
34
|
-
const single = only.length === 1 && only[0]?.type === 'assignment' && only[0].key.value === id;
|
|
35
|
-
if (hasBlockingDiagnostics(probe.diagnostics) || !single || only[0]?.type !== 'assignment')
|
|
36
|
-
fail('CHARACTER_WRITE_BODY_INVALID', 'The body must be the text between the braces of one character: balanced braces and no definition of its own', { diagnosticCodes: probe.diagnostics.map(({ code }) => code) });
|
|
37
|
-
if (only[0].value.type !== 'block' || only[0].value.entries.length === 0)
|
|
38
|
-
fail('CHARACTER_WRITE_BODY_INVALID', 'The body of a character cannot be empty');
|
|
39
|
-
}
|
|
40
|
-
function definitionTexts(document, skip) {
|
|
41
|
-
const byKey = new Map();
|
|
42
|
-
for (const character of definitions(document)) {
|
|
43
|
-
if (character.start === skip?.start)
|
|
44
|
-
continue;
|
|
45
|
-
const key = character.key.value;
|
|
46
|
-
byKey.set(key, [
|
|
47
|
-
...(byKey.get(key) ?? []),
|
|
48
|
-
document.text.slice(character.start, character.end),
|
|
49
|
-
]);
|
|
50
|
-
}
|
|
51
|
-
return byKey;
|
|
52
|
-
}
|
|
53
|
-
function checkRequest(input) {
|
|
54
|
-
if (!ID_PATTERN.test(input.id))
|
|
55
|
-
fail('CHARACTER_WRITE_ID_INVALID', `${JSON.stringify(input.id)} is not a valid character id`, {
|
|
56
|
-
id: input.id,
|
|
57
|
-
});
|
|
58
|
-
if (input.operation === 'remove' && input.body !== undefined)
|
|
59
|
-
fail('CHARACTER_WRITE_BODY_UNEXPECTED', 'remove takes no body');
|
|
60
|
-
if (input.operation !== 'remove' && (input.body === undefined || input.body.trim() === ''))
|
|
61
|
-
fail('CHARACTER_WRITE_BODY_REQUIRED', `${input.operation} needs the body of the character`);
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
import { callWritePlan, replacementSchema, } from '../script-write/engine-plan.js';
|
|
3
|
+
const planSchema = z.object({
|
|
4
|
+
operation: z.enum(['add', 'replace', 'remove']),
|
|
5
|
+
id: z.string(),
|
|
6
|
+
path: z.string(),
|
|
7
|
+
edit: replacementSchema,
|
|
8
|
+
untouchedDefinitions: z.number().int().nonnegative(),
|
|
9
|
+
});
|
|
10
|
+
async function plan(path, input, source) {
|
|
11
|
+
const answer = await callWritePlan({
|
|
12
|
+
op: 'character_write.plan',
|
|
13
|
+
path,
|
|
14
|
+
input: { ...input },
|
|
15
|
+
...(source === undefined ? {} : { source }),
|
|
16
|
+
result: planSchema,
|
|
17
|
+
});
|
|
18
|
+
return { ...answer.result, text: answer.text, bytes: answer.bytes, diff: answer.diff };
|
|
62
19
|
}
|
|
63
|
-
/**
|
|
64
|
-
* The plan that creates a new `common/characters` file holding one new character, for
|
|
65
|
-
* `createFile: true`. The file is UTF-8 without a byte order mark and uses tabs and LF, as the
|
|
66
|
-
* game's own character files do.
|
|
67
|
-
*/
|
|
20
|
+
/** The plan that creates a new file holding one new character, for `createFile: true`. */
|
|
68
21
|
export function planNewCharacterFile(path, input) {
|
|
69
|
-
|
|
70
|
-
if (input.operation !== 'add')
|
|
71
|
-
fail('CHARACTER_WRITE_FILE_NOT_FOUND', `${path} does not exist, and only add can create a file`);
|
|
72
|
-
assertBodyIsOneBlock(input.id, input.body);
|
|
73
|
-
const text = [
|
|
74
|
-
'characters = {',
|
|
75
|
-
`\t${input.id} = {`,
|
|
76
|
-
indentedBody(input.body, '\t\t', '\n'),
|
|
77
|
-
'\t}',
|
|
78
|
-
'}',
|
|
79
|
-
'',
|
|
80
|
-
].join('\n');
|
|
81
|
-
const written = parseClausewitz(Buffer.from(text, 'utf8'), path);
|
|
82
|
-
if (hasBlockingDiagnostics(written.diagnostics))
|
|
83
|
-
fail('CHARACTER_WRITE_RESULT_INVALID', 'The new file would have syntax errors', {
|
|
84
|
-
diagnosticCodes: written.diagnostics.map(({ code }) => code),
|
|
85
|
-
});
|
|
86
|
-
return {
|
|
87
|
-
operation: 'add',
|
|
88
|
-
id: input.id,
|
|
89
|
-
path,
|
|
90
|
-
text,
|
|
91
|
-
bytes: Buffer.from(text, 'utf8'),
|
|
92
|
-
edit: { start: 0, end: 0, text, description: `create ${path} with ${input.id}` },
|
|
93
|
-
diff: unifiedTextDiff('', text, `a/${path}`, `b/${path}`, { context: DIFF_CONTEXT_LINES }),
|
|
94
|
-
untouchedDefinitions: 0,
|
|
95
|
-
};
|
|
22
|
+
return plan(path, input, undefined);
|
|
96
23
|
}
|
|
97
24
|
export function planCharacterWrite(source, input) {
|
|
98
|
-
|
|
99
|
-
const document = parseClausewitz(source.bytes, source.path);
|
|
100
|
-
if (hasBlockingDiagnostics(document.diagnostics))
|
|
101
|
-
fail('CHARACTER_WRITE_SOURCE_INVALID', 'The source has syntax errors and cannot be edited safely', { path: source.path, diagnosticCodes: document.diagnostics.map(({ code }) => code) });
|
|
102
|
-
const text = document.text;
|
|
103
|
-
const newline = document.newline;
|
|
104
|
-
if (input.body !== undefined)
|
|
105
|
-
assertBodyIsOneBlock(input.id, input.body);
|
|
106
|
-
const unit = indentUnit(document);
|
|
107
|
-
const existing = definitions(document).filter(({ key }) => key.value === input.id);
|
|
108
|
-
let edit;
|
|
109
|
-
let skip;
|
|
110
|
-
if (input.operation === 'add') {
|
|
111
|
-
if (existing.length > 0)
|
|
112
|
-
fail('CHARACTER_WRITE_DUPLICATE_ID', `${input.id} is already defined in this file`, {
|
|
113
|
-
id: input.id,
|
|
114
|
-
line: existing[0]?.key.token.line,
|
|
115
|
-
});
|
|
116
|
-
const blocks = assignments(document.root, 'characters').filter(({ value }) => value.type === 'block');
|
|
117
|
-
if (blocks.length !== 1)
|
|
118
|
-
fail('CHARACTER_WRITE_LAYOUT_UNSUPPORTED', blocks.length === 0
|
|
119
|
-
? 'The file has no characters block to put the new character in'
|
|
120
|
-
: `The file has ${blocks.length} characters blocks, so the new character has no single place`, { blocks: blocks.length });
|
|
121
|
-
const characters = blocks[0];
|
|
122
|
-
const block = characters.value;
|
|
123
|
-
const close = block.close;
|
|
124
|
-
if (close === undefined)
|
|
125
|
-
fail('CHARACTER_WRITE_LAYOUT_UNSUPPORTED', 'The characters block has no closing brace');
|
|
126
|
-
const closeLineStart = text.lastIndexOf('\n', close.start - 1) + 1;
|
|
127
|
-
if (!/^[ \t]*$/u.test(text.slice(closeLineStart, close.start)))
|
|
128
|
-
fail('CHARACTER_WRITE_LAYOUT_UNSUPPORTED', 'The closing brace of the characters block shares its line with other text, so the new character has no line to go on', { line: close.line });
|
|
129
|
-
const characterIndent = lineIndent(text, characters.start) + unit;
|
|
130
|
-
const characterText = `${characterIndent}${input.id} = {${newline}${indentedBody(input.body, characterIndent + unit, newline)}${newline}${characterIndent}}${newline}`;
|
|
131
|
-
edit = {
|
|
132
|
-
start: closeLineStart,
|
|
133
|
-
end: closeLineStart,
|
|
134
|
-
text: `${block.entries.length > 0 ? newline : ''}${characterText}`,
|
|
135
|
-
description: `add ${input.id}`,
|
|
136
|
-
};
|
|
137
|
-
}
|
|
138
|
-
else {
|
|
139
|
-
if (existing.length === 0)
|
|
140
|
-
fail('CHARACTER_WRITE_NOT_FOUND', `${input.id} is not defined in this file`, {
|
|
141
|
-
id: input.id,
|
|
142
|
-
});
|
|
143
|
-
if (existing.length > 1)
|
|
144
|
-
fail('CHARACTER_WRITE_DUPLICATE_ID', `${input.id} is defined ${existing.length} times in this file`, { id: input.id, lines: existing.map(({ key }) => key.token.line) });
|
|
145
|
-
const found = existing[0];
|
|
146
|
-
skip = found;
|
|
147
|
-
const characterIndent = lineIndent(text, found.start);
|
|
148
|
-
if (input.operation === 'replace') {
|
|
149
|
-
edit = {
|
|
150
|
-
start: found.start,
|
|
151
|
-
end: found.end,
|
|
152
|
-
text: `${input.id} = {${newline}${indentedBody(input.body, characterIndent + unit, newline)}${newline}${characterIndent}}`,
|
|
153
|
-
description: `replace ${input.id}`,
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
else {
|
|
157
|
-
const lineStart = text.lastIndexOf('\n', found.start - 1) + 1;
|
|
158
|
-
const lineEndAt = text.indexOf('\n', found.end);
|
|
159
|
-
const lineEnd = lineEndAt === -1 ? text.length : lineEndAt + 1;
|
|
160
|
-
const alone = /^[ \t]*$/u.test(text.slice(lineStart, found.start)) &&
|
|
161
|
-
/^[ \t]*\r?$/u.test(text.slice(found.end, lineEndAt === -1 ? text.length : lineEndAt));
|
|
162
|
-
if (!alone) {
|
|
163
|
-
edit = { start: found.start, end: found.end, text: '', description: `remove ${input.id}` };
|
|
164
|
-
}
|
|
165
|
-
else {
|
|
166
|
-
// A blank line that only separated this character from the one before it goes with it.
|
|
167
|
-
const before = text.slice(0, lineStart);
|
|
168
|
-
const blankBefore = /(?:^|\n)[ \t]*\r?\n$/u.test(before) && before.length > 0;
|
|
169
|
-
const after = text.slice(lineEnd);
|
|
170
|
-
const nextIsBlankOrClose = /^[ \t]*(?:\r?\n|\})/u.test(after) || after === '';
|
|
171
|
-
let start = lineStart;
|
|
172
|
-
if (blankBefore && nextIsBlankOrClose)
|
|
173
|
-
start = before.lastIndexOf('\n', before.length - 2) + 1;
|
|
174
|
-
edit = { start, end: lineEnd, text: '', description: `remove ${input.id}` };
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
const bytes = applyReplacements(document, [edit]);
|
|
179
|
-
const after = text.slice(0, edit.start) + edit.text + text.slice(edit.end);
|
|
180
|
-
const written = parseClausewitz(bytes, source.path);
|
|
181
|
-
if (hasBlockingDiagnostics(written.diagnostics))
|
|
182
|
-
fail('CHARACTER_WRITE_RESULT_INVALID', 'The edit would leave the file with syntax errors', {
|
|
183
|
-
diagnosticCodes: written.diagnostics.map(({ code }) => code),
|
|
184
|
-
});
|
|
185
|
-
const before = definitionTexts(document, skip);
|
|
186
|
-
const afterTexts = definitionTexts(written, undefined);
|
|
187
|
-
let untouched = 0;
|
|
188
|
-
for (const [key, texts] of before) {
|
|
189
|
-
const now = afterTexts.get(key) ?? [];
|
|
190
|
-
for (const textOfCharacter of texts)
|
|
191
|
-
if (now.includes(textOfCharacter))
|
|
192
|
-
untouched += 1;
|
|
193
|
-
else
|
|
194
|
-
fail('CHARACTER_WRITE_RESULT_INVALID', `The edit would change ${key}, which it must not touch`, { key });
|
|
195
|
-
}
|
|
196
|
-
if (written.text !== after)
|
|
197
|
-
fail('CHARACTER_WRITE_RESULT_INVALID', 'The written file does not match the planned edit');
|
|
198
|
-
return {
|
|
199
|
-
operation: input.operation,
|
|
200
|
-
id: input.id,
|
|
201
|
-
path: source.path,
|
|
202
|
-
text: after,
|
|
203
|
-
bytes,
|
|
204
|
-
edit,
|
|
205
|
-
diff: unifiedTextDiff(text, after, `a/${source.path}`, `b/${source.path}`, {
|
|
206
|
-
context: DIFF_CONTEXT_LINES,
|
|
207
|
-
}),
|
|
208
|
-
untouchedDefinitions: untouched,
|
|
209
|
-
};
|
|
25
|
+
return plan(source.path, input, source.bytes);
|
|
210
26
|
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { z } from 'zod/v4';
|
|
2
|
+
import { callEngineOperation } from './engine-operation.js';
|
|
3
|
+
import { ServiceError } from './result.js';
|
|
4
|
+
const sha256 = z.string().regex(/^[a-f0-9]{64}$/u);
|
|
5
|
+
export const engineArtifactLinkSchema = z
|
|
6
|
+
.object({
|
|
7
|
+
uri: z.string(),
|
|
8
|
+
name: z.string(),
|
|
9
|
+
mimeType: z.string(),
|
|
10
|
+
size: z.number().int().nonnegative(),
|
|
11
|
+
sha256,
|
|
12
|
+
description: z.string().optional(),
|
|
13
|
+
})
|
|
14
|
+
.strict();
|
|
15
|
+
export const engineStoredArtifactSchema = engineArtifactLinkSchema.extend({
|
|
16
|
+
provenanceHash: sha256,
|
|
17
|
+
path: z.string(),
|
|
18
|
+
provenance: z.record(z.string(), z.unknown()),
|
|
19
|
+
});
|
|
20
|
+
const createdSchema = z.object({
|
|
21
|
+
targets: z.array(z.string()),
|
|
22
|
+
manifests: z.array(z.string()),
|
|
23
|
+
/** The engine's claim on these files until the caller commits or releases the put. */
|
|
24
|
+
batch: z.string().optional(),
|
|
25
|
+
});
|
|
26
|
+
const putResultSchema = z.object({
|
|
27
|
+
artifacts: z.array(engineStoredArtifactSchema),
|
|
28
|
+
physical: z.array(engineStoredArtifactSchema),
|
|
29
|
+
created: createdSchema,
|
|
30
|
+
});
|
|
31
|
+
function packWrites(writes) {
|
|
32
|
+
const buffers = writes.map(({ content }) => typeof content === 'string' ? Buffer.from(content, 'utf8') : Buffer.from(content));
|
|
33
|
+
return {
|
|
34
|
+
writes: writes.map((write, index) => ({
|
|
35
|
+
name: write.name,
|
|
36
|
+
mimeType: write.mimeType,
|
|
37
|
+
length: buffers[index].length,
|
|
38
|
+
provenance: write.provenance,
|
|
39
|
+
...(write.description === undefined ? {} : { description: write.description }),
|
|
40
|
+
})),
|
|
41
|
+
payload: Buffer.concat(buffers),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function storeBody(workspace, limits) {
|
|
45
|
+
return { workspace, ...(limits === undefined ? {} : { limits }) };
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Stores a batch of artifacts. `retention` supplies the caller's durable pins: the engine asks for
|
|
49
|
+
* them (`ARTIFACT_RETENTION_REQUIRED`) only when it must evict to make room, and the call is made
|
|
50
|
+
* again with them.
|
|
51
|
+
*/
|
|
52
|
+
export async function putArtifacts(workspace, writes, options = {}) {
|
|
53
|
+
const packed = packWrites(writes);
|
|
54
|
+
const call = (retained, epoch) => callEngineOperation({
|
|
55
|
+
op: options.chunked === true ? 'artifacts.put_chunked' : 'artifacts.put',
|
|
56
|
+
body: {
|
|
57
|
+
...storeBody(workspace, options.limits),
|
|
58
|
+
writes: packed.writes,
|
|
59
|
+
...(options.retention === undefined ? {} : { retentionPending: true }),
|
|
60
|
+
...(retained === undefined ? {} : { retainedUris: retained }),
|
|
61
|
+
...(epoch === undefined ? {} : { retentionEpoch: epoch }),
|
|
62
|
+
},
|
|
63
|
+
payload: packed.payload,
|
|
64
|
+
result: putResultSchema,
|
|
65
|
+
...(options.request === undefined ? {} : { options: options.request }),
|
|
66
|
+
});
|
|
67
|
+
let retained;
|
|
68
|
+
let epoch;
|
|
69
|
+
for (let attempt = 0;; attempt += 1) {
|
|
70
|
+
try {
|
|
71
|
+
return (await call(retained, epoch)).result;
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (options.retention === undefined ||
|
|
75
|
+
attempt >= retentionAttempts ||
|
|
76
|
+
error.code !== 'ARTIFACT_RETENTION_REQUIRED')
|
|
77
|
+
throw error;
|
|
78
|
+
// The epoch is taken before the pins are read: a commit made meanwhile moves it, and the
|
|
79
|
+
// engine then asks again instead of evicting an artifact that list does not know about.
|
|
80
|
+
const reported = error.details?.epoch;
|
|
81
|
+
epoch = typeof reported === 'number' ? reported : undefined;
|
|
82
|
+
retained = [...(await options.retention())];
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/** How many times a put re-reads the caller's pins when commits keep changing them. */
|
|
87
|
+
const retentionAttempts = 5;
|
|
88
|
+
/** Takes back the files a put created, when the caller's own commit failed. */
|
|
89
|
+
export async function releaseArtifacts(workspace, created, limits) {
|
|
90
|
+
await callEngineOperation({
|
|
91
|
+
op: 'artifacts.release',
|
|
92
|
+
body: { ...storeBody(workspace, limits), created },
|
|
93
|
+
result: z.object({}),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Tells the engine the caller's commit succeeded, so the files of a put are no longer held against
|
|
98
|
+
* eviction. A put's claim also expires on its own after ten minutes.
|
|
99
|
+
*/
|
|
100
|
+
export async function commitArtifacts(workspace, created, limits) {
|
|
101
|
+
await callEngineOperation({
|
|
102
|
+
op: 'artifacts.commit',
|
|
103
|
+
body: { ...storeBody(workspace, limits), created },
|
|
104
|
+
result: z.object({}),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
export async function readArtifact(workspace, uri, range, limits, request) {
|
|
108
|
+
const { result, payload } = await callEngineOperation({
|
|
109
|
+
op: 'artifacts.read',
|
|
110
|
+
body: { ...storeBody(workspace, limits), uri, ...(range === undefined ? {} : { range }) },
|
|
111
|
+
result: z.object({ mimeType: z.string(), name: z.string(), totalSize: z.number() }),
|
|
112
|
+
...(request === undefined ? {} : { options: request }),
|
|
113
|
+
});
|
|
114
|
+
return { bytes: payload, ...result };
|
|
115
|
+
}
|
|
116
|
+
export async function readLogicalArtifact(workspace, uri, logical, limits) {
|
|
117
|
+
const { result, payload } = await callEngineOperation({
|
|
118
|
+
op: 'artifacts.read_logical',
|
|
119
|
+
body: { ...storeBody(workspace, limits), uri, ...logical },
|
|
120
|
+
result: z.object({ mimeType: z.string(), name: z.string(), totalSize: z.number() }),
|
|
121
|
+
});
|
|
122
|
+
return { bytes: payload, ...result };
|
|
123
|
+
}
|
|
124
|
+
export async function describeArtifact(workspace, uri, limits) {
|
|
125
|
+
return (await callEngineOperation({
|
|
126
|
+
op: 'artifacts.describe',
|
|
127
|
+
body: { ...storeBody(workspace, limits), uri },
|
|
128
|
+
result: engineStoredArtifactSchema,
|
|
129
|
+
})).result;
|
|
130
|
+
}
|
|
131
|
+
export async function artifactsAvailable(workspace, uris, limits) {
|
|
132
|
+
return (await callEngineOperation({
|
|
133
|
+
op: 'artifacts.available',
|
|
134
|
+
body: { ...storeBody(workspace, limits), uris },
|
|
135
|
+
result: z.object({ available: z.boolean() }),
|
|
136
|
+
})).result.available;
|
|
137
|
+
}
|
|
138
|
+
export async function listArtifacts(workspace, limits) {
|
|
139
|
+
// The links are the payload (a JSON array): a full root lists more than a response header may hold.
|
|
140
|
+
const answer = await callEngineOperation({
|
|
141
|
+
op: 'artifacts.list',
|
|
142
|
+
body: storeBody(workspace, limits),
|
|
143
|
+
result: z.object({ count: z.number() }),
|
|
144
|
+
});
|
|
145
|
+
const links = z
|
|
146
|
+
.array(engineArtifactLinkSchema)
|
|
147
|
+
.parse(JSON.parse(answer.payload.toString('utf8')));
|
|
148
|
+
if (links.length !== answer.result.count)
|
|
149
|
+
throw new ServiceError('ENGINE_UNAVAILABLE', 'hoi4-engine artifacts.list answered out of shape', {
|
|
150
|
+
op: 'artifacts.list',
|
|
151
|
+
reason: 'invalid_response',
|
|
152
|
+
});
|
|
153
|
+
return links;
|
|
154
|
+
}
|
|
155
|
+
export async function listArtifactPage(workspace, page, limits) {
|
|
156
|
+
return (await callEngineOperation({
|
|
157
|
+
op: 'artifacts.list_page',
|
|
158
|
+
body: { ...storeBody(workspace, limits), ...page },
|
|
159
|
+
result: z.object({
|
|
160
|
+
artifacts: z.array(engineArtifactLinkSchema),
|
|
161
|
+
total: z.number(),
|
|
162
|
+
revision: z.string(),
|
|
163
|
+
afterFound: z.boolean(),
|
|
164
|
+
hasMore: z.boolean(),
|
|
165
|
+
}),
|
|
166
|
+
})).result;
|
|
167
|
+
}
|
|
168
|
+
const changedSummarySchema = z.object({
|
|
169
|
+
total: z.number(),
|
|
170
|
+
created: z.number(),
|
|
171
|
+
removed: z.number(),
|
|
172
|
+
modified: z.number(),
|
|
173
|
+
folders: z.array(z.object({
|
|
174
|
+
folder: z.string(),
|
|
175
|
+
created: z.number(),
|
|
176
|
+
removed: z.number(),
|
|
177
|
+
modified: z.number(),
|
|
178
|
+
})),
|
|
179
|
+
omittedFolders: z.number(),
|
|
180
|
+
});
|
|
181
|
+
export async function summarizeChangedFilesOnEngine(files, limit) {
|
|
182
|
+
return (await callEngineOperation({
|
|
183
|
+
op: 'artifacts.changed_summary',
|
|
184
|
+
body: { files, ...(limit === undefined ? {} : { limit }) },
|
|
185
|
+
result: changedSummarySchema,
|
|
186
|
+
})).result;
|
|
187
|
+
}
|
|
188
|
+
export async function unifiedTextDiffOnEngine(oldText, newText, oldName, newName, options = {}) {
|
|
189
|
+
// Both texts and the diff travel as payload: a real file's diff is larger than a response header may be.
|
|
190
|
+
const oldBytes = Buffer.from(oldText, 'utf8');
|
|
191
|
+
const answer = await callEngineOperation({
|
|
192
|
+
op: 'diff.text',
|
|
193
|
+
body: { oldLength: oldBytes.length, oldName, newName, ...options },
|
|
194
|
+
payload: Buffer.concat([oldBytes, Buffer.from(newText, 'utf8')]),
|
|
195
|
+
result: z.object({ length: z.number() }),
|
|
196
|
+
});
|
|
197
|
+
return answer.payload.toString('utf8');
|
|
198
|
+
}
|
|
199
|
+
const binaryDiffSchema = z.object({
|
|
200
|
+
oldSize: z.number(),
|
|
201
|
+
newSize: z.number(),
|
|
202
|
+
changedBytes: z.number(),
|
|
203
|
+
firstChangedOffset: z.number().optional(),
|
|
204
|
+
lastChangedOffset: z.number().optional(),
|
|
205
|
+
});
|
|
206
|
+
export async function binaryDiffOnEngine(oldBytes, newBytes) {
|
|
207
|
+
return (await callEngineOperation({
|
|
208
|
+
op: 'diff.binary',
|
|
209
|
+
body: { oldLength: oldBytes.length },
|
|
210
|
+
payload: Buffer.concat([oldBytes, newBytes]),
|
|
211
|
+
result: binaryDiffSchema,
|
|
212
|
+
})).result;
|
|
213
|
+
}
|
|
214
|
+
export async function comparePngImagesOnEngine(left, right, options = {}) {
|
|
215
|
+
const { result, payload } = await callEngineOperation({
|
|
216
|
+
op: 'diff.image',
|
|
217
|
+
body: { leftLength: left.length, ...options },
|
|
218
|
+
payload: Buffer.concat([left, right]),
|
|
219
|
+
result: z.object({
|
|
220
|
+
width: z.number(),
|
|
221
|
+
height: z.number(),
|
|
222
|
+
changedPixels: z.number(),
|
|
223
|
+
changedRatio: z.number(),
|
|
224
|
+
json: z.string(),
|
|
225
|
+
reservedPixels: z.number(),
|
|
226
|
+
}),
|
|
227
|
+
});
|
|
228
|
+
return { ...result, png: payload };
|
|
229
|
+
}
|
|
230
|
+
const managedPlanSchema = z.object({
|
|
231
|
+
deletions: z.array(z.object({ relativePath: z.string(), operationIds: z.array(z.string()) })),
|
|
232
|
+
manifest: z.string(),
|
|
233
|
+
written: z.array(z.string()),
|
|
234
|
+
retired: z.array(z.string()),
|
|
235
|
+
released: z.array(z.string()),
|
|
236
|
+
ignored: z.array(z.string()),
|
|
237
|
+
});
|
|
238
|
+
export async function planManagedOutputsOnEngine(input) {
|
|
239
|
+
return (await callEngineOperation({
|
|
240
|
+
op: 'artifacts.managed_plan',
|
|
241
|
+
body: { ...input },
|
|
242
|
+
result: managedPlanSchema,
|
|
243
|
+
})).result;
|
|
244
|
+
}
|
|
245
|
+
const managedRefreshSchema = z.object({
|
|
246
|
+
refresh: z
|
|
247
|
+
.object({
|
|
248
|
+
content: z.string().nullable().optional(),
|
|
249
|
+
refreshed: z.array(z.string()),
|
|
250
|
+
dropped: z.array(z.string()),
|
|
251
|
+
keptEdited: z.array(z.string()),
|
|
252
|
+
unchanged: z.array(z.string()),
|
|
253
|
+
unscanned: z.array(z.string()),
|
|
254
|
+
added: z.array(z.string()),
|
|
255
|
+
operationIds: z.array(z.string()),
|
|
256
|
+
})
|
|
257
|
+
.nullable(),
|
|
258
|
+
});
|
|
259
|
+
export async function refreshManagedOutputsOnEngine(input) {
|
|
260
|
+
return (await callEngineOperation({
|
|
261
|
+
op: 'artifacts.managed_refresh',
|
|
262
|
+
body: { ...input },
|
|
263
|
+
result: managedRefreshSchema,
|
|
264
|
+
})).result.refresh;
|
|
265
|
+
}
|
|
266
|
+
export async function sweepTemporaryDirectoriesOnEngine(parent, options = {}) {
|
|
267
|
+
return (await callEngineOperation({
|
|
268
|
+
op: 'artifacts.sweep_temporary',
|
|
269
|
+
body: { parent, ...options },
|
|
270
|
+
result: z.object({ removed: z.number(), retainedBytes: z.number() }),
|
|
271
|
+
})).result;
|
|
272
|
+
}
|
|
@@ -173,6 +173,12 @@ export const serverConfigurationSchema = z
|
|
|
173
173
|
* indexes instead of scanning cold; 0 starts a fresh worker for every job.
|
|
174
174
|
*/
|
|
175
175
|
jobWorkerIdleSeconds: z.number().int().min(0).max(3_600).default(180),
|
|
176
|
+
/**
|
|
177
|
+
* How long after the last tool call the in-memory analysis caches (scans, indexes and the
|
|
178
|
+
* views built from them) are released; the next call rebuilds what it needs. A busy server
|
|
179
|
+
* reuses them between calls. `0` releases them as soon as a call ends.
|
|
180
|
+
*/
|
|
181
|
+
idleCacheReleaseSeconds: z.number().int().min(0).max(3_600).default(30),
|
|
176
182
|
scanMaxBytes: z
|
|
177
183
|
.number()
|
|
178
184
|
.int()
|