hoi4-agent-tools 2.2.0 → 2.3.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 (62) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +30 -21
  3. package/dist/bin/stdio.js +0 -4
  4. package/dist/hoi4_agent_tools/core/clausewitz-evaluation.js +90 -0
  5. package/dist/hoi4_agent_tools/core/engine.js +5 -0
  6. package/dist/hoi4_agent_tools/core/index.js +57 -1
  7. package/dist/hoi4_agent_tools/core/source/ast-path.js +41 -0
  8. package/dist/hoi4_agent_tools/core/source/index.js +1 -0
  9. package/dist/hoi4_agent_tools/event/limits.js +1 -1
  10. package/dist/hoi4_agent_tools/mcp/server/create.js +3 -1
  11. package/dist/hoi4_agent_tools/mcp/tools/probability.js +413 -0
  12. package/dist/hoi4_agent_tools/probability/adapters.js +344 -0
  13. package/dist/hoi4_agent_tools/probability/compare.js +178 -0
  14. package/dist/hoi4_agent_tools/probability/evaluation.js +649 -0
  15. package/dist/hoi4_agent_tools/probability/index.js +13 -0
  16. package/dist/hoi4_agent_tools/probability/model.js +5 -0
  17. package/dist/hoi4_agent_tools/probability/rational.js +145 -0
  18. package/dist/hoi4_agent_tools/probability/render.js +307 -0
  19. package/dist/hoi4_agent_tools/probability/sequence.js +858 -0
  20. package/dist/hoi4_agent_tools/probability/service.js +1168 -0
  21. package/dist/hoi4_agent_tools/probability/simulation.js +545 -0
  22. package/dist/hoi4_agent_tools/probability/source-analysis.js +458 -0
  23. package/dist/hoi4_agent_tools/probability/sweep.js +265 -0
  24. package/dist/hoi4_agent_tools/probability/trigger-evaluator.js +280 -0
  25. package/dist/hoi4_agent_tools/probability/value-evaluator.js +357 -0
  26. package/dist/hoi4_agent_tools/schemas/probability.js +930 -0
  27. package/dist/hoi4_agent_tools/version.js +1 -1
  28. package/docs/README.md +1 -0
  29. package/docs/development.md +2 -0
  30. package/docs/probability.md +80 -0
  31. package/docs/research/probability-adapter-evidence.md +64 -0
  32. package/examples/clients/codex-config.toml +3 -0
  33. package/examples/clients/generic.json +8 -0
  34. package/examples/probability/adaptive-event-pool.json +92 -0
  35. package/examples/probability/adaptive-event-sequence-input.json +57 -0
  36. package/examples/probability/event-mtth-scenarios.json +57 -0
  37. package/examples/probability/event-mtth-simulate-input.json +37 -0
  38. package/examples/probability/focus-route-scenarios.json +61 -0
  39. package/examples/probability/focus-route-sweep-input.json +36 -0
  40. package/package.json +17 -8
  41. package/schemas/configuration.schema.json +747 -0
  42. package/schemas/continuous-focus-palette.schema.json +325 -0
  43. package/schemas/custom-weighted-pool.schema.json +298 -0
  44. package/schemas/event-feature-manifest.schema.json +63 -0
  45. package/schemas/focus-plan.schema.json +927 -0
  46. package/schemas/focus-planning-sidecar.schema.json +407 -0
  47. package/schemas/gui-animation-source.schema.json +176 -0
  48. package/schemas/gui-helper.schema.json +301 -0
  49. package/schemas/gui-scenario.schema.json +298 -0
  50. package/schemas/map-operation.schema.json +2284 -0
  51. package/schemas/operation-result.schema.json +327 -0
  52. package/schemas/probability-analysis-result.schema.json +2211 -0
  53. package/schemas/probability-compare-input.schema.json +664 -0
  54. package/schemas/probability-evaluate-input.schema.json +665 -0
  55. package/schemas/probability-inspect-input.schema.json +97 -0
  56. package/schemas/probability-render-input.schema.json +141 -0
  57. package/schemas/probability-scenario-set.schema.json +430 -0
  58. package/schemas/probability-sequence-input.schema.json +886 -0
  59. package/schemas/probability-simulate-input.schema.json +691 -0
  60. package/schemas/probability-sweep-input.schema.json +702 -0
  61. package/server.json +3 -3
  62. package/dist/hoi4_agent_tools/mcp/tools/chaosx.js +0 -530
