hoi4-agent-tools 4.7.0 → 4.8.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 +24 -0
- package/README.md +32 -13
- package/dist/hoi4_agent_tools/core/engine-client.js +74 -5
- package/dist/hoi4_agent_tools/core/operation-result.js +9 -0
- package/dist/hoi4_agent_tools/core/resident-engine.js +273 -0
- package/dist/hoi4_agent_tools/core/temporary-directories.js +3 -2
- package/dist/hoi4_agent_tools/decision/service.js +7 -0
- package/dist/hoi4_agent_tools/event/service.js +18 -6
- package/dist/hoi4_agent_tools/event/summary.js +9 -0
- package/dist/hoi4_agent_tools/focus/engine-layout.js +1 -1
- package/dist/hoi4_agent_tools/focus/game-render.js +72 -0
- package/dist/hoi4_agent_tools/focus/game-view-output.js +160 -0
- package/dist/hoi4_agent_tools/focus/native-effects.js +4 -4
- package/dist/hoi4_agent_tools/focus/quality/focus-quality-calibration.json +241 -241
- package/dist/hoi4_agent_tools/focus/quality/orthogonal.js +30 -19
- package/dist/hoi4_agent_tools/focus/quality/schematic.js +5 -3
- package/dist/hoi4_agent_tools/focus/quality/scorecard.js +1 -1
- package/dist/hoi4_agent_tools/focus/render.js +21 -9
- package/dist/hoi4_agent_tools/focus/tool-operations.js +158 -3
- package/dist/hoi4_agent_tools/gui/assets.js +18 -0
- package/dist/hoi4_agent_tools/gui/dds.js +38 -5
- package/dist/hoi4_agent_tools/gui/engine-textures.js +48 -0
- package/dist/hoi4_agent_tools/gui/source-graph.js +7 -0
- package/dist/hoi4_agent_tools/gui/tool-operations.js +23 -4
- package/dist/hoi4_agent_tools/gui/validators.js +31 -2
- package/dist/hoi4_agent_tools/ideas/inspect.js +43 -0
- package/dist/hoi4_agent_tools/localisation/inspect.js +34 -0
- package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
- package/dist/hoi4_agent_tools/mcp/tools/event.js +2 -0
- package/dist/hoi4_agent_tools/mcp/tools/focus.js +1 -1
- package/dist/hoi4_agent_tools/mcp/tools/reference.js +18 -0
- package/dist/hoi4_agent_tools/probability/operations.js +27 -1
- package/dist/hoi4_agent_tools/probability/service.js +91 -11
- package/dist/hoi4_agent_tools/probability/source-analysis.js +2 -2
- package/dist/hoi4_agent_tools/probability/sweep.js +20 -6
- package/dist/hoi4_agent_tools/reference/command-phrases.json +11065 -0
- package/dist/hoi4_agent_tools/reference/error-log.js +24 -0
- package/dist/hoi4_agent_tools/reference/known-mistakes.js +8 -5
- package/dist/hoi4_agent_tools/reference/known-mistakes.json +4 -4
- package/dist/hoi4_agent_tools/reference/operations.js +68 -2
- package/dist/hoi4_agent_tools/reference/ranking.js +32 -0
- package/dist/hoi4_agent_tools/reference/script-validation.js +46 -6
- package/dist/hoi4_agent_tools/reference/service.js +33 -0
- package/dist/hoi4_agent_tools/reference/source-lookup.js +8 -0
- package/dist/hoi4_agent_tools/schemas/focus-requests.js +4 -0
- package/dist/hoi4_agent_tools/schemas/ideas.js +142 -0
- package/dist/hoi4_agent_tools/schemas/localisation.js +94 -0
- package/dist/hoi4_agent_tools/schemas/mod-tools.js +11 -0
- package/dist/hoi4_agent_tools/version.js +1 -1
- package/docs/focus.md +9 -5
- package/docs/research/reference-benchmark.md +41 -0
- package/docs/tools.md +43 -39
- package/docs/troubleshooting.md +13 -12
- package/engine/README.md +284 -0
- 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 +26 -0
- package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +4 -1
- package/schemas/configuration.schema.json +1 -1
- package/schemas/continuous-focus-palette.schema.json +1 -1
- package/schemas/custom-weighted-pool.schema.json +1 -1
- package/schemas/decision-inspect-input.schema.json +1 -1
- package/schemas/error-log-input.schema.json +1 -1
- package/schemas/event-feature-manifest.schema.json +1 -1
- package/schemas/focus-plan.schema.json +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
|
@@ -3,6 +3,7 @@ import { sortDiagnostics } from '../core/diagnostics.js';
|
|
|
3
3
|
import { sha256Bytes } from '../core/canonical.js';
|
|
4
4
|
import { assertRenderDimensions } from '../core/render-budget.js';
|
|
5
5
|
import { GuiAssetCatalog } from './assets.js';
|
|
6
|
+
import { RISKY_TEXTURE_FORMATS } from './engine-textures.js';
|
|
6
7
|
import { GUI_GRAPH_MAX_EDGES, GUI_GRAPH_MAX_NODES, GUI_SCENE_MAX_ELEMENTS, GUI_VALIDATION_MAX_ANCESTOR_HOPS, GUI_VALIDATION_MAX_DIAGNOSTICS, GUI_VALIDATION_MAX_PAIR_COMPARISONS, } from './limits.js';
|
|
7
8
|
/** Horizontal offsets from a parent's centre above rounding and up to a few pixels look accidental. */
|
|
8
9
|
const NEAR_CENTRE_TOLERANCE_PX = 0.5;
|
|
@@ -434,6 +435,31 @@ function validateSourceCosts(graph, scene, diagnostics) {
|
|
|
434
435
|
}
|
|
435
436
|
}
|
|
436
437
|
}
|
|
438
|
+
/**
|
|
439
|
+
* A plain image drawn beneath an element that lies wholly inside it is a background, frame or
|
|
440
|
+
* fill layer, not a collision: panels sit under their titles and frames sit over their fills.
|
|
441
|
+
*/
|
|
442
|
+
function isBackdropLayering(left, right) {
|
|
443
|
+
const isBackdrop = (candidate, other) => candidate.text === undefined &&
|
|
444
|
+
!candidate.clickable &&
|
|
445
|
+
candidate.sprite !== undefined &&
|
|
446
|
+
candidate.zIndex <= other.zIndex &&
|
|
447
|
+
contains(candidate.rect, other.rect, 0.5);
|
|
448
|
+
return isBackdrop(left, right) || isBackdrop(right, left);
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Meters slide a fill image through a clipping window: an icon parked beyond the leading edge
|
|
452
|
+
* is the empty state. Only an image that never reaches past the window's far edges counts, so
|
|
453
|
+
* an icon overflowing to the right or bottom is still reported.
|
|
454
|
+
*/
|
|
455
|
+
function isSlidingFill(element) {
|
|
456
|
+
const clip = element.clipRect;
|
|
457
|
+
if (clip === undefined || element.text !== undefined || element.clickable)
|
|
458
|
+
return false;
|
|
459
|
+
const rect = element.unclippedRect;
|
|
460
|
+
return (rect.x + rect.width <= clip.x + clip.width + 0.5 &&
|
|
461
|
+
rect.y + rect.height <= clip.y + clip.height + 0.5);
|
|
462
|
+
}
|
|
437
463
|
function validateOverlapAndGeometry(scene, diagnostics, work) {
|
|
438
464
|
const visible = scene.elements.filter((element) => element.visible && area(element.rect) > 0);
|
|
439
465
|
const byId = new Map(scene.elements.map((element) => [element.id, element]));
|
|
@@ -454,7 +480,7 @@ function validateOverlapAndGeometry(scene, diagnostics, work) {
|
|
|
454
480
|
if (element.unclippedRect.width <= 0 || element.unclippedRect.height <= 0) {
|
|
455
481
|
diagnostics.push(issue('GUI_INVALID_SIZE', 'warning', 'layout', `${element.name} has a non-positive ${element.unclippedRect.width}x${element.unclippedRect.height} size.`, element));
|
|
456
482
|
}
|
|
457
|
-
if (element.clipped)
|
|
483
|
+
if (element.clipped && !isSlidingFill(element))
|
|
458
484
|
diagnostics.push(issue('GUI_ACCIDENTAL_CLIPPING', 'warning', 'layout', `${element.name} is clipped from ${element.unclippedRect.width}x${element.unclippedRect.height} to ${element.rect.width}x${element.rect.height}.`, element));
|
|
459
485
|
if (element.text?.overflowX === true || element.text?.overflowY === true) {
|
|
460
486
|
diagnostics.push(issue('GUI_TEXT_OVERFLOW', 'warning', 'layout', `${element.name} text measures ${element.text.measuredWidth.toFixed(2)}x${element.text.measuredHeight.toFixed(2)} inside ${element.unclippedRect.width.toFixed(2)}x${element.unclippedRect.height.toFixed(2)}.`, element));
|
|
@@ -501,7 +527,7 @@ function validateOverlapAndGeometry(scene, diagnostics, work) {
|
|
|
501
527
|
if (left.clickable && right.clickable && ratio > 0.02) {
|
|
502
528
|
diagnostics.push(issue('GUI_CONFLICTING_CLICK_REGIONS', 'error', 'design', `${left.name} and ${right.name} have overlapping click regions (${(ratio * 100).toFixed(1)}%).`, right, { left: left.id, right: right.id, ratio }));
|
|
503
529
|
}
|
|
504
|
-
if (left.depth === right.depth && ratio > 0.2) {
|
|
530
|
+
if (left.depth === right.depth && ratio > 0.2 && !isBackdropLayering(left, right)) {
|
|
505
531
|
diagnostics.push(issue('GUI_VISIBLE_OVERLAP', 'warning', 'layout', `${left.name} and ${right.name} overlap by ${(ratio * 100).toFixed(1)}% of the smaller element.`, right, { left: left.id, right: right.id, ratio }));
|
|
506
532
|
}
|
|
507
533
|
const later = left.zIndex > right.zIndex ? left : right;
|
|
@@ -966,6 +992,9 @@ async function validateGuiAnimationsInto(graph, files, selectedSpriteNames, cata
|
|
|
966
992
|
add(sprite.frameAnimated ? 'GUI_ANIMATION_TEXTURE_UNSUPPORTED' : 'GUI_TEXTURE_UNSUPPORTED', 'error', `${sprite.name}: ${raster.reason ?? 'texture unsupported'}`);
|
|
967
993
|
continue;
|
|
968
994
|
}
|
|
995
|
+
const risk = RISKY_TEXTURE_FORMATS[raster.format];
|
|
996
|
+
if (risk !== undefined)
|
|
997
|
+
add('GUI_TEXTURE_FORMAT_RISKY', 'warning', `${sprite.name}: ${sprite.texturePath} is ${raster.format}, which the preview draws. ${risk}`);
|
|
969
998
|
const safeFrameCount = Math.max(1, sprite.frameCount);
|
|
970
999
|
if (raster.width % safeFrameCount !== 0)
|
|
971
1000
|
add(sprite.frameAnimated
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { runEngineCommand } from '../core/engine-client.js';
|
|
2
|
+
import { ServiceError } from '../core/result.js';
|
|
3
|
+
import { ideaEngineAuditSchema, ideaEngineInspectionSchema, } from '../schemas/ideas.js';
|
|
4
|
+
/** A whole-mod audit of a large mod reads every idea, character, sprite and name. */
|
|
5
|
+
const IDEAS_TIMEOUT_MS = 180_000;
|
|
6
|
+
/**
|
|
7
|
+
* `hoi4.idea_inspect` on the shared Rust engine (`hoi4-engine ideas`). This side passes the
|
|
8
|
+
* workspace's roots and turns the engine's answer into the tool's data. A missing engine is
|
|
9
|
+
* `ENGINE_UNAVAILABLE`, with no TypeScript fallback.
|
|
10
|
+
*/
|
|
11
|
+
export async function inspectIdeas(workspace, input, signal) {
|
|
12
|
+
const started = Date.now();
|
|
13
|
+
const request = {
|
|
14
|
+
...(workspace.gameRoot === undefined ? {} : { game: workspace.gameRoot }),
|
|
15
|
+
...(workspace.registration.kind === 'game' ? {} : { mod: workspace.modRoot }),
|
|
16
|
+
dependencies: workspace.dependencyRoots,
|
|
17
|
+
includeDlc: workspace.dlcLayers.length > 0,
|
|
18
|
+
kind: input.kind,
|
|
19
|
+
...(input.id === undefined ? {} : { id: input.id }),
|
|
20
|
+
audit: input.audit,
|
|
21
|
+
limit: input.limit,
|
|
22
|
+
};
|
|
23
|
+
const options = { timeoutMs: IDEAS_TIMEOUT_MS, ...(signal === undefined ? {} : { signal }) };
|
|
24
|
+
if (input.audit) {
|
|
25
|
+
const result = await runEngineCommand('ideas', request, ideaEngineAuditSchema, options);
|
|
26
|
+
if (!result.available)
|
|
27
|
+
throw new ServiceError('ENGINE_UNAVAILABLE', result.message, { reason: result.reason });
|
|
28
|
+
if (result.outcome === 'invalid_request')
|
|
29
|
+
throw new ServiceError(result.error.code, result.error.message);
|
|
30
|
+
return { audit: result.response, durationMs: Date.now() - started };
|
|
31
|
+
}
|
|
32
|
+
const result = await runEngineCommand('ideas', request, ideaEngineInspectionSchema, options);
|
|
33
|
+
if (!result.available)
|
|
34
|
+
throw new ServiceError('ENGINE_UNAVAILABLE', result.message, { reason: result.reason });
|
|
35
|
+
if (result.outcome === 'invalid_request')
|
|
36
|
+
throw new ServiceError(result.error.code, result.error.message);
|
|
37
|
+
const inspection = result.response;
|
|
38
|
+
if (!inspection.found) {
|
|
39
|
+
const suggestions = inspection.suggestions ?? [];
|
|
40
|
+
throw new ServiceError(input.kind === 'idea' ? 'IDEA_NOT_FOUND' : 'CHARACTER_NOT_FOUND', `No loaded file defines the ${input.kind} ${input.id ?? ''}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { id: input.id ?? '', suggestions });
|
|
41
|
+
}
|
|
42
|
+
return { inspection, durationMs: Date.now() - started };
|
|
43
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { runEngineCommand } from '../core/engine-client.js';
|
|
2
|
+
import { ServiceError } from '../core/result.js';
|
|
3
|
+
import { localisationEngineResponseSchema, } from '../schemas/localisation.js';
|
|
4
|
+
/** A whole-mod audit of a large mod reads every localisation file and the mod's script. */
|
|
5
|
+
const LOCALISATION_TIMEOUT_MS = 180_000;
|
|
6
|
+
/**
|
|
7
|
+
* `hoi4.localisation_inspect` on the shared Rust engine. The engine reads the workspace's layers
|
|
8
|
+
* in load order; this side only passes the roots and turns its answer into the tool's data. A
|
|
9
|
+
* missing engine is `ENGINE_UNAVAILABLE`, with no TypeScript fallback.
|
|
10
|
+
*/
|
|
11
|
+
export async function inspectLocalisation(workspace, input, signal) {
|
|
12
|
+
const started = Date.now();
|
|
13
|
+
const isGame = workspace.registration.kind === 'game';
|
|
14
|
+
const result = await runEngineCommand('localisation', {
|
|
15
|
+
...(workspace.gameRoot === undefined ? {} : { game: workspace.gameRoot }),
|
|
16
|
+
...(isGame ? {} : { mod: workspace.modRoot }),
|
|
17
|
+
dependencies: workspace.dependencyRoots,
|
|
18
|
+
includeDlc: workspace.dlcLayers.length > 0,
|
|
19
|
+
mode: input.mode,
|
|
20
|
+
...(input.key === undefined ? {} : { key: input.key }),
|
|
21
|
+
...(input.language === undefined ? {} : { language: input.language }),
|
|
22
|
+
limit: input.limit,
|
|
23
|
+
}, localisationEngineResponseSchema, { timeoutMs: LOCALISATION_TIMEOUT_MS, ...(signal === undefined ? {} : { signal }) });
|
|
24
|
+
if (!result.available)
|
|
25
|
+
throw new ServiceError('ENGINE_UNAVAILABLE', result.message, { reason: result.reason });
|
|
26
|
+
if (result.outcome === 'invalid_request')
|
|
27
|
+
throw new ServiceError(result.error.code, result.error.message);
|
|
28
|
+
const answer = result.response;
|
|
29
|
+
if (answer.key?.found === false) {
|
|
30
|
+
const suggestions = answer.key.suggestions ?? [];
|
|
31
|
+
throw new ServiceError('LOCALISATION_KEY_NOT_FOUND', `No language defines ${input.key ?? ''}${suggestions.length === 0 ? '' : `; did you mean ${suggestions.join(', ')}?`}`, { key: input.key ?? '', suggestions, mentions: answer.key.mentions.length });
|
|
32
|
+
}
|
|
33
|
+
return { ...answer, durationMs: Date.now() - started };
|
|
34
|
+
}
|
|
@@ -13,6 +13,8 @@ export const ARGUMENT_EXAMPLES = {
|
|
|
13
13
|
'hoi4.script_validate': '{"path":"events/my_events.txt"} or {"source":"add_political_power = 10","kind":"effect","scope":"country"}',
|
|
14
14
|
'hoi4.error_log': '{"scope":"mod","category":"effect"}',
|
|
15
15
|
'hoi4.mod_index': '{"mode":"overview"} or {"mode":"next_id","kind":"event","namespace":"my_mod"}',
|
|
16
|
+
'hoi4.localisation_inspect': '{"mode":"key","key":"my_event.1.t"} or {"mode":"audit"}',
|
|
17
|
+
'hoi4.idea_inspect': '{"kind":"idea","id":"my_idea"} or {"kind":"character","audit":true}',
|
|
16
18
|
'hoi4.event_inspect': '{"mode":"lint","selector":"chaosx.nr14"} or {"mode":"trace","selector":"chaosx.nr14.1","direction":"downstream"}',
|
|
17
19
|
'hoi4.event_render': '{"view":"overview","selector":"chaosx.nr14"}',
|
|
18
20
|
'hoi4.focus_inspect': '{"treeId":"my_focus_tree"}',
|
|
@@ -104,6 +104,8 @@ const eventInspectSummarySchema = z
|
|
|
104
104
|
edges: nonNegativeIntegerSchema,
|
|
105
105
|
events: nonNegativeIntegerSchema,
|
|
106
106
|
eventIds: inlineIdsSchema,
|
|
107
|
+
entryPoints: inlineIdsSchema,
|
|
108
|
+
helpers: inlineIdsSchema,
|
|
107
109
|
boundaryNodes: nonNegativeIntegerSchema,
|
|
108
110
|
truncated: z.boolean(),
|
|
109
111
|
})
|
|
@@ -71,7 +71,7 @@ const focusRenderOutputSchema = strictOperationResultSchema(z.discriminatedUnion
|
|
|
71
71
|
inlineImages: z
|
|
72
72
|
.array(z
|
|
73
73
|
.object({
|
|
74
|
-
kind: z.enum(['overview', 'branch', 'focus', 'problem']),
|
|
74
|
+
kind: z.enum(['overview', 'branch', 'focus', 'problem', 'game']),
|
|
75
75
|
label: z.string().max(300),
|
|
76
76
|
focusIds: z.array(z.string().max(256)).max(50),
|
|
77
77
|
region: z
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { errorResult, strictOperationResultSchema } from '../../core/operation-result.js';
|
|
2
2
|
import { ReferenceToolService } from '../../reference/operations.js';
|
|
3
3
|
import { referenceContextRequestSchema, referenceReadRequestSchema, referenceSearchRequestSchema, sourceLookupRequestSchema, referenceContextDataSchema, referenceReadDataSchema, referenceSearchDataSchema, sourceLookupDataSchema, } from '../../schemas/reference.js';
|
|
4
|
+
import { localisationInspectDataSchema, localisationInspectRequestSchema, } from '../../schemas/localisation.js';
|
|
5
|
+
import { ideaInspectDataSchema, ideaInspectRequestSchema } from '../../schemas/ideas.js';
|
|
4
6
|
import { errorLogDataSchema, errorLogRequestSchema, modIndexDataSchema, modIndexRequestSchema, } from '../../schemas/mod-tools.js';
|
|
5
7
|
import { scriptValidateDataSchema, scriptValidateRequestSchema, } from '../../schemas/script-validation.js';
|
|
6
8
|
const readOnly = {
|
|
@@ -66,6 +68,22 @@ export const referenceTools = [
|
|
|
66
68
|
outputSchema: strictOperationResultSchema(modIndexDataSchema),
|
|
67
69
|
annotations: readOnly,
|
|
68
70
|
},
|
|
71
|
+
{
|
|
72
|
+
name: 'hoi4.localisation_inspect',
|
|
73
|
+
title: 'Check localisation in every language',
|
|
74
|
+
description: 'Read localisation in every language the game and mod ship. key: one key per language with file, line and layer, the languages lacking it and the files mentioning it. audit: keys the mod uses that no language defines, keys missing from a supported language, keys defined twice in one language, and file problems. coverage: keys per language. Example: {"mode":"key","key":"my_event.1.t"} or {"mode":"audit"}. Returns counts per problem and a few examples of each.',
|
|
75
|
+
inputSchema: localisationInspectRequestSchema,
|
|
76
|
+
outputSchema: strictOperationResultSchema(localisationInspectDataSchema),
|
|
77
|
+
annotations: readOnly,
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
name: 'hoi4.idea_inspect',
|
|
81
|
+
title: 'Inspect ideas and characters',
|
|
82
|
+
description: 'Read an idea or character across the game, DLC and mod. idea: category, picture sprite and texture, modifiers checked against the game docs, conditions, name in every language, the advisor it belongs to, and files mentioning it. character: name, roles with traits checked, portraits checked. audit: true checks every idea or character of the mod. Example: {"kind":"idea","id":"GER_mefo_bills_1"} or {"kind":"character","audit":true}.',
|
|
83
|
+
inputSchema: ideaInspectRequestSchema,
|
|
84
|
+
outputSchema: strictOperationResultSchema(ideaInspectDataSchema),
|
|
85
|
+
annotations: readOnly,
|
|
86
|
+
},
|
|
69
87
|
];
|
|
70
88
|
export function registerReferenceTools(server, engine, context) {
|
|
71
89
|
const service = new ReferenceToolService(engine);
|
|
@@ -185,11 +185,26 @@ export async function inspectProbabilities(analyzer, input, context) {
|
|
|
185
185
|
let inspected = await analyzer.inspect(runtime(context, input.refresh), input.adapter, source, candidatePool, customPoolManifest);
|
|
186
186
|
// A wrong adapter guess, such as a mission named as a decision, should not cost another call.
|
|
187
187
|
const suggested = inspected.discovery?.suggestedAdapter;
|
|
188
|
+
// Without an adapter, an identifier or pool that names weighted blocks picks its own adapter:
|
|
189
|
+
// an event id evaluates its options rather than returning the whole source inventory.
|
|
190
|
+
const namedBySource = input.adapter === undefined &&
|
|
191
|
+
inspected.discovery?.reason === 'source_inventory' &&
|
|
192
|
+
inspected.discovery.availableAdapters.some(({ adapterId, identifierMatchCount, candidatePoolMatchCount }) => adapterId === suggested && (identifierMatchCount > 0 || candidatePoolMatchCount > 0)) &&
|
|
193
|
+
(source?.identifier !== undefined || candidatePool.length > 0);
|
|
194
|
+
const alternatives = namedBySource
|
|
195
|
+
? inspected
|
|
196
|
+
.discovery.availableAdapters.filter(({ adapterId, identifierMatchCount, candidatePoolMatchCount }) => adapterId !== suggested &&
|
|
197
|
+
(source?.identifier === undefined
|
|
198
|
+
? candidatePoolMatchCount > 0
|
|
199
|
+
: identifierMatchCount > 0))
|
|
200
|
+
.map(({ adapterId }) => adapterId)
|
|
201
|
+
: [];
|
|
188
202
|
if (input.evaluate !== false &&
|
|
189
203
|
inspected.surface === undefined &&
|
|
190
204
|
suggested !== undefined &&
|
|
191
205
|
suggested !== input.adapter &&
|
|
192
|
-
(
|
|
206
|
+
(namedBySource ||
|
|
207
|
+
inspected.discovery?.reason === 'candidate_pool_not_found' ||
|
|
193
208
|
inspected.discovery?.reason === 'requested_adapter_empty' ||
|
|
194
209
|
inspected.discovery?.reason === 'identifier_not_found'))
|
|
195
210
|
inspected = await analyzer.inspect(runtime(context), suggested, source, candidatePool, customPoolManifest);
|
|
@@ -221,6 +236,17 @@ export async function inspectProbabilities(analyzer, input, context) {
|
|
|
221
236
|
});
|
|
222
237
|
const result = probabilityAnalysisServiceResult(context.workspaceId, analyzed);
|
|
223
238
|
result.artifacts = [...result.artifacts, ...inspected.artifacts];
|
|
239
|
+
if (namedBySource && alternatives.length > 0)
|
|
240
|
+
result.diagnostics = [
|
|
241
|
+
{
|
|
242
|
+
code: 'PROBABILITY_ADAPTER_SELECTED',
|
|
243
|
+
severity: 'info',
|
|
244
|
+
category: 'configuration',
|
|
245
|
+
message: `No adapter was requested, so ${surface.adapter.id} was used; pass adapter to evaluate ${alternatives.join(', ')} instead`,
|
|
246
|
+
details: { adapterId: surface.adapter.id, alternatives },
|
|
247
|
+
},
|
|
248
|
+
...result.diagnostics,
|
|
249
|
+
];
|
|
224
250
|
if (input.scenarioSet === undefined)
|
|
225
251
|
result.diagnostics = [
|
|
226
252
|
{
|
|
@@ -52,6 +52,12 @@ function resolveSourceBackedAdapter(snapshot, source, candidatePool, requested)
|
|
|
52
52
|
(error.code !== 'PROBABILITY_SURFACE_EMPTY' &&
|
|
53
53
|
error.code !== 'PROBABILITY_IDENTIFIER_NOT_FOUND'))
|
|
54
54
|
throw error;
|
|
55
|
+
// An explicit adapter is honoured or refused. Running another one would answer a
|
|
56
|
+
// different question than the one asked.
|
|
57
|
+
const alternatives = inventoryWeightedSurfaces(snapshot, source, candidatePool).adapters.filter(({ candidateCount }) => candidateCount > 0);
|
|
58
|
+
throw new ServiceError(error.code, `Adapter ${requested} found no matching weighted blocks in this source${alternatives.length === 0
|
|
59
|
+
? ''
|
|
60
|
+
: `; adapters with weighted blocks here: ${alternatives.map(({ adapterId }) => adapterId).join(', ')}`}`, { requestedAdapter: requested, source, candidatePool, availableAdapters: alternatives });
|
|
55
61
|
}
|
|
56
62
|
}
|
|
57
63
|
const inventory = inventoryWeightedSurfaces(snapshot, source, candidatePool);
|
|
@@ -210,8 +216,61 @@ function filterCandidateMetrics(candidate, metrics) {
|
|
|
210
216
|
: {}),
|
|
211
217
|
};
|
|
212
218
|
}
|
|
219
|
+
/** A requested metric that no candidate carries gets a reason instead of a silent null. */
|
|
220
|
+
function unmetMetricDiagnostics(scenarios, surface, requested) {
|
|
221
|
+
const output = [];
|
|
222
|
+
const candidates = scenarios.flatMap((scenario) => scenario.candidates);
|
|
223
|
+
const timed = surface.adapter.id === 'event_mean_time_to_happen';
|
|
224
|
+
const pending = candidates.some(({ eligibility }) => eligibility === 'unresolved') ||
|
|
225
|
+
scenarios.some(({ unresolved }) => unresolved.length > 0);
|
|
226
|
+
const reasonFor = (metric) => {
|
|
227
|
+
if (candidates.some((candidate) => {
|
|
228
|
+
if (metric === 'conditional_probability')
|
|
229
|
+
return (candidate.conditionalProbability !== undefined &&
|
|
230
|
+
candidate.conditionalProbability !== null);
|
|
231
|
+
if (metric === 'cumulative_chance')
|
|
232
|
+
return candidate.cumulativeChance !== undefined;
|
|
233
|
+
if (metric === 'effective_mtth_days')
|
|
234
|
+
return candidate.effectiveMtthDays !== undefined;
|
|
235
|
+
return candidate.rawValue !== undefined && candidate.rawValue !== null;
|
|
236
|
+
}))
|
|
237
|
+
return undefined;
|
|
238
|
+
if (metric === 'conditional_probability') {
|
|
239
|
+
if (surface.adapter.selectionRule === 'score_only')
|
|
240
|
+
return `${surface.adapter.id} is score-only, so its weights are not normalized into probabilities`;
|
|
241
|
+
if (timed)
|
|
242
|
+
return 'a mean time to happen is a timing model with no categorical probability; use cumulative_chance with horizonDays';
|
|
243
|
+
if (!surface.poolComplete && surface.adapter.completePoolRequired)
|
|
244
|
+
return 'the candidate pool is not proven complete';
|
|
245
|
+
}
|
|
246
|
+
if (metric === 'cumulative_chance' || metric === 'effective_mtth_days') {
|
|
247
|
+
if (!timed)
|
|
248
|
+
return `${surface.adapter.id} has no timing model`;
|
|
249
|
+
if (metric === 'cumulative_chance' &&
|
|
250
|
+
scenarios.every(({ horizonDays }) => horizonDays === undefined))
|
|
251
|
+
return 'cumulative_chance needs horizonDays, the number of days to accumulate over';
|
|
252
|
+
}
|
|
253
|
+
return pending
|
|
254
|
+
? 'a condition or value in the source needs a scenario fact that was not declared (see missingInputs)'
|
|
255
|
+
: 'the adapter did not produce this metric for the evaluated candidates';
|
|
256
|
+
};
|
|
257
|
+
for (const metric of requested ?? []) {
|
|
258
|
+
const reason = reasonFor(metric);
|
|
259
|
+
if (reason !== undefined)
|
|
260
|
+
output.push({
|
|
261
|
+
code: 'PROBABILITY_METRIC_NOT_COMPUTED',
|
|
262
|
+
severity: 'warning',
|
|
263
|
+
category: 'validation',
|
|
264
|
+
message: `${metric} was requested but not computed: ${reason}`,
|
|
265
|
+
details: { metric, adapterId: surface.adapter.id },
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
return output;
|
|
269
|
+
}
|
|
213
270
|
function diagnosticsFor(scenarios, surface, extra = {}) {
|
|
214
|
-
const diagnostics = [
|
|
271
|
+
const diagnostics = [
|
|
272
|
+
...unmetMetricDiagnostics(scenarios, surface, extra.requestedMetrics),
|
|
273
|
+
];
|
|
215
274
|
const thresholds = resolvedThresholds(extra.diagnosticThresholds);
|
|
216
275
|
if (!surface.poolComplete && surface.adapter.completePoolRequired)
|
|
217
276
|
diagnostics.push({
|
|
@@ -895,15 +954,23 @@ export class ProbabilityAnalyzer {
|
|
|
895
954
|
adapter: surface.adapter,
|
|
896
955
|
scenarios,
|
|
897
956
|
...(prevalenceAggregate === undefined ? {} : { prevalenceAggregate }),
|
|
898
|
-
diagnostics:
|
|
899
|
-
...(
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
? {}
|
|
904
|
-
: {
|
|
905
|
-
|
|
906
|
-
|
|
957
|
+
diagnostics: [
|
|
958
|
+
...diagnosticsFor(scenarios, surface, {
|
|
959
|
+
...(metadata.requestedMetrics === undefined
|
|
960
|
+
? {}
|
|
961
|
+
: { requestedMetrics: metadata.requestedMetrics }),
|
|
962
|
+
...(extra.sweep === undefined ? {} : { sweep: extra.sweep }),
|
|
963
|
+
...(extra.simulation === undefined ? {} : { simulation: extra.simulation }),
|
|
964
|
+
...(extra.acceptanceBands === undefined
|
|
965
|
+
? {}
|
|
966
|
+
: { acceptanceBands: extra.acceptanceBands }),
|
|
967
|
+
...(extra.diagnosticThresholds === undefined
|
|
968
|
+
? {}
|
|
969
|
+
: { diagnosticThresholds: extra.diagnosticThresholds }),
|
|
970
|
+
...(extra.unresolved === undefined ? {} : { unresolved: extra.unresolved }),
|
|
971
|
+
}),
|
|
972
|
+
...(extra.diagnostics ?? []),
|
|
973
|
+
],
|
|
907
974
|
unresolved,
|
|
908
975
|
...(extra.sweep === undefined ? {} : { sweep: extra.sweep }),
|
|
909
976
|
...(extra.simulation === undefined ? {} : { simulation: extra.simulation }),
|
|
@@ -1205,9 +1272,22 @@ export class ProbabilityAnalyzer {
|
|
|
1205
1272
|
const analyzed = await this.analyzeUnstored('sweep', request, { sweep: request.sweep });
|
|
1206
1273
|
if (analyzed.result.operation === 'sweep' && analyzed.result.sweep !== undefined)
|
|
1207
1274
|
return this.store(analyzed.result, request.outputs ?? ['json', 'sensitivity'], false, request.signal, request.principal);
|
|
1208
|
-
const sweep = sweepSurface(analyzed.surface, request.scenarioSet.scenarios, analyzed.definitions, request.sweep, request.signal);
|
|
1275
|
+
const { defaultedRanges, ...sweep } = sweepSurface(analyzed.surface, request.scenarioSet.scenarios, analyzed.definitions, request.sweep, request.signal);
|
|
1209
1276
|
const result = this.buildResult('sweep', analyzed.result.metadata, analyzed.surface, analyzed.result.scenarios, {
|
|
1210
1277
|
sweep,
|
|
1278
|
+
...(defaultedRanges.length === 0
|
|
1279
|
+
? {}
|
|
1280
|
+
: {
|
|
1281
|
+
diagnostics: [
|
|
1282
|
+
{
|
|
1283
|
+
code: 'PROBABILITY_SWEEP_RANGE_DEFAULTED',
|
|
1284
|
+
severity: 'info',
|
|
1285
|
+
category: 'configuration',
|
|
1286
|
+
message: 'No range or alternatives were declared for some sweep paths, so the requested steps were spread from zero to twice the current value; declare uncertainInputs to choose the range',
|
|
1287
|
+
details: { ranges: defaultedRanges },
|
|
1288
|
+
},
|
|
1289
|
+
],
|
|
1290
|
+
}),
|
|
1211
1291
|
...(request.acceptanceBands === undefined
|
|
1212
1292
|
? {}
|
|
1213
1293
|
: { acceptanceBands: request.acceptanceBands }),
|
|
@@ -152,9 +152,9 @@ function decisionCandidates(context, adapterId) {
|
|
|
152
152
|
eventKeys.has(ancestors[0].key) ||
|
|
153
153
|
ignored.has(assignment.key.value))
|
|
154
154
|
continue;
|
|
155
|
+
// days_remove is not a mission marker: ordinary decisions often carry days_remove = -1.
|
|
155
156
|
const mission = firstScalar(assignment.value, 'is_mission')?.value === 'yes' ||
|
|
156
|
-
firstScalar(assignment.value, 'days_mission_timeout') !== undefined
|
|
157
|
-
firstScalar(assignment.value, 'days_remove') !== undefined;
|
|
157
|
+
firstScalar(assignment.value, 'days_mission_timeout') !== undefined;
|
|
158
158
|
if ((adapterId === 'mission_ai_will_do') !== mission)
|
|
159
159
|
continue;
|
|
160
160
|
const weight = childBlocks(assignment.value, 'ai_will_do')[0];
|
|
@@ -2,7 +2,13 @@ import { ServiceError } from '../core/result.js';
|
|
|
2
2
|
import { conditionBreakpointValues, evaluateSurfaceScenarios } from './evaluation.js';
|
|
3
3
|
import { scenarioPathValue, withScenarioPathValue } from './scenario-state.js';
|
|
4
4
|
const MAX_SWEEP_POINTS = 250_000;
|
|
5
|
-
|
|
5
|
+
/** From zero to twice the current value, so the declared value sits in the middle of the sweep. */
|
|
6
|
+
function defaultRange(current) {
|
|
7
|
+
if (current === 0)
|
|
8
|
+
return { min: 0, max: 1 };
|
|
9
|
+
return current > 0 ? { min: 0, max: current * 2 } : { min: current * 2, max: 0 };
|
|
10
|
+
}
|
|
11
|
+
function declaredValues(surface, scenario, path, steps, defaulted) {
|
|
6
12
|
const uncertain = scenario.uncertainInputs?.find((input) => input.path === path);
|
|
7
13
|
if (uncertain?.range !== undefined)
|
|
8
14
|
return [
|
|
@@ -17,8 +23,14 @@ function declaredValues(surface, scenario, path, steps) {
|
|
|
17
23
|
return [...new Set(values)].sort((left, right) => left - right);
|
|
18
24
|
}
|
|
19
25
|
const current = scenarioPathValue(scenario, path);
|
|
20
|
-
if (typeof current === 'number')
|
|
21
|
-
|
|
26
|
+
if (typeof current === 'number') {
|
|
27
|
+
// Only a current value is declared. Sweeping it as one point would ignore the requested
|
|
28
|
+
// steps, so spread them over a default range and report the range that was chosen.
|
|
29
|
+
const range = defaultRange(current);
|
|
30
|
+
if (!defaulted.some((item) => item.scenarioId === scenario.id && item.path === path))
|
|
31
|
+
defaulted.push({ scenarioId: scenario.id, path, current, ...range });
|
|
32
|
+
return values(range, steps);
|
|
33
|
+
}
|
|
22
34
|
throw new ServiceError('PROBABILITY_SWEEP_RANGE_REQUIRED', 'Every sweep path requires a scenario range, numeric alternatives, or numeric state value', { scenarioId: scenario.id, path });
|
|
23
35
|
}
|
|
24
36
|
function values(range, steps) {
|
|
@@ -217,14 +229,15 @@ export function sweepSurface(surface, scenarios, definitions, request, signal) {
|
|
|
217
229
|
limit: MAX_SWEEP_POINTS,
|
|
218
230
|
});
|
|
219
231
|
const points = [];
|
|
232
|
+
const defaultedRanges = [];
|
|
220
233
|
for (const scenario of scenarios) {
|
|
221
234
|
if (request.pairwise && request.paths.length > 1) {
|
|
222
235
|
for (let leftIndex = 0; leftIndex < request.paths.length; leftIndex += 1) {
|
|
223
236
|
for (let rightIndex = leftIndex + 1; rightIndex < request.paths.length; rightIndex += 1) {
|
|
224
237
|
const leftPath = request.paths[leftIndex];
|
|
225
238
|
const rightPath = request.paths[rightIndex];
|
|
226
|
-
const leftValues = declaredValues(surface, scenario, leftPath, request.steps);
|
|
227
|
-
const rightValues = declaredValues(surface, scenario, rightPath, request.steps);
|
|
239
|
+
const leftValues = declaredValues(surface, scenario, leftPath, request.steps, defaultedRanges);
|
|
240
|
+
const rightValues = declaredValues(surface, scenario, rightPath, request.steps, defaultedRanges);
|
|
228
241
|
for (const left of leftValues) {
|
|
229
242
|
for (const right of rightValues) {
|
|
230
243
|
if ((points.length & 1023) === 0)
|
|
@@ -242,7 +255,7 @@ export function sweepSurface(surface, scenarios, definitions, request, signal) {
|
|
|
242
255
|
}
|
|
243
256
|
else {
|
|
244
257
|
for (const path of request.paths) {
|
|
245
|
-
for (const value of declaredValues(surface, scenario, path, request.steps)) {
|
|
258
|
+
for (const value of declaredValues(surface, scenario, path, request.steps, defaultedRanges)) {
|
|
246
259
|
if ((points.length & 1023) === 0)
|
|
247
260
|
signal?.throwIfAborted();
|
|
248
261
|
if (points.length >= MAX_SWEEP_POINTS)
|
|
@@ -265,5 +278,6 @@ export function sweepSurface(surface, scenarios, definitions, request, signal) {
|
|
|
265
278
|
breakpoints,
|
|
266
279
|
localElasticities: localElasticities(points),
|
|
267
280
|
pairwiseInteractions: pairwiseInteractions(points),
|
|
281
|
+
defaultedRanges,
|
|
268
282
|
};
|
|
269
283
|
}
|