hoi4-agent-tools 4.20.3 → 4.22.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.
Files changed (140) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +2 -0
  3. package/dist/bin/setup.js +1 -0
  4. package/dist/bin/stdio.js +1 -0
  5. package/dist/hoi4_agent_tools/characters/write-operations.js +2 -2
  6. package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
  7. package/dist/hoi4_agent_tools/common-write/documented-lists.js +62 -0
  8. package/dist/hoi4_agent_tools/common-write/limits.js +35 -0
  9. package/dist/hoi4_agent_tools/common-write/paths.js +17 -0
  10. package/dist/hoi4_agent_tools/common-write/write-job-operations.js +42 -0
  11. package/dist/hoi4_agent_tools/common-write/write-operations.js +360 -0
  12. package/dist/hoi4_agent_tools/common-write/write-plan.js +34 -0
  13. package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
  14. package/dist/hoi4_agent_tools/core/configuration.js +6 -0
  15. package/dist/hoi4_agent_tools/core/domain-tools.js +8 -0
  16. package/dist/hoi4_agent_tools/core/engine.js +67 -21
  17. package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
  18. package/dist/hoi4_agent_tools/core/job-controls.js +12 -2
  19. package/dist/hoi4_agent_tools/core/job-executor.js +8 -7
  20. package/dist/hoi4_agent_tools/core/job-operation-registration.js +4 -0
  21. package/dist/hoi4_agent_tools/core/job-store.js +97 -5
  22. package/dist/hoi4_agent_tools/core/job-worker-host.js +2 -2
  23. package/dist/hoi4_agent_tools/core/operation-result.js +118 -33
  24. package/dist/hoi4_agent_tools/core/operation-tasks.js +4 -2
  25. package/dist/hoi4_agent_tools/core/transactions.js +6 -0
  26. package/dist/hoi4_agent_tools/core/workspace.js +25 -2
  27. package/dist/hoi4_agent_tools/country/job-operations.js +42 -0
  28. package/dist/hoi4_agent_tools/country/write-operations.js +646 -0
  29. package/dist/hoi4_agent_tools/country/write-plan.js +28 -0
  30. package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
  31. package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
  32. package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
  33. package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
  34. package/dist/hoi4_agent_tools/event/graph.js +3 -3
  35. package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
  36. package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
  37. package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
  38. package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
  39. package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
  40. package/dist/hoi4_agent_tools/gui/assets.js +3 -13
  41. package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
  42. package/dist/hoi4_agent_tools/gui/layout.js +2 -4
  43. package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
  44. package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
  45. package/dist/hoi4_agent_tools/gui/studio.js +31 -0
  46. package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
  47. package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
  48. package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
  49. package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
  50. package/dist/hoi4_agent_tools/map/landmass-source.js +42 -0
  51. package/dist/hoi4_agent_tools/map/landmass.js +190 -0
  52. package/dist/hoi4_agent_tools/map/model.js +17 -3
  53. package/dist/hoi4_agent_tools/map/operations.js +20 -6
  54. package/dist/hoi4_agent_tools/map/references.js +6 -3
  55. package/dist/hoi4_agent_tools/map/service.js +88 -8
  56. package/dist/hoi4_agent_tools/map/validation.js +12 -18
  57. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  58. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  59. package/dist/hoi4_agent_tools/mcp/server/create.js +4 -0
  60. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +4 -0
  61. package/dist/hoi4_agent_tools/mcp/tools/common-write.js +21 -0
  62. package/dist/hoi4_agent_tools/mcp/tools/country-write.js +21 -0
  63. package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -1
  64. package/dist/hoi4_agent_tools/mcp/transports/http.js +2 -0
  65. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
  66. package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
  67. package/dist/hoi4_agent_tools/runtime.js +83 -3
  68. package/dist/hoi4_agent_tools/schemas/character-write.js +5 -1
  69. package/dist/hoi4_agent_tools/schemas/common-write.js +74 -0
  70. package/dist/hoi4_agent_tools/schemas/country-write.js +206 -0
  71. package/dist/hoi4_agent_tools/schemas/decision-write.js +5 -1
  72. package/dist/hoi4_agent_tools/schemas/doctrine-write.js +5 -1
  73. package/dist/hoi4_agent_tools/schemas/event-write.js +5 -1
  74. package/dist/hoi4_agent_tools/schemas/idea-write.js +5 -1
  75. package/dist/hoi4_agent_tools/schemas/landmass.js +129 -0
  76. package/dist/hoi4_agent_tools/schemas/localisation-write.js +10 -1
  77. package/dist/hoi4_agent_tools/schemas/map-requests.js +1 -1
  78. package/dist/hoi4_agent_tools/schemas/map.js +2 -0
  79. package/dist/hoi4_agent_tools/schemas/tech-write.js +5 -1
  80. package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
  81. package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
  82. package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
  83. package/dist/hoi4_agent_tools/technology/operations.js +1 -2
  84. package/dist/hoi4_agent_tools/technology/service.js +30 -59
  85. package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
  86. package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
  87. package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
  88. package/dist/hoi4_agent_tools/version.js +1 -1
  89. package/docs/configuration.md +11 -10
  90. package/docs/jobs.md +2 -2
  91. package/docs/setup.md +1 -0
  92. package/docs/tools.md +16 -2
  93. package/docs/troubleshooting.md +11 -11
  94. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  95. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  96. package/engine/bin/linux-x64/hoi4-engine +0 -0
  97. package/engine/bin/manifest.json +8 -8
  98. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  99. package/npm-shrinkwrap.json +43 -19
  100. package/package.json +2 -2
  101. package/schemas/configuration.schema.json +143 -134
  102. package/schemas/continuous-focus-palette.schema.json +1 -1
  103. package/schemas/custom-weighted-pool.schema.json +1 -1
  104. package/schemas/decision-inspect-input.schema.json +1 -1
  105. package/schemas/error-log-input.schema.json +1 -1
  106. package/schemas/event-feature-manifest.schema.json +1 -1
  107. package/schemas/focus-plan.schema.json +1 -1
  108. package/schemas/focus-planning-sidecar.schema.json +1 -1
  109. package/schemas/geography-model.schema.json +1 -1
  110. package/schemas/gui-animation-source.schema.json +1 -1
  111. package/schemas/gui-helper.schema.json +1 -1
  112. package/schemas/gui-scenario.schema.json +1 -1
  113. package/schemas/helper-expansion-request.schema.json +1 -1
  114. package/schemas/helper-expansion-summary.schema.json +1 -1
  115. package/schemas/impact-inspect-input.schema.json +1 -1
  116. package/schemas/map-operation.schema.json +354 -1
  117. package/schemas/mechanic-test-input.schema.json +1 -1
  118. package/schemas/mod-index-input.schema.json +1 -1
  119. package/schemas/operation-result.schema.json +1 -1
  120. package/schemas/package-check-input.schema.json +1 -1
  121. package/schemas/package-manifest.schema.json +1 -1
  122. package/schemas/probability-analysis-result.schema.json +1 -1
  123. package/schemas/probability-compare-input.schema.json +1 -1
  124. package/schemas/probability-evaluate-input.schema.json +1 -1
  125. package/schemas/probability-inspect-input.schema.json +1 -1
  126. package/schemas/probability-render-input.schema.json +1 -1
  127. package/schemas/probability-scenario-set.schema.json +1 -1
  128. package/schemas/probability-sequence-input.schema.json +1 -1
  129. package/schemas/probability-simulate-input.schema.json +1 -1
  130. package/schemas/probability-sweep-input.schema.json +1 -1
  131. package/schemas/reference-context-input.schema.json +1 -1
  132. package/schemas/reference-read-input.schema.json +1 -1
  133. package/schemas/reference-search-input.schema.json +1 -1
  134. package/schemas/reference-sheets.schema.json +1 -1
  135. package/schemas/scenario-suite.schema.json +1 -1
  136. package/schemas/scenario-test-input.schema.json +1 -1
  137. package/schemas/script-validate-input.schema.json +1 -1
  138. package/schemas/shared-scenario.schema.json +1 -1
  139. package/schemas/source-lookup-input.schema.json +1 -1
  140. package/server.json +2 -2