@@ -1,530 +0,0 @@
1
- import path from 'node:path';
2
- import sharp from 'sharp';
3
- import { z } from 'zod/v4';
4
- import { publicArtifactLink } from '../../core/artifacts.js';
5
- import { compareCodeUnits, hashCanonical } from '../../core/canonical.js';
6
- import { emptyServiceResult } from '../../core/result.js';
7
- import { RenderBudget } from '../../core/render-budget.js';
8
- import { workspaceIdSchema } from '../../schemas/common.js';
9
- import { GuiAssetCatalog } from '../../gui/assets.js';
10
- import { ScriptedGuiStudio } from '../../gui/index.js';
11
- import { buildGuiSourceGraph } from '../../gui/source-graph.js';
12
- import { PACKAGE_VERSION } from '../../version.js';
13
- import { compactValidatedInputSchema } from '../server/context-schemas.js';
14
- import { nonNegativeIntegerSchema, sha256Schema } from '../server/output-schemas.js';
15
- import { progressReporter } from '../server/progress.js';
16
- import { errorResult, setInlineFilesScanned, strictOperationResultSchema, toolResult, } from '../server/result.js';
17
- import { computeFocusVisualRevisions } from './focus.js';
18
- const countryTagSchema = z
19
- .string()
20
- .regex(/^[A-Z0-9]{3}$/u)
21
- .describe('Exact HOI4 country tag selected by ChaosX');
22
- const chaosxCountryAssetsInput = compactValidatedInputSchema(z
23
- .object({
24
- workspaceId: workspaceIdSchema,
25
- countryTags: z.array(countryTagSchema).min(1).max(4),
26
- eventId: z.number().int().min(0).max(999).optional(),
27
- treeId: z.string().min(1).max(256).optional(),
28
- })
29
- .strict(), 'ChaosX-only country tags and optional event/focus identity');
30
- const chaosxCountryAssetsOutput = strictOperationResultSchema(z
31
- .object({
32
- revision: sha256Schema,
33
- countries: z
34
- .array(z
35
- .object({
36
- tag: countryTagSchema,
37
- flagArtifactName: z.string().max(128).optional(),
38
- leaderPortraitArtifactName: z.string().max(128).optional(),
39
- leaderSprite: z.string().max(256).optional(),
40
- })
41
- .strict())
42
- .max(4),
43
- artifactCount: nonNegativeIntegerSchema,
44
- })
45
- .strict());
46
- const visualFocusSelectorSchema = z
47
- .object({
48
- relativePath: z.string().min(1).max(1024),
49
- treeId: z.string().min(1).max(256),
50
- })
51
- .strict();
52
- const visualGuiSelectorSchema = z
53
- .object({
54
- windowName: z.string().min(1).max(256),
55
- guiId: z.string().min(1).max(256),
56
- })
57
- .strict();
58
- const chaosxVisualRevisionInput = compactValidatedInputSchema(z
59
- .object({
60
- workspaceId: workspaceIdSchema,
61
- focusTrees: z.array(visualFocusSelectorSchema).max(3).default([]),
62
- guiWindows: z.array(visualGuiSelectorSchema).max(3).default([]),
63
- countryTags: z.array(countryTagSchema).max(12).default([]),
64
- eventId: z.number().int().min(0).max(999).optional(),
65
- })
66
- .strict(), 'ChaosX-only selectors for fast visual cache revision checks');
67
- const visualRevisionEntrySchema = z
68
- .object({
69
- relativePath: z.string().min(1).max(1024).optional(),
70
- treeId: z.string().min(1).max(256).optional(),
71
- windowName: z.string().min(1).max(256).optional(),
72
- guiId: z.string().min(1).max(256).optional(),
73
- revision: sha256Schema,
74
- })
75
- .strict();
76
- const chaosxVisualRevisionOutput = strictOperationResultSchema(z
77
- .object({
78
- workspaceRevision: sha256Schema,
79
- focusRevisions: z.array(visualRevisionEntrySchema).max(3),
80
- guiRevisions: z.array(visualRevisionEntrySchema).max(3),
81
- countryRevision: sha256Schema,
82
- dependencyFileCount: nonNegativeIntegerSchema,
83
- })
84
- .strict());
85
- const artifactProducing = {
86
- readOnlyHint: false,
87
- destructiveHint: false,
88
- idempotentHint: true,
89
- openWorldHint: false,
90
- };
91
- const readOnly = { ...artifactProducing, readOnlyHint: true };
92
- function activeFiles(snapshot) {
93
- return snapshot.files.filter(({ shadowedBy }) => shadowedBy === undefined);
94
- }
95
- function historyFile(snapshot, tag) {
96
- const prefix = `history/countries/${tag.toLowerCase()} `;
97
- return activeFiles(snapshot)
98
- .filter(({ relativePath }) => relativePath.toLowerCase().startsWith(prefix))
99
- .sort((left, right) => {
100
- const ownership = Number(right.rootKind === 'mod') - Number(left.rootKind === 'mod');
101
- return (ownership ||
102
- right.loadOrder - left.loadOrder ||
103
- compareCodeUnits(left.displayPath, right.displayPath));
104
- })[0];
105
- }
106
- function pictureFromText(file, tag, requireTagPrefix) {
107
- const text = file.bytes.toString('utf8');
108
- const pattern = requireTagPrefix
109
- ? new RegExp(`\\bpicture\\s*=\\s*"?(GFX_portrait_${tag}_[A-Za-z0-9_.:-]+)"?`, 'u')
110
- : /\bpicture\s*=\s*"?(GFX_[A-Za-z0-9_.:-]+)"?/u;
111
- return pattern.exec(text)?.[1];
112
- }
113
- function eventPictureSource(snapshot, tag, eventId) {
114
- const eventPrefix = eventId === undefined ? undefined : String(eventId).padStart(3, '0');
115
- const candidates = activeFiles(snapshot)
116
- .filter(({ relativePath, bytes }) => {
117
- const normalized = relativePath.toLowerCase();
118
- return (normalized.endsWith('.txt') &&
119
- (normalized.startsWith('events/') || normalized.startsWith('common/scripted_effects/')) &&
120
- bytes.includes(Buffer.from(`GFX_portrait_${tag}_`, 'utf8')));
121
- })
122
- .sort((left, right) => {
123
- const leftPreferred = eventPrefix !== undefined && path.posix.basename(left.relativePath).startsWith(eventPrefix);
124
- const rightPreferred = eventPrefix !== undefined &&
125
- path.posix.basename(right.relativePath).startsWith(eventPrefix);
126
- return (Number(rightPreferred) - Number(leftPreferred) ||
127
- compareCodeUnits(left.displayPath, right.displayPath));
128
- });
129
- for (const file of candidates) {
130
- const sprite = pictureFromText(file, tag, true);
131
- if (sprite !== undefined)
132
- return { sprite, path: file.displayPath };
133
- }
134
- return undefined;
135
- }
136
- function leaderSelection(snapshot, tag, eventId) {
137
- const countryHistory = historyFile(snapshot, tag);
138
- const historyPicture = countryHistory === undefined ? undefined : pictureFromText(countryHistory, tag, false);
139
- const eventPicture = historyPicture === undefined ? eventPictureSource(snapshot, tag, eventId) : undefined;
140
- const fallbackSprite = snapshot.index
141
- .findAll('sprite')
142
- .filter(({ overridden, id }) => !overridden && id.startsWith(`GFX_portrait_${tag}_`))
143
- .sort((left, right) => compareCodeUnits(left.id, right.id))[0];
144
- const leaderSprite = historyPicture ?? eventPicture?.sprite ?? fallbackSprite?.id;
145
- if (leaderSprite === undefined)
146
- return {};
147
- const sprite = snapshot.index.find('sprite', leaderSprite);
148
- const texture = typeof sprite?.metadata.texture === 'string' ? sprite.metadata.texture : undefined;
149
- return {
150
- leaderSprite,
151
- ...(texture === undefined ? {} : { leaderTexturePath: texture }),
152
- ...(countryHistory !== undefined
153
- ? { discoverySourcePath: countryHistory.displayPath }
154
- : eventPicture === undefined
155
- ? {}
156
- : { discoverySourcePath: eventPicture.path }),
157
- ...(sprite === undefined ? {} : { spriteSourcePath: sprite.path }),
158
- };
159
- }
160
- function flagCandidates(tag) {
161
- return ['tga', 'dds', 'png'].flatMap((extension) => [
162
- `gfx/flags/${tag}.${extension}`,
163
- `gfx/flags/medium/${tag}.${extension}`,
164
- `gfx/flags/small/${tag}.${extension}`,
165
- ]);
166
- }
167
- async function rasterPng(catalog, assetPath) {
168
- const raster = await catalog.loadRaster(assetPath);
169
- if (!raster.supported || raster.width < 1 || raster.height < 1)
170
- return undefined;
171
- return sharp(raster.data, {
172
- raw: { width: raster.width, height: raster.height, channels: 4 },
173
- })
174
- .png({ compressionLevel: 9, adaptiveFiltering: false, palette: false })
175
- .toBuffer();
176
- }
177
- async function selectCountryAssets(engine, snapshot, workspaceId, tags, eventId, context, signal) {
178
- const selections = tags.map((tag) => ({
179
- tag,
180
- ...leaderSelection(snapshot, tag, eventId),
181
- }));
182
- const patterns = [
183
- ...new Set(selections.flatMap(({ tag, leaderTexturePath }) => [
184
- ...flagCandidates(tag),
185
- ...(leaderTexturePath === undefined ? [] : [leaderTexturePath]),
186
- ])),
187
- ].sort(compareCodeUnits);
188
- const workspace = engine.resolver.get(workspaceId, context.principal);
189
- const scannedAssets = patterns.length === 0
190
- ? []
191
- : await engine.scanner.scan(workspace, {
192
- patterns,
193
- ...(signal === undefined ? {} : { signal }),
194
- });
195
- const graph = buildGuiSourceGraph([], snapshot.index);
196
- const catalog = new GuiAssetCatalog(graph, scannedAssets, new RenderBudget());
197
- for (const selection of selections) {
198
- const flagPath = flagCandidates(selection.tag).find((candidate) => catalog.resolveFile(candidate) !== undefined);
199
- if (flagPath !== undefined)
200
- selection.flagPath = flagPath;
201
- }
202
- return { selections, catalog };
203
- }
204
- function scannerPattern(displayPath) {
205
- const separator = displayPath.indexOf(':');
206
- return separator < 0 ? displayPath : displayPath.slice(separator + 1);
207
- }
208
- async function cachedGuiRevisionCurrent(engine, context, workspaceId, cached, signal) {
209
- const expectedPaths = Object.keys(cached.sourceHashes);
210
- if (expectedPaths.length === 0)
211
- return true;
212
- const workspace = engine.resolver.get(workspaceId, context.principal);
213
- const expected = new Set(expectedPaths);
214
- const scanned = await engine.scanner.scan(workspace, {
215
- patterns: [...new Set(expectedPaths.map(scannerPattern))].sort(compareCodeUnits),
216
- signal,
217
- });
218
- const current = Object.fromEntries(scanned
219
- .filter(({ displayPath }) => expected.has(displayPath))
220
- .map(({ displayPath, sha256 }) => [displayPath, sha256]));
221
- return hashCanonical(current) === hashCanonical(cached.sourceHashes);
222
- }
223
- function collectNamedGuiAttributes(value, keys, output) {
224
- if (Array.isArray(value)) {
225
- for (const entry of value)
226
- collectNamedGuiAttributes(entry, keys, output);
227
- return;
228
- }
229
- if (typeof value !== 'object' || value === null)
230
- return;
231
- for (const [key, entry] of Object.entries(value)) {
232
- if (keys.has(key) && typeof entry === 'string' && entry.length > 0)
233
- output.add(entry);
234
- collectNamedGuiAttributes(entry, keys, output);
235
- }
236
- }
237
- function guiDependencySourceHashes(graph, selector) {
238
- const window = [...graph.elements]
239
- .sort((left, right) => left.definitionOrder - right.definitionOrder)
240
- .find(({ name }) => name === selector.windowName);
241
- if (window === undefined)
242
- throw new Error(`GUI window not found: ${selector.windowName}`);
243
- const scriptedGui = graph.scriptedGuis.find(({ name }) => name === selector.guiId);
244
- if (scriptedGui === undefined)
245
- throw new Error(`Scripted GUI not found: ${selector.guiId}`);
246
- const nodeById = new Map(graph.nodes.map((node) => [node.id, node]));
247
- const elementById = new Map(graph.elements.map((element) => [element.id, element]));
248
- const spriteByName = new Map(graph.sprites.map((sprite) => [sprite.name, sprite]));
249
- const fontByName = new Map(graph.fonts.map((font) => [font.name, font]));
250
- const localisationByKey = new Map();
251
- for (const localisation of graph.localisation)
252
- if (!localisationByKey.has(localisation.key))
253
- localisationByKey.set(localisation.key, localisation);
254
- const outgoing = new Map();
255
- for (const edge of graph.edges) {
256
- if (!edge.resolved)
257
- continue;
258
- const targets = outgoing.get(edge.from) ?? [];
259
- targets.push(edge.to);
260
- outgoing.set(edge.from, targets);
261
- }
262
- const pending = [window.id, scriptedGui.id];
263
- const visited = new Set();
264
- const sourcePaths = new Set([window.sourcePath, scriptedGui.sourcePath]);
265
- while (pending.length > 0) {
266
- const nodeId = pending.pop();
267
- if (nodeId === undefined || visited.has(nodeId))
268
- continue;
269
- visited.add(nodeId);
270
- const node = nodeById.get(nodeId);
271
- if (node !== undefined && graph.sourceHashes[node.path] !== undefined)
272
- sourcePaths.add(node.path);
273
- const element = elementById.get(nodeId);
274
- if (element !== undefined) {
275
- const spriteNames = new Set();
276
- const fontNames = new Set();
277
- const localisationKeys = new Set();
278
- collectNamedGuiAttributes(element.attributes, new Set(['spriteType', 'quadTextureSprite']), spriteNames);
279
- collectNamedGuiAttributes(element.attributes, new Set(['font', 'buttonFont']), fontNames);
280
- collectNamedGuiAttributes(element.attributes, new Set(['text', 'buttonText', 'pdx_tooltip', 'pdx_tooltip_delayed', 'hint_tag']), localisationKeys);
281
- for (const spriteName of spriteNames) {
282
- const sprite = spriteByName.get(spriteName);
283
- if (sprite !== undefined)
284
- pending.push(sprite.id);
285
- }
286
- for (const fontName of fontNames) {
287
- const font = fontByName.get(fontName);
288
- if (font !== undefined)
289
- pending.push(font.id);
290
- }
291
- for (const localisationKey of localisationKeys) {
292
- const localisation = localisationByKey.get(localisationKey);
293
- if (localisation !== undefined)
294
- sourcePaths.add(localisation.sourcePath);
295
- }
296
- }
297
- for (const target of outgoing.get(nodeId) ?? [])
298
- pending.push(target);
299
- }
300
- return Object.fromEntries([...sourcePaths]
301
- .filter((sourcePath) => graph.sourceHashes[sourcePath] !== undefined)
302
- .sort(compareCodeUnits)
303
- .map((sourcePath) => [sourcePath, graph.sourceHashes[sourcePath]]));
304
- }
305
- async function resolveGuiRevision(engine, context, studio, cache, workspaceId, selector, signal) {
306
- const cacheKey = hashCanonical({ workspaceId, selector });
307
- const cached = cache.get(cacheKey);
308
- if (cached !== undefined &&
309
- (await cachedGuiRevisionCurrent(engine, context, workspaceId, cached, signal))) {
310
- return {
311
- windowName: selector.windowName,
312
- guiId: selector.guiId,
313
- revision: cached.sourceRevision,
314
- workspaceRevision: cached.workspaceRevision,
315
- filesScanned: Object.keys(cached.sourceHashes).sort(compareCodeUnits),
316
- };
317
- }
318
- const linted = await studio.lint({
319
- workspaceId,
320
- windowName: selector.windowName,
321
- scenario: {
322
- id: 'chaosx-visual-revision',
323
- resolution: { width: 1920, height: 1080 },
324
- state: 'active',
325
- scriptedGui: { [selector.guiId]: true },
326
- visibility: { [selector.windowName]: true, [selector.guiId]: true },
327
- },
328
- ...(context.principal === undefined ? {} : { principal: context.principal }),
329
- signal,
330
- });
331
- const sourceHashes = guiDependencySourceHashes(linted.graph, selector);
332
- const sourceRevision = hashCanonical({ selector, sourceHashes });
333
- const next = {
334
- workspaceRevision: linted.scene.sourceRevision,
335
- sourceRevision,
336
- sourceHashes,
337
- };
338
- cache.set(cacheKey, next);
339
- return {
340
- windowName: selector.windowName,
341
- guiId: selector.guiId,
342
- revision: sourceRevision,
343
- workspaceRevision: next.workspaceRevision,
344
- filesScanned: Object.keys(sourceHashes).sort(compareCodeUnits),
345
- };
346
- }
347
- function countryRevision(snapshot, selections, catalog) {
348
- const sourceHashes = {};
349
- for (const selection of selections) {
350
- for (const sourcePath of [selection.discoverySourcePath, selection.spriteSourcePath]) {
351
- if (sourcePath === undefined)
352
- continue;
353
- const source = snapshot.files.find(({ displayPath }) => displayPath === sourcePath);
354
- if (source !== undefined)
355
- sourceHashes[source.displayPath] = source.sha256;
356
- }
357
- for (const assetPath of [selection.flagPath, selection.leaderTexturePath]) {
358
- if (assetPath === undefined)
359
- continue;
360
- const source = catalog.resolveFile(assetPath);
361
- if (source !== undefined)
362
- sourceHashes[source.displayPath] = source.sha256;
363
- }
364
- }
365
- return {
366
- revision: hashCanonical({ selections, sourceHashes }),
367
- filesScanned: Object.keys(sourceHashes).sort(compareCodeUnits),
368
- };
369
- }
370
- export function registerChaosxTools(server, engine, context) {
371
- const guiStudio = new ScriptedGuiStudio(engine);
372
- const guiRevisionCache = new Map();
373
- server.registerTool('chaosx.visual_revision', {
374
- title: 'Check ChaosX visual revisions',
375
- description: 'Private ChaosX cache-coherency endpoint. Computes exact source revisions for event, focus, GUI, flag, and leader visuals without rendering PNG artifacts.',
376
- inputSchema: chaosxVisualRevisionInput,
377
- outputSchema: chaosxVisualRevisionOutput,
378
- annotations: readOnly,
379
- }, async (input, extra) => {
380
- const workspaceId = engine.resolver.resolveWorkspaceId(input.workspaceId, context.principal);
381
- try {
382
- const progress = progressReporter(extra);
383
- await progress.report(0, 4, 'Scanning ChaosX visual sources');
384
- const snapshot = await engine.scan(workspaceId, {}, context.principal, progress.signal);
385
- const focusRevisions = await computeFocusVisualRevisions(engine, context, workspaceId, snapshot, input.focusTrees, progress.signal);
386
- await progress.report(1, 4, 'Checking ChaosX GUI sources');
387
- const resolvedGuiRevisions = [];
388
- for (const selector of input.guiWindows)
389
- resolvedGuiRevisions.push(await resolveGuiRevision(engine, context, guiStudio, guiRevisionCache, workspaceId, selector, progress.signal));
390
- const guiRevisions = resolvedGuiRevisions.map(({ windowName, guiId, revision }) => ({
391
- windowName,
392
- guiId,
393
- revision,
394
- }));
395
- await progress.report(2, 4, 'Checking ChaosX country artwork');
396
- const tags = [...new Set(input.countryTags)];
397
- const { selections, catalog } = await selectCountryAssets(engine, snapshot, workspaceId, tags, input.eventId, context, progress.signal);
398
- const countries = countryRevision(snapshot, selections, catalog);
399
- const filesScanned = new Set([
400
- ...focusRevisions.flatMap(({ filesScanned }) => filesScanned),
401
- ...resolvedGuiRevisions.flatMap(({ filesScanned }) => filesScanned),
402
- ...countries.filesScanned,
403
- ]);
404
- const result = emptyServiceResult(workspaceId, {
405
- workspaceRevision: snapshot.revision,
406
- focusRevisions: focusRevisions.map(({ relativePath, treeId, revision }) => ({
407
- relativePath,
408
- treeId,
409
- revision,
410
- })),
411
- guiRevisions,
412
- countryRevision: countries.revision,
413
- dependencyFileCount: filesScanned.size,
414
- });
415
- result.code = 'CHAOSX_VISUAL_REVISION_CHECKED';
416
- setInlineFilesScanned(result, [...filesScanned].sort(compareCodeUnits));
417
- await progress.report(4, 4, 'ChaosX visual revisions complete');
418
- return toolResult(result);
419
- }
420
- catch (error) {
421
- return errorResult(error, workspaceId);
422
- }
423
- });
424
- server.registerTool('chaosx.focus_country_assets', {
425
- title: 'Render ChaosX focus country assets',
426
- description: 'Private ChaosX Discord integration endpoint. Returns country flags and leader portraits to accompany a focus-tree raster; it is not intended for coding-agent workflows.',
427
- inputSchema: chaosxCountryAssetsInput,
428
- outputSchema: chaosxCountryAssetsOutput,
429
- annotations: artifactProducing,
430
- }, async (input, extra) => {
431
- const workspaceId = engine.resolver.resolveWorkspaceId(input.workspaceId, context.principal);
432
- try {
433
- const progress = progressReporter(extra);
434
- await progress.report(0, 3, 'Resolving ChaosX country assets');
435
- const snapshot = await engine.scan(workspaceId, {}, context.principal, progress.signal);
436
- const tags = [...new Set(input.countryTags)];
437
- const { selections, catalog } = await selectCountryAssets(engine, snapshot, workspaceId, tags, input.eventId, context, progress.signal);
438
- await progress.report(1, 3, 'Rasterizing ChaosX country assets');
439
- const writes = [];
440
- const countries = [];
441
- const filesScanned = new Set();
442
- for (const selection of selections) {
443
- const country = { tag: selection.tag };
444
- const sourcePaths = [selection.discoverySourcePath, selection.spriteSourcePath].filter((value) => value !== undefined);
445
- for (const sourcePath of sourcePaths)
446
- filesScanned.add(sourcePath);
447
- if (selection.flagPath !== undefined) {
448
- const png = await rasterPng(catalog, selection.flagPath);
449
- const source = catalog.resolveFile(selection.flagPath);
450
- if (png !== undefined && source !== undefined) {
451
- filesScanned.add(source.displayPath);
452
- const name = `chaosx-${selection.tag}-flag.png`;
453
- country.flagArtifactName = name;
454
- writes.push({
455
- name,
456
- mimeType: 'image/png',
457
- content: png,
458
- provenance: {
459
- kind: 'chaosx-country-flag',
460
- toolVersion: PACKAGE_VERSION,
461
- schemaVersion: 'chaosx-country-assets.v1',
462
- sourceHashes: { [source.displayPath]: source.sha256 },
463
- metadata: {
464
- tag: selection.tag,
465
- eventId: input.eventId ?? null,
466
- treeId: input.treeId ?? null,
467
- },
468
- },
469
- description: `ChaosX country flag for ${selection.tag}`,
470
- });
471
- }
472
- }
473
- if (selection.leaderTexturePath !== undefined) {
474
- const png = await rasterPng(catalog, selection.leaderTexturePath);
475
- const source = catalog.resolveFile(selection.leaderTexturePath);
476
- if (png !== undefined && source !== undefined) {
477
- filesScanned.add(source.displayPath);
478
- const name = `chaosx-${selection.tag}-leader.png`;
479
- country.leaderPortraitArtifactName = name;
480
- const leaderSprite = selection.leaderSprite;
481
- if (leaderSprite !== undefined)
482
- country.leaderSprite = leaderSprite;
483
- const sourceHashes = { [source.displayPath]: source.sha256 };
484
- for (const sourcePath of sourcePaths) {
485
- const file = snapshot.files.find(({ displayPath }) => displayPath === sourcePath);
486
- if (file !== undefined)
487
- sourceHashes[sourcePath] = file.sha256;
488
- }
489
- writes.push({
490
- name,
491
- mimeType: 'image/png',
492
- content: png,
493
- provenance: {
494
- kind: 'chaosx-leader-portrait',
495
- toolVersion: PACKAGE_VERSION,
496
- schemaVersion: 'chaosx-country-assets.v1',
497
- sourceHashes,
498
- metadata: {
499
- tag: selection.tag,
500
- leaderSprite: selection.leaderSprite ?? null,
501
- eventId: input.eventId ?? null,
502
- treeId: input.treeId ?? null,
503
- },
504
- },
505
- description: `ChaosX leader portrait for ${selection.tag}`,
506
- });
507
- }
508
- }
509
- countries.push(country);
510
- }
511
- const workspace = engine.resolver.get(workspaceId, context.principal);
512
- const artifacts = writes.length === 0
513
- ? []
514
- : await engine.artifacts.withAtomicChunkedWrites(workspace, writes, (stored) => Promise.resolve([...stored]), progress.signal);
515
- const result = emptyServiceResult(workspaceId, {
516
- revision: snapshot.revision,
517
- countries,
518
- artifactCount: artifacts.length,
519
- });
520
- result.code = 'CHAOSX_COUNTRY_ASSETS_RENDERED';
521
- setInlineFilesScanned(result, [...filesScanned].sort(compareCodeUnits));
522
- result.artifacts = artifacts.map(publicArtifactLink);
523
- await progress.report(3, 3, 'ChaosX country assets complete');
524
- return toolResult(result);
525
- }
526
- catch (error) {
527
- return errorResult(error, workspaceId);
528
- }
529
- });
530
- }