@@ -0,0 +1,360 @@
1
+ import { emptyServiceResult, ServiceError } from '../core/result.js';
2
+ import { autonomousResultArtifacts, } from '../core/transaction-execution.js';
3
+ import { commonWriteDataSchema, } from '../schemas/common-write.js';
4
+ import { documentedLists } from './documented-lists.js';
5
+ import { capFindings, capList, cutText, MAX_DIAGNOSTICS, MAX_DIFF_UNITS, MAX_NAMES, } from './limits.js';
6
+ import { isPlainRelativePath } from './paths.js';
7
+ import { planCommonWrite, planNewCommonFile, } from './write-plan.js';
8
+ const MAX_INLINE_PATHS = 8;
9
+ const MAX_INLINE_ARTIFACTS = 2;
10
+ /**
11
+ * Where each kind lives, for choosing the file. The engine's descriptor owns the folder rule and
12
+ * refuses a path outside it; this table only narrows the scan to the kind's files.
13
+ */
14
+ const FOLDERS = {
15
+ bop: 'common/bop/',
16
+ ai_strategy: 'common/ai_strategy/',
17
+ ai_strategy_plan: 'common/ai_strategy_plans/',
18
+ on_action: 'common/on_actions/',
19
+ };
20
+ function fail(code, message, details) {
21
+ throw new ServiceError(code, message, details);
22
+ }
23
+ function normalized(path) {
24
+ return path.replaceAll('\\', '/').replace(/^\.\//u, '').toLowerCase();
25
+ }
26
+ /** The mod files of the kind, the ones this tool may write. */
27
+ function modFiles(snapshot, kind) {
28
+ return snapshot.files.filter(({ rootKind, shadowedBy, relativePath }) => rootKind === 'mod' &&
29
+ shadowedBy === undefined &&
30
+ normalized(relativePath).startsWith(FOLDERS[kind]) &&
31
+ relativePath.toLowerCase().endsWith('.txt'));
32
+ }
33
+ /**
34
+ * The mod files that define the id, found by asking the engine to plan a removal of it from each:
35
+ * a file without the id answers "not found", a file that cannot be read answers nothing about it.
36
+ */
37
+ async function holders(files, input) {
38
+ const holding = [];
39
+ const unreadable = [];
40
+ for (const file of files) {
41
+ try {
42
+ await planCommonWrite({ bytes: file.bytes, path: file.relativePath }, { kind: input.kind, operation: 'remove', id: input.id });
43
+ holding.push(file);
44
+ }
45
+ catch (error) {
46
+ if (!(error instanceof ServiceError))
47
+ throw error;
48
+ if (error.code === 'COMMON_WRITE_NOT_FOUND')
49
+ continue;
50
+ // Only a file that really has the id holds it; one the engine cannot read or place an edit
51
+ // in is reported apart, so a refusal can name what it could not search.
52
+ if (error.code === 'COMMON_WRITE_DUPLICATE_ID')
53
+ holding.push(file);
54
+ else
55
+ unreadable.push(file.relativePath);
56
+ }
57
+ }
58
+ return { holding, unreadable };
59
+ }
60
+ async function targetFile(snapshot, input) {
61
+ const files = modFiles(snapshot, input.kind);
62
+ const folder = FOLDERS[input.kind];
63
+ const listed = files.map(({ relativePath }) => relativePath).slice(0, 20);
64
+ if (input.createFile === true && input.operation !== 'add')
65
+ fail('COMMON_WRITE_FILE_UNEXPECTED', 'createFile applies to add only', {});
66
+ // An add of a one-block-per-id kind must see every file of the kind: a file the engine cannot
67
+ // read might hold the id, so the add is refused, and a file that does hold it is a duplicate
68
+ // whichever file the add names.
69
+ const searched = input.operation === 'add' && input.kind !== 'on_action'
70
+ ? await holders(files, input)
71
+ : undefined;
72
+ if (searched !== undefined) {
73
+ if (searched.unreadable.length > 0)
74
+ fail('COMMON_WRITE_FILES_UNREADABLE', `${searched.unreadable.length} ${folder} file(s) of the mod could not be read, so the add cannot tell whether ${input.id} is already defined; fix them first`, { id: input.id, unreadable: searched.unreadable.slice(0, 20) });
75
+ if (searched.holding.length > 0)
76
+ fail('COMMON_WRITE_DUPLICATE_ID', `${input.id} is already defined in the mod`, {
77
+ id: input.id,
78
+ path: searched.holding[0]?.relativePath,
79
+ });
80
+ }
81
+ if (input.file !== undefined) {
82
+ const named = files.find(({ relativePath }) => normalized(relativePath) === normalized(input.file));
83
+ if (named !== undefined) {
84
+ if (input.createFile === true)
85
+ // The file exists, so the flag has nothing to create; refusing keeps a wrong guess visible.
86
+ fail('COMMON_WRITE_FILE_EXISTS', `${named.relativePath} already exists; drop createFile to add to it`, { file: named.relativePath });
87
+ return { file: named };
88
+ }
89
+ if (input.operation !== 'add' || input.createFile !== true)
90
+ fail('COMMON_WRITE_FILE_NOT_FOUND', `${input.file} is not a ${folder} file of the mod${input.operation === 'add' ? '; pass createFile: true to create it' : ''}`, { file: input.file, files: listed });
91
+ const newPath = input.file.replaceAll('\\', '/').replace(/^\.\//u, '');
92
+ if (!normalized(newPath).startsWith(folder) ||
93
+ !newPath.toLowerCase().endsWith('.txt') ||
94
+ !isPlainRelativePath(newPath))
95
+ fail('COMMON_WRITE_FILE_INVALID', `${input.file} is not a plain .txt path under ${folder}, so a new file cannot go there`, { file: input.file });
96
+ return { newPath };
97
+ }
98
+ const { holding, unreadable } = searched ?? (await holders(files, input));
99
+ if (input.operation === 'add') {
100
+ if (input.createFile === true)
101
+ fail('COMMON_WRITE_FILE_REQUIRED', 'createFile needs file, the path of the new file', {
102
+ files: listed,
103
+ });
104
+ if (holding.length > 0 && input.kind !== 'on_action')
105
+ fail('COMMON_WRITE_DUPLICATE_ID', `${input.id} is already defined in the mod`, {
106
+ id: input.id,
107
+ path: holding[0]?.relativePath,
108
+ });
109
+ const choices = holding.length > 0 ? holding : files;
110
+ if (choices.length === 1)
111
+ return { file: choices[0] };
112
+ fail('COMMON_WRITE_FILE_REQUIRED', choices.length === 0
113
+ ? `The mod has no ${folder} file; name a new one with file and createFile: true`
114
+ : `${choices.length} files of the mod could hold ${input.id}; name one with file`, { files: choices.map(({ relativePath }) => relativePath).slice(0, 20) });
115
+ }
116
+ if (holding.length === 0)
117
+ fail('COMMON_WRITE_NOT_FOUND', `${input.id} is not defined in a ${folder} file of the mod${unreadable.length === 0 ? '' : `; ${unreadable.length} file(s) could not be searched`}`, { id: input.id, files: listed, ...(unreadable.length === 0 ? {} : { unreadable }) });
118
+ if (holding.length > 1)
119
+ fail('COMMON_WRITE_FILE_REQUIRED', `${input.id} is defined in ${holding.length} files; name one with file`, { files: holding.map(({ relativePath }) => relativePath) });
120
+ return { file: holding[0] };
121
+ }
122
+ export async function computeCommonWrite(engine, input, context, applied) {
123
+ const snapshot = await engine.scan(context.workspaceId, {
124
+ patterns: [
125
+ `${FOLDERS[input.kind]}**/*.txt`,
126
+ 'common/decisions/**/*.txt',
127
+ 'common/national_focus/**/*.txt',
128
+ 'interface/**/*.gfx',
129
+ 'localisation/english/**/*.{yml,yaml}',
130
+ 'localisation/*.{yml,yaml}',
131
+ ],
132
+ }, context.principal, context.signal);
133
+ const lists = input.operation === 'remove'
134
+ ? { tokens: undefined, names: undefined }
135
+ : await documentedLists(engine, context.workspaceId, context.principal, context.signal);
136
+ const planInput = {
137
+ kind: input.kind,
138
+ operation: input.operation,
139
+ id: input.id,
140
+ ...(input.body === undefined ? {} : { body: input.body }),
141
+ ...(input.blockIndex === undefined ? {} : { blockIndex: input.blockIndex }),
142
+ ...(input.kind === 'ai_strategy' && lists.tokens !== undefined
143
+ ? { knownTokens: lists.tokens }
144
+ : {}),
145
+ ...(input.kind === 'on_action' && lists.names !== undefined ? { knownNames: lists.names } : {}),
146
+ };
147
+ const target = await targetFile(snapshot, input);
148
+ let file;
149
+ let plan;
150
+ if ('file' in target) {
151
+ file = target.file;
152
+ plan = await planCommonWrite({ bytes: file.bytes, path: file.relativePath }, planInput);
153
+ }
154
+ else {
155
+ plan = await planNewCommonFile(target.newPath, planInput);
156
+ }
157
+ const missing = {
158
+ localisation: [],
159
+ sprites: [],
160
+ categories: [],
161
+ focuses: [],
162
+ };
163
+ const diagnostics = plan.findings.map(({ code, severity, message }) => ({
164
+ code: `COMMON_WRITE_${code}`,
165
+ severity,
166
+ category: 'reference',
167
+ message,
168
+ details: { id: plan.id },
169
+ }));
170
+ if (input.operation !== 'remove') {
171
+ for (const key of plan.references.localisation)
172
+ if (snapshot.index.find('localisation', `l_english:${key}`) === undefined)
173
+ missing.localisation.push(key);
174
+ for (const sprite of plan.references.sprites)
175
+ if (snapshot.index.find('sprite', sprite) === undefined)
176
+ missing.sprites.push(sprite);
177
+ for (const category of plan.references.categories)
178
+ if (snapshot.index.find('decision_category', category) === undefined)
179
+ missing.categories.push(category);
180
+ for (const focus of plan.references.focuses)
181
+ if (snapshot.index.find('focus', focus) === undefined)
182
+ missing.focuses.push(focus);
183
+ const lines = [
184
+ [
185
+ 'localisation',
186
+ 'LOCALISATION_MISSING',
187
+ 'No English text is defined for the localisation key',
188
+ ],
189
+ ['sprites', 'SPRITE_UNDEFINED', 'The sprite is not defined:'],
190
+ ['categories', 'CATEGORY_UNDEFINED', 'No decision category is defined with the name'],
191
+ ['focuses', 'FOCUS_UNDEFINED', 'No focus is defined with the id'],
192
+ ];
193
+ for (const [field, code, text] of lines)
194
+ for (const name of missing[field])
195
+ diagnostics.push({
196
+ code: `COMMON_WRITE_${code}`,
197
+ severity: 'warning',
198
+ category: 'reference',
199
+ message: `${text} ${name}`,
200
+ details: { name },
201
+ });
202
+ }
203
+ const omittedDiagnostics = Math.max(0, diagnostics.length - MAX_DIAGNOSTICS);
204
+ const budget = plan.diff.length > MAX_DIFF_UNITS;
205
+ const findings = capFindings(plan.findings);
206
+ const capped = {
207
+ localisation: capList(missing.localisation, MAX_NAMES.localisation),
208
+ sprites: capList(missing.sprites, MAX_NAMES.sprites),
209
+ categories: capList(missing.categories, MAX_NAMES.categories),
210
+ focuses: capList(missing.focuses, MAX_NAMES.focuses),
211
+ };
212
+ const data = commonWriteDataSchema.parse({
213
+ operation: plan.operation,
214
+ kind: plan.kind,
215
+ id: plan.id,
216
+ path: cutText(plan.path, 1024),
217
+ applied,
218
+ diff: budget ? `${cutText(plan.diff, MAX_DIFF_UNITS)}\n` : plan.diff,
219
+ diffTruncated: budget,
220
+ untouchedDefinitions: plan.untouchedDefinitions,
221
+ findings: findings.kept.map(({ severity, code, message }) => ({ severity, code, message })),
222
+ missing: {
223
+ localisation: capped.localisation.kept,
224
+ sprites: capped.sprites.kept,
225
+ categories: capped.categories.kept,
226
+ focuses: capped.focuses.kept,
227
+ },
228
+ omitted: {
229
+ findings: findings.omitted,
230
+ diagnostics: omittedDiagnostics,
231
+ localisation: capped.localisation.omitted,
232
+ sprites: capped.sprites.omitted,
233
+ categories: capped.categories.omitted,
234
+ focuses: capped.focuses.omitted,
235
+ },
236
+ });
237
+ diagnostics.splice(MAX_DIAGNOSTICS);
238
+ return { plan, file, data, diagnostics };
239
+ }
240
+ function resultFor(workspaceId, data, outcome) {
241
+ const result = emptyServiceResult(workspaceId, data);
242
+ result.code =
243
+ outcome === 'preview'
244
+ ? 'COMMON_WRITE_PREVIEW'
245
+ : outcome === 'applied'
246
+ ? 'COMMON_WRITE_APPLIED'
247
+ : outcome === 'unchanged'
248
+ ? 'COMMON_WRITE_UNCHANGED'
249
+ : 'COMMON_WRITE_BLOCKED';
250
+ result.status = outcome === 'blocked' ? 'blocked' : 'ok';
251
+ result.proposedFiles = [data.path].slice(0, MAX_INLINE_PATHS);
252
+ return result;
253
+ }
254
+ /** `apply: false`: the diff of the one file the call would change, and nothing written. */
255
+ export async function previewCommonWrite(engine, input, context) {
256
+ await context.progress?.(0, 2, 'Reading the definitions of the mod');
257
+ const computed = await computeCommonWrite(engine, input, context, false);
258
+ const result = resultFor(context.workspaceId, computed.data, computed.file !== undefined && computed.plan.bytes.equals(computed.file.bytes)
259
+ ? 'unchanged'
260
+ : 'preview');
261
+ result.diagnostics = computed.diagnostics;
262
+ await context.progress?.(2, 2, 'Definition preview ready');
263
+ return result;
264
+ }
265
+ /** `apply: true`: the same plan, as one validated transaction for atomic replacement. */
266
+ export async function prepareCommonWrite(engine, input, context) {
267
+ await context.progress?.(0, 3, 'Reading the definitions of the mod');
268
+ const computed = await computeCommonWrite(engine, input, context, true);
269
+ const { plan, file, data, diagnostics } = computed;
270
+ if (file !== undefined && plan.bytes.equals(file.bytes)) {
271
+ const result = resultFor(context.workspaceId, { ...data, applied: false }, 'unchanged');
272
+ result.diagnostics = diagnostics;
273
+ return { readOnlyPreview: result };
274
+ }
275
+ const workspace = engine.resolver.get(context.workspaceId, context.principal);
276
+ const modRoot = workspace.roots.find((root) => root.kind === 'mod');
277
+ const operationId = `common-${plan.kind}-${plan.operation}`;
278
+ await context.progress?.(1, 3, 'Preparing the definition transaction');
279
+ const transaction = await engine.transactions.plan({
280
+ workspaceId: context.workspaceId,
281
+ ...(context.principal === undefined ? {} : { principal: context.principal }),
282
+ operationKind: 'common-changes',
283
+ operations: [
284
+ {
285
+ id: operationId,
286
+ kind: operationId,
287
+ summary: `${plan.operation} ${plan.id} (${plan.kind})`,
288
+ data: { id: plan.id, kind: plan.kind },
289
+ },
290
+ ],
291
+ changes: [
292
+ {
293
+ relativePath: plan.path,
294
+ content: plan.bytes,
295
+ operationIds: [operationId],
296
+ mediaType: 'text/plain',
297
+ },
298
+ ],
299
+ readDependencies: file === undefined
300
+ ? []
301
+ : [
302
+ {
303
+ rootKind: 'mod',
304
+ loadOrder: modRoot?.loadOrder ?? 0,
305
+ relativePath: file.relativePath,
306
+ sha256: file.sha256,
307
+ },
308
+ ],
309
+ validate: (proposed, signal) => {
310
+ signal?.throwIfAborted();
311
+ const bytes = proposed.get(plan.path);
312
+ const matches = bytes !== undefined && bytes !== null && Buffer.from(bytes).equals(plan.bytes);
313
+ return Promise.resolve({
314
+ diagnostics: matches
315
+ ? []
316
+ : [
317
+ {
318
+ code: 'COMMON_WRITE_TRANSACTION_BYTES_MISMATCH',
319
+ severity: 'blocker',
320
+ category: 'validation',
321
+ message: 'Transaction dry-run bytes differ from the planned file',
322
+ },
323
+ ],
324
+ checks: [
325
+ {
326
+ id: 'common-proposed-bytes-match',
327
+ passed: matches,
328
+ message: matches
329
+ ? 'Transaction bytes exactly match the planned file'
330
+ : 'Transaction bytes differ from the planned file',
331
+ },
332
+ ],
333
+ });
334
+ },
335
+ ...(context.signal === undefined ? {} : { signal: context.signal }),
336
+ });
337
+ await context.progress?.(2, 3, 'Definition change prepared for journaled application');
338
+ return { transaction, recipe: { data, diagnostics } };
339
+ }
340
+ export function completeCommonWrite(workspaceId, execution, recipe) {
341
+ const parsed = recipe;
342
+ const data = commonWriteDataSchema.parse({
343
+ ...parsed.data,
344
+ applied: execution.outcome === 'applied',
345
+ });
346
+ const transaction = execution.transaction;
347
+ const result = resultFor(workspaceId, data, execution.outcome);
348
+ result.status = transaction.validation.passed ? 'ok' : 'blocked';
349
+ result.changedFiles = transaction.appliedFiles.slice(0, MAX_INLINE_PATHS);
350
+ const hard = transaction.diagnostics.filter(({ severity }) => severity === 'error' || severity === 'blocker');
351
+ result.diagnostics = [...hard, ...parsed.diagnostics].slice(0, 20);
352
+ result.artifacts = autonomousResultArtifacts(execution).slice(0, MAX_INLINE_ARTIFACTS);
353
+ result.validation = transaction.validation;
354
+ result.blockers = hard.slice(0, 20).map(({ code, message, details }) => ({
355
+ code,
356
+ message,
357
+ ...(details === undefined ? {} : { details }),
358
+ }));
359
+ return result;
360
+ }
@@ -0,0 +1,34 @@
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
+ kind: z.enum(['bop', 'ai_strategy', 'ai_strategy_plan', 'on_action']),
6
+ id: z.string(),
7
+ path: z.string(),
8
+ edit: replacementSchema,
9
+ untouchedDefinitions: z.number().int().nonnegative(),
10
+ findings: z.array(z.object({ severity: z.enum(['warning']), code: z.string(), message: z.string() })),
11
+ references: z.object({
12
+ localisation: z.array(z.string()),
13
+ sprites: z.array(z.string()),
14
+ categories: z.array(z.string()),
15
+ focuses: z.array(z.string()),
16
+ }),
17
+ });
18
+ async function plan(path, input, source) {
19
+ const answer = await callWritePlan({
20
+ op: 'common.block_write.plan',
21
+ path,
22
+ input: { ...input },
23
+ ...(source === undefined ? {} : { source }),
24
+ result: planSchema,
25
+ });
26
+ return { ...answer.result, text: answer.text, bytes: answer.bytes, diff: answer.diff };
27
+ }
28
+ /** The plan that creates a new file holding one new definition, for `createFile: true`. */
29
+ export function planNewCommonFile(path, input) {
30
+ return plan(path, input, undefined);
31
+ }
32
+ export function planCommonWrite(source, input) {
33
+ return plan(source.path, input, source.bytes);
34
+ }
@@ -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()