cwtools-shared 0.2.9 → 0.4.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 (65) hide show
  1. package/dist/debug/zz.d.ts +1 -0
  2. package/dist/debug/zz.js +12 -0
  3. package/dist/generated/mcpTools.d.ts +49 -4
  4. package/dist/generated/mcpTools.js +94 -49
  5. package/dist/generated/workshopDetection.d.ts +22 -0
  6. package/dist/generated/workshopDetection.js +50 -0
  7. package/dist/generated/workspaceDetectionProfiles.d.ts +2 -0
  8. package/dist/generated/workspaceDetectionProfiles.js +84 -0
  9. package/dist/generated/workspaceGameDetection.d.ts +39 -0
  10. package/dist/generated/workspaceGameDetection.js +424 -0
  11. package/dist/host/capabilities.d.ts +39 -0
  12. package/dist/host/capabilities.js +128 -0
  13. package/dist/host/diagnostics.d.ts +8 -1
  14. package/dist/host/filesystem.d.ts +2 -0
  15. package/dist/host/hostServices.d.ts +47 -0
  16. package/dist/host/indexing.d.ts +3 -0
  17. package/dist/host/lsp.d.ts +9 -0
  18. package/dist/host/lsp.js +27 -0
  19. package/dist/host/readiness.js +10 -0
  20. package/dist/host/vanillaCache.js +1 -1
  21. package/dist/index.d.ts +16 -1
  22. package/dist/index.js +22 -1
  23. package/dist/knowledge/interfaceKnowledge.d.ts +8 -0
  24. package/dist/knowledge/interfaceKnowledge.js +222 -0
  25. package/dist/project/descriptor.d.ts +12 -0
  26. package/dist/project/descriptor.js +69 -0
  27. package/dist/project/init.d.ts +11 -0
  28. package/dist/project/init.js +356 -0
  29. package/dist/project/knowledge.d.ts +6 -0
  30. package/dist/project/knowledge.js +20 -8
  31. package/dist/project/profile.d.ts +62 -7
  32. package/dist/project/profile.js +4 -3
  33. package/dist/project/profileBuilder.d.ts +31 -0
  34. package/dist/project/profileBuilder.js +989 -0
  35. package/dist/tools/archetypeArtifacts.d.ts +29 -0
  36. package/dist/tools/archetypeArtifacts.js +136 -0
  37. package/dist/tools/archetypeSlots.d.ts +32 -0
  38. package/dist/tools/archetypeSlots.js +257 -0
  39. package/dist/tools/archetypeTools.d.ts +4 -0
  40. package/dist/tools/archetypeTools.js +118 -0
  41. package/dist/tools/callHandler.d.ts +10 -0
  42. package/dist/tools/callHandler.js +76 -0
  43. package/dist/tools/catalog.d.ts +4094 -0
  44. package/dist/tools/catalog.js +5031 -0
  45. package/dist/tools/domainTools.d.ts +8 -0
  46. package/dist/tools/domainTools.js +222 -0
  47. package/dist/tools/mcpSchema.d.ts +20 -3
  48. package/dist/tools/mcpSchema.js +55 -7
  49. package/dist/tools/mediaWrites.d.ts +52 -0
  50. package/dist/tools/mediaWrites.js +322 -0
  51. package/dist/tools/names.d.ts +4 -4
  52. package/dist/tools/names.js +14 -1
  53. package/dist/tools/pdxWriteCore.d.ts +51 -0
  54. package/dist/tools/pdxWriteCore.js +628 -0
  55. package/dist/tools/pdxWrites.d.ts +88 -0
  56. package/dist/tools/pdxWrites.js +629 -0
  57. package/dist/tools/registry.d.ts +1 -0
  58. package/dist/tools/scopeBridge.d.ts +36 -0
  59. package/dist/tools/scopeBridge.js +173 -0
  60. package/dist/tools/symbols.js +22 -2
  61. package/dist/tools/targetingWeights.d.ts +206 -0
  62. package/dist/tools/targetingWeights.js +350 -0
  63. package/dist/tools/toolHandlers.d.ts +5 -1
  64. package/dist/tools/toolHandlers.js +146 -33
  65. package/package.json +1 -1
@@ -3,7 +3,10 @@ import type { FilesystemHost } from './filesystem';
3
3
  import type { IndexHost } from './indexing';
4
4
  import type { LspHost } from './lsp';
5
5
  import type { VanillaCacheStatus } from './vanillaCache';
6
+ import type { WorkspaceProjectKind } from '../generated/workspaceGameDetection';
6
7
  export type HostLogLevel = 'debug' | 'info' | 'warn' | 'error';
8
+ /** Optional host capabilities used to disclose only tools with a real execution path. */
9
+ export type CwtoolsHostCapability = 'project_init' | 'domain_writes' | 'archetypes' | 'diagnostic_settings' | 'ide_context' | 'visual_editor' | 'gui_capture';
7
10
  export interface ProjectProfileHost {
8
11
  readProfile(): Promise<unknown | null>;
9
12
  }
@@ -15,6 +18,40 @@ export interface GameKnowledgeHost {
15
18
  export interface CompletionHost {
16
19
  getCompletionContext(args: unknown): Promise<unknown>;
17
20
  }
21
+ export interface IdeHost {
22
+ getContext(args: Record<string, unknown>, context?: {
23
+ signal?: AbortSignal;
24
+ }): Promise<unknown>;
25
+ openVisualEditor(args: Record<string, unknown>, context?: {
26
+ signal?: AbortSignal;
27
+ }): Promise<unknown>;
28
+ captureGuiPreview?(args: Record<string, unknown>, context?: {
29
+ signal?: AbortSignal;
30
+ }): Promise<unknown>;
31
+ }
32
+ export interface ExternalCommandRequest {
33
+ command: string;
34
+ args: string[];
35
+ timeoutMs: number;
36
+ signal?: AbortSignal;
37
+ }
38
+ export interface ExternalCommandResult {
39
+ success: boolean;
40
+ stdout?: string;
41
+ stderr?: string;
42
+ message?: string;
43
+ }
44
+ export interface ExternalCommandHost {
45
+ run(request: ExternalCommandRequest): Promise<ExternalCommandResult>;
46
+ }
47
+ export interface MediaToolSettingsHost {
48
+ imageMagickPath?: string;
49
+ ffmpegPath?: string;
50
+ }
51
+ export interface DiagnosticSettingsHost {
52
+ getIgnoredKeys(): Promise<string[]>;
53
+ removeIgnoredKey(key: string): Promise<void>;
54
+ }
18
55
  export interface RulesConfigHost {
19
56
  gameId?: string;
20
57
  configDirs?: string[];
@@ -32,6 +69,8 @@ export interface HostServices {
32
69
  readonlyMode: boolean;
33
70
  writesEnabled: boolean;
34
71
  allowedWriteTools?: ReadonlySet<string>;
72
+ /** Undefined retains the static catalog; a provided set enables strict host filtering. */
73
+ capabilities?: ReadonlySet<CwtoolsHostCapability>;
35
74
  lsp: LspHost;
36
75
  diagnostics: DiagnosticsHost;
37
76
  filesystem: FilesystemHost;
@@ -40,9 +79,17 @@ export interface HostServices {
40
79
  knowledge?: GameKnowledgeHost;
41
80
  completion?: CompletionHost;
42
81
  rules?: RulesConfigHost;
82
+ diagnosticSettings?: DiagnosticSettingsHost;
83
+ ide?: IdeHost;
84
+ externalCommands?: ExternalCommandHost;
85
+ mediaTools?: MediaToolSettingsHost;
43
86
  vanillaCache?: VanillaCacheStatus;
44
87
  projectSupported?: boolean;
45
88
  projectSupportReason?: string;
89
+ projectKind?: WorkspaceProjectKind;
90
+ projectGameId?: string;
91
+ projectEvidence?: string[];
92
+ projectCandidates?: string[];
46
93
  now(): number;
47
94
  log(level: HostLogLevel, message: string, data?: unknown): void;
48
95
  dispose?(): void;
@@ -21,6 +21,9 @@ export interface WorkspaceIndexEntry {
21
21
  container?: string;
22
22
  updatedAt?: number;
23
23
  fileVersion?: number;
24
+ references?: Array<{
25
+ context: string;
26
+ }>;
24
27
  }
25
28
  export interface LocalisationIndexQuery {
26
29
  key?: string;
@@ -1,8 +1,17 @@
1
1
  export interface LspCommandOptions {
2
2
  timeoutMs?: number;
3
+ signal?: AbortSignal;
3
4
  }
4
5
  export interface LspHost {
5
6
  executeCommand<T = unknown>(command: string, args?: unknown[], options?: LspCommandOptions): Promise<T>;
6
7
  request?<T = unknown>(method: string, params?: unknown, options?: LspCommandOptions): Promise<T>;
7
8
  }
9
+ /** True for a DOMException/Error raised because an AbortSignal fired. */
10
+ export declare function isAbortError(error: unknown): boolean;
11
+ /** Build the error a host rejects with when it stops work for an aborted signal. */
12
+ export declare function createAbortError(message?: string): Error;
13
+ /** Rethrow an abort error, ignoring anything else. Used to keep aborts out of `unavailable` paths. */
14
+ export declare function rethrowIfAborted(error: unknown): void;
15
+ /** Throwing guard: clears the way for hosts that poll before each step. */
16
+ export declare function throwIfAborted(signal?: AbortSignal): void;
8
17
  export declare function createUnavailableLspHost(message?: string): LspHost;
package/dist/host/lsp.js CHANGED
@@ -1,6 +1,33 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isAbortError = isAbortError;
4
+ exports.createAbortError = createAbortError;
5
+ exports.rethrowIfAborted = rethrowIfAborted;
6
+ exports.throwIfAborted = throwIfAborted;
3
7
  exports.createUnavailableLspHost = createUnavailableLspHost;
8
+ /** True for a DOMException/Error raised because an AbortSignal fired. */
9
+ function isAbortError(error) {
10
+ if (!error || typeof error !== 'object')
11
+ return false;
12
+ const record = error;
13
+ return record.name === 'AbortError' || record.code === 'ABORT_ERR';
14
+ }
15
+ /** Build the error a host rejects with when it stops work for an aborted signal. */
16
+ function createAbortError(message = 'Operation was aborted.') {
17
+ const error = new Error(message);
18
+ error.name = 'AbortError';
19
+ return error;
20
+ }
21
+ /** Rethrow an abort error, ignoring anything else. Used to keep aborts out of `unavailable` paths. */
22
+ function rethrowIfAborted(error) {
23
+ if (isAbortError(error))
24
+ throw error;
25
+ }
26
+ /** Throwing guard: clears the way for hosts that poll before each step. */
27
+ function throwIfAborted(signal) {
28
+ if (signal?.aborted)
29
+ throw createAbortError(signal.reason instanceof Error ? signal.reason.message : undefined);
30
+ }
4
31
  function createUnavailableLspHost(message = 'CWTools LSP is not connected.') {
5
32
  return {
6
33
  async executeCommand() {
@@ -56,6 +56,16 @@ function annotateReadiness(toolName, result, readiness) {
56
56
  if (readiness.ready) {
57
57
  return { ...result, readiness };
58
58
  }
59
+ // "Backend is gone" is not "backend is still loading": keep the call's own
60
+ // failure (or its fallback success) instead of relabelling it `loading`, which
61
+ // callers would retry forever while the transport stays down.
62
+ if (readiness.reason === 'lsp_unavailable') {
63
+ return {
64
+ ...result,
65
+ readiness,
66
+ warnings: [...(result.warnings ?? []), 'CWTools backend is unavailable; this result carries no semantic model evidence.'],
67
+ };
68
+ }
59
69
  return {
60
70
  ...result,
61
71
  ok: true,
@@ -17,7 +17,7 @@ const GAME_CACHE_PREFIX = {
17
17
  vic3: 'vic3',
18
18
  };
19
19
  function vanillaCacheFileName(game) {
20
- const prefix = GAME_CACHE_PREFIX[(game ?? 'stellaris').toLowerCase()];
20
+ const prefix = game ? GAME_CACHE_PREFIX[game.toLowerCase()] : undefined;
21
21
  return prefix ? `${prefix}.cwb` : undefined;
22
22
  }
23
23
  // Read-only tools whose results are only complete when vanilla data is loaded.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- export * from './generated/mcpTools';
1
+ export * from './tools/catalog';
2
+ export * from './generated/workspaceGameDetection';
3
+ export * from './host/capabilities';
2
4
  export * from './host/diagnostics';
3
5
  export * from './host/filesystem';
4
6
  export * from './host/hostServices';
@@ -9,17 +11,30 @@ export * from './host/vanillaCache';
9
11
  export * from './host/vsCodeHostServices';
10
12
  export * from './knowledge/diagnosticRouting';
11
13
  export * from './knowledge/gameKnowledge';
14
+ export * from './knowledge/interfaceKnowledge';
12
15
  export * from './knowledge/rules';
13
16
  export * from './knowledge/workflowHints';
14
17
  export * from './project/profile';
18
+ export * from './project/init';
19
+ export { buildProjectProfile, mergeDeepCompatibilityEvidence, queryProjectProfile, readProjectProfile, writeProjectProfile } from './project/profileBuilder';
15
20
  export * from './project/knowledge';
16
21
  export * from './safety/localisation';
17
22
  export * from './safety/paths';
18
23
  export * from './safety/writes';
24
+ export * from './tools/archetypeArtifacts';
25
+ export * from './tools/archetypeSlots';
26
+ export * from './tools/archetypeTools';
27
+ export * from './tools/callHandler';
28
+ export * from './tools/domainTools';
19
29
  export * from './tools/mcpSchema';
30
+ export * from './tools/mediaWrites';
31
+ export * from './tools/pdxWriteCore';
32
+ export * from './tools/pdxWrites';
20
33
  export * from './tools/names';
21
34
  export * from './tools/pdxBlock';
22
35
  export * from './tools/registry';
23
36
  export * from './tools/schema';
37
+ export * from './tools/scopeBridge';
24
38
  export * from './tools/symbols';
39
+ export * from './tools/targetingWeights';
25
40
  export * from './tools/toolHandlers';
package/dist/index.js CHANGED
@@ -14,7 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./generated/mcpTools"), exports);
17
+ exports.writeProjectProfile = exports.readProjectProfile = exports.queryProjectProfile = exports.mergeDeepCompatibilityEvidence = exports.buildProjectProfile = void 0;
18
+ __exportStar(require("./tools/catalog"), exports);
19
+ __exportStar(require("./generated/workspaceGameDetection"), exports);
20
+ __exportStar(require("./host/capabilities"), exports);
18
21
  __exportStar(require("./host/diagnostics"), exports);
19
22
  __exportStar(require("./host/filesystem"), exports);
20
23
  __exportStar(require("./host/hostServices"), exports);
@@ -25,17 +28,35 @@ __exportStar(require("./host/vanillaCache"), exports);
25
28
  __exportStar(require("./host/vsCodeHostServices"), exports);
26
29
  __exportStar(require("./knowledge/diagnosticRouting"), exports);
27
30
  __exportStar(require("./knowledge/gameKnowledge"), exports);
31
+ __exportStar(require("./knowledge/interfaceKnowledge"), exports);
28
32
  __exportStar(require("./knowledge/rules"), exports);
29
33
  __exportStar(require("./knowledge/workflowHints"), exports);
30
34
  __exportStar(require("./project/profile"), exports);
35
+ __exportStar(require("./project/init"), exports);
36
+ var profileBuilder_1 = require("./project/profileBuilder");
37
+ Object.defineProperty(exports, "buildProjectProfile", { enumerable: true, get: function () { return profileBuilder_1.buildProjectProfile; } });
38
+ Object.defineProperty(exports, "mergeDeepCompatibilityEvidence", { enumerable: true, get: function () { return profileBuilder_1.mergeDeepCompatibilityEvidence; } });
39
+ Object.defineProperty(exports, "queryProjectProfile", { enumerable: true, get: function () { return profileBuilder_1.queryProjectProfile; } });
40
+ Object.defineProperty(exports, "readProjectProfile", { enumerable: true, get: function () { return profileBuilder_1.readProjectProfile; } });
41
+ Object.defineProperty(exports, "writeProjectProfile", { enumerable: true, get: function () { return profileBuilder_1.writeProjectProfile; } });
31
42
  __exportStar(require("./project/knowledge"), exports);
32
43
  __exportStar(require("./safety/localisation"), exports);
33
44
  __exportStar(require("./safety/paths"), exports);
34
45
  __exportStar(require("./safety/writes"), exports);
46
+ __exportStar(require("./tools/archetypeArtifacts"), exports);
47
+ __exportStar(require("./tools/archetypeSlots"), exports);
48
+ __exportStar(require("./tools/archetypeTools"), exports);
49
+ __exportStar(require("./tools/callHandler"), exports);
50
+ __exportStar(require("./tools/domainTools"), exports);
35
51
  __exportStar(require("./tools/mcpSchema"), exports);
52
+ __exportStar(require("./tools/mediaWrites"), exports);
53
+ __exportStar(require("./tools/pdxWriteCore"), exports);
54
+ __exportStar(require("./tools/pdxWrites"), exports);
36
55
  __exportStar(require("./tools/names"), exports);
37
56
  __exportStar(require("./tools/pdxBlock"), exports);
38
57
  __exportStar(require("./tools/registry"), exports);
39
58
  __exportStar(require("./tools/schema"), exports);
59
+ __exportStar(require("./tools/scopeBridge"), exports);
40
60
  __exportStar(require("./tools/symbols"), exports);
61
+ __exportStar(require("./tools/targetingWeights"), exports);
41
62
  __exportStar(require("./tools/toolHandlers"), exports);
@@ -0,0 +1,8 @@
1
+ export type InterfaceKnowledgeTopic = 'overview' | 'gui_files' | 'gfx_files' | 'buttons_and_effects' | 'custom_windows' | 'off_canvas_hiding' | 'layout' | 'debugging' | 'all';
2
+ export interface InterfaceKnowledgeQuery {
3
+ topic?: InterfaceKnowledgeTopic;
4
+ query?: string;
5
+ elementType?: string;
6
+ limit?: number;
7
+ }
8
+ export declare function queryInterfaceKnowledge(input?: unknown): Record<string, unknown>;
@@ -0,0 +1,222 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.queryInterfaceKnowledge = queryInterfaceKnowledge;
4
+ const SOURCE = {
5
+ title: 'Interface modding - Stellaris Wiki',
6
+ canonicalUrl: 'https://stellaris.paradoxwikis.com/Interface_modding',
7
+ revisionUrl: 'https://stellaris.paradoxwikis.com/index.php?title=Interface_modding&oldid=106757',
8
+ revisionId: 106757,
9
+ license: 'CC BY-SA 3.0',
10
+ retrieval: 'bundled_curated_snapshot',
11
+ };
12
+ const ENTRIES = [
13
+ {
14
+ id: 'preserve_engine_bound_controls',
15
+ topics: ['off_canvas_hiding', 'custom_windows', 'layout'],
16
+ title: 'Preserve engine-bound controls outside the visible canvas',
17
+ summary: 'Existing named GUI instances may be looked up by hardcoded engine logic. Keep their type, name, parent hierarchy, and block present even when the control is not displayed.',
18
+ safePatterns: [
19
+ 'Move the unused control far outside the visible canvas, for example position = { x = -9999 y = -9999 }.',
20
+ 'Preserve established project constants such as @invisible_position instead of normalizing their large values.',
21
+ 'Treat coordinates with an absolute component above 5000 as intentional off-canvas compatibility markers unless current vanilla evidence proves otherwise.',
22
+ ],
23
+ unsafePatterns: [
24
+ 'Deleting a named vanilla/custom_gui control because it is invisible or appears unused.',
25
+ 'Renaming or reparenting an off-canvas control during cleanup.',
26
+ 'Clamping, normalizing, auto-arranging, or pulling extreme coordinates back into the visible canvas.',
27
+ ],
28
+ keywords: ['off canvas', 'offscreen', 'hidden', 'delete', 'crash', 'ctd', 'invisible_position', 'position'],
29
+ riskLevel: 'crash_risk',
30
+ sourceSection: 'Custom Windows / Clearing',
31
+ },
32
+ {
33
+ id: 'button_effect_relationship',
34
+ topics: ['buttons_and_effects'],
35
+ title: 'Choose button types according to their engine and script relationship',
36
+ summary: 'buttonType actions are generally hardcoded. effectButtonType is the mod-facing button form whose effect property can reference /common/button_effects/ and participate in custom GUI behavior.',
37
+ safePatterns: [
38
+ 'Use effectButtonType when a custom UI action must call a verified button effect.',
39
+ 'Resolve the effect identifier in current project or vanilla /common/button_effects/ before writing it.',
40
+ 'Preserve hardcoded button names when modifying an existing vanilla window.',
41
+ ],
42
+ unsafePatterns: [
43
+ 'Assuming a newly created buttonType gains behavior from its visual name or sprite.',
44
+ 'Inventing an effect identifier without checking project and vanilla definitions.',
45
+ 'Renaming an existing button without tracing its engine or script callers.',
46
+ ],
47
+ keywords: ['buttonType', 'effectButtonType', 'effect', 'button_effects', 'custom_gui', 'scripted_gui'],
48
+ riskLevel: 'engine_constraint',
49
+ sourceSection: 'Modifying GUI / buttonType / effectButtonType',
50
+ },
51
+ {
52
+ id: 'custom_window_contract',
53
+ topics: ['custom_windows', 'layout'],
54
+ title: 'Custom windows reuse engine-recognized GUI contracts',
55
+ summary: 'A diplomatic event custom_gui points to a specific containerWindowType. Required instances and expected structure must remain compatible with the engine-facing window contract.',
56
+ safePatterns: [
57
+ 'Read the complete current vanilla container before modifying a custom_gui window.',
58
+ 'Keep required child instances and hide unused visual parts off-canvas.',
59
+ 'Preserve source order when the current template does not prove reordering is safe.',
60
+ ],
61
+ unsafePatterns: [
62
+ 'Replacing the window with a visually equivalent but structurally different tree.',
63
+ 'Deleting portrait, option, heading, background, or other inherited instances solely because the mod does not display them.',
64
+ ],
65
+ keywords: ['custom window', 'custom_gui', 'diplomatic', 'containerWindowType', 'hierarchy', 'instance'],
66
+ riskLevel: 'crash_risk',
67
+ sourceSection: 'Custom Windows / Start / Clearing',
68
+ },
69
+ {
70
+ id: 'gui_and_gfx_roles',
71
+ topics: ['overview', 'gui_files', 'gfx_files'],
72
+ title: 'Separate GUI structure from GFX sprite libraries',
73
+ summary: '.gui files define interface structure and layout; .gfx files bind GFX identifiers to sprite and texture resources used by GUI elements.',
74
+ safePatterns: [
75
+ 'Trace .gui spriteType or quadTextureSprite references to verified .gfx definitions.',
76
+ 'Prefer new mod-owned .gfx library files over editing vanilla files directly.',
77
+ ],
78
+ unsafePatterns: [
79
+ 'Treating a GFX_* identifier as valid merely because a texture file exists.',
80
+ 'Guessing sprite identifiers or changing .gui and .gfx independently.',
81
+ ],
82
+ keywords: ['guiTypes', '.gui', '.gfx', 'spriteType', 'quadTextureSprite', 'texturefile', 'sprite library'],
83
+ riskLevel: 'reference',
84
+ sourceSection: 'Getting Started / GUI Files / GFX Files',
85
+ },
86
+ {
87
+ id: 'layout_hierarchy',
88
+ topics: ['gui_files', 'layout'],
89
+ title: 'Interpret coordinates through the complete parent hierarchy',
90
+ summary: 'Positions, orientations, origo, margins, clipping, and sizes are interpreted relative to parent containers. A local coordinate is not meaningful without its containing window.',
91
+ safePatterns: [
92
+ 'Read the complete parent containerWindowType before changing a child position.',
93
+ 'Preserve orientation and origo until the active hierarchy has been inspected.',
94
+ ],
95
+ unsafePatterns: [
96
+ 'Flattening or reparenting controls based only on their apparent preview position.',
97
+ 'Auto-normalizing large coordinates without distinguishing visible layout from hidden engine instances.',
98
+ ],
99
+ keywords: ['containerWindowType', 'orientation', 'origo', 'position', 'size', 'margin', 'clipping'],
100
+ riskLevel: 'engine_constraint',
101
+ sourceSection: 'GUI Files / Element Attributes / containerWindowType',
102
+ },
103
+ {
104
+ id: 'interface_debugging',
105
+ topics: ['debugging'],
106
+ title: 'Use the game interface debugging loop',
107
+ summary: 'Stellaris provides targeted interface reload and inspection commands that shorten the edit-check cycle, but runtime checks remain necessary for engine-bound behavior.',
108
+ safePatterns: [
109
+ 'Use reload <file>.gui for GUI-only changes when supported.',
110
+ 'Use reload texture all after texture changes and restart when texture resolution changes.',
111
+ 'Use guibounds and debugtooltip to locate engine UI instances and their source files.',
112
+ ],
113
+ unsafePatterns: [
114
+ 'Treating a clean static parse as proof that a custom window will not crash.',
115
+ ],
116
+ keywords: ['reload', 'reload texture all', 'guibounds', 'debugtooltip', 'console'],
117
+ riskLevel: 'reference',
118
+ sourceSection: 'Getting Started',
119
+ },
120
+ ];
121
+ const TOPICS = new Set([
122
+ 'overview',
123
+ 'gui_files',
124
+ 'gfx_files',
125
+ 'buttons_and_effects',
126
+ 'custom_windows',
127
+ 'off_canvas_hiding',
128
+ 'layout',
129
+ 'debugging',
130
+ 'all',
131
+ ]);
132
+ function asRecord(value) {
133
+ return value && typeof value === 'object' && !Array.isArray(value)
134
+ ? value
135
+ : undefined;
136
+ }
137
+ function stringField(record, key) {
138
+ return typeof record?.[key] === 'string' ? record[key].trim() : '';
139
+ }
140
+ function tokens(value) {
141
+ return value.toLowerCase().match(/[a-z0-9_./@-]{2,}|[\u4e00-\u9fff]{2,}/g)?.slice(0, 24) ?? [];
142
+ }
143
+ function normalizeTopic(value) {
144
+ return typeof value === 'string' && TOPICS.has(value)
145
+ ? value
146
+ : 'all';
147
+ }
148
+ function queryInterfaceKnowledge(input = {}) {
149
+ const args = asRecord(input);
150
+ const topic = normalizeTopic(args?.topic);
151
+ const query = stringField(args, 'query');
152
+ const elementType = stringField(args, 'elementType');
153
+ const queryTokens = tokens(`${query} ${elementType}`);
154
+ const rawLimit = typeof args?.limit === 'number' && Number.isFinite(args.limit) ? Math.floor(args.limit) : 5;
155
+ const limit = Math.max(1, Math.min(rawLimit, 10));
156
+ const ranked = ENTRIES
157
+ .map((entry, index) => {
158
+ const searchable = [
159
+ entry.id,
160
+ entry.title,
161
+ entry.summary,
162
+ ...entry.keywords,
163
+ ...entry.safePatterns,
164
+ ...entry.unsafePatterns,
165
+ ].join(' ').toLowerCase();
166
+ const topicScore = topic === 'all' || entry.topics.includes(topic) ? 20 : 0;
167
+ const tokenScore = queryTokens.reduce((score, token) => score + (searchable.includes(token) ? 4 : 0), 0);
168
+ const riskScore = entry.riskLevel === 'crash_risk' ? 2 : entry.riskLevel === 'engine_constraint' ? 1 : 0;
169
+ return { entry, index, score: topicScore + tokenScore + riskScore };
170
+ })
171
+ .filter(item => topic === 'all' || item.score > 0)
172
+ .sort((left, right) => right.score - left.score || left.index - right.index)
173
+ .slice(0, limit)
174
+ .map(({ entry }) => entry);
175
+ const criticalSafetyRules = ENTRIES
176
+ .filter(entry => entry.riskLevel === 'crash_risk')
177
+ .map(entry => ({
178
+ id: entry.id,
179
+ title: entry.title,
180
+ summary: entry.summary,
181
+ safePatterns: entry.safePatterns,
182
+ unsafePatterns: entry.unsafePatterns,
183
+ riskLevel: entry.riskLevel,
184
+ }));
185
+ return {
186
+ status: 'ready',
187
+ scope: 'stellaris_interface',
188
+ topic,
189
+ query: query || undefined,
190
+ elementType: elementType || undefined,
191
+ source: SOURCE,
192
+ // Fact-layer split: static versioned engine guidance vs project facts
193
+ // vs the current-version vanilla contract vs what still needs runtime
194
+ // confirmation. The model must never present engineGuidance as a
195
+ // project fact or an unresolved behavior as settled.
196
+ engineGuidance: {
197
+ versioned: true,
198
+ bundledAt: SOURCE.revisionId,
199
+ criticalSafetyRules,
200
+ entries: ranked,
201
+ instruction: 'Large off-canvas coordinates are intentional compatibility evidence. Never delete, rename, reparent, clamp, or auto-arrange those controls as cleanup.',
202
+ },
203
+ projectGraph: {
204
+ available: false,
205
+ hint: 'Use query_workspace_index with source="gui" (and includeAssetChain for sprite targets) or explore_pdx_project for current project GUI facts.',
206
+ },
207
+ vanillaContract: {
208
+ available: false,
209
+ hint: 'Use query_workspace_index with origin="vanilla" source="gui" or explore_pdx_project on the vanilla GUI file for current-version structure.',
210
+ },
211
+ unresolved: [
212
+ 'Window open/close timing and engine-bound control lookup are hardcoded runtime behavior that static analysis cannot confirm.',
213
+ 'Effect identifiers resolved through scripted GUI or generated button effects still require an in-game verification.',
214
+ ],
215
+ requiredNextChecks: [
216
+ 'Read the complete current project or vanilla parent GUI block before editing.',
217
+ 'Verify .gui to GFX_* to .gfx references with current project and vanilla evidence.',
218
+ 'Resolve effectButtonType effect identifiers in /common/button_effects/ or the current scripted GUI model.',
219
+ 'Run fresh diagnostics after writing; runtime-bound window contracts still require an in-game check.',
220
+ ],
221
+ };
222
+ }
@@ -0,0 +1,12 @@
1
+ export interface ModDescriptor {
2
+ exists: boolean;
3
+ name?: string;
4
+ version?: string;
5
+ tags?: string[];
6
+ supportedVersion?: string;
7
+ remoteFileId?: string;
8
+ dependencies?: string[];
9
+ warnings?: string[];
10
+ }
11
+ /** Read descriptor.mod without throwing; malformed or unreadable fields become warnings. */
12
+ export declare function readDescriptor(root: string): ModDescriptor;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.readDescriptor = readDescriptor;
37
+ const fs = __importStar(require("fs"));
38
+ const path = __importStar(require("path"));
39
+ /** Read descriptor.mod without throwing; malformed or unreadable fields become warnings. */
40
+ function readDescriptor(root) {
41
+ const descriptorPath = path.join(root, 'descriptor.mod');
42
+ if (!fs.existsSync(descriptorPath))
43
+ return { exists: false };
44
+ let content;
45
+ try {
46
+ content = fs.readFileSync(descriptorPath, 'utf8');
47
+ }
48
+ catch {
49
+ return { exists: true, warnings: ['descriptor.mod is not readable; treating it as absent.'] };
50
+ }
51
+ const warnings = [];
52
+ const name = content.match(/^name\s*=\s*"?([^"\r\n]+)"?/m)?.[1]?.trim();
53
+ const version = content.match(/^version\s*=\s*"?([^"\r\n]+)"?/m)?.[1]?.trim();
54
+ const supportedVersion = content.match(/^supported_version\s*=\s*"?([^"\r\n]+)"?/m)?.[1]?.trim();
55
+ const remoteFileId = content.match(/^remote_file_id\s*=\s*"?(\d+)"?/m)?.[1]?.trim();
56
+ const tagsBlock = content.match(/^tags\s*=\s*\{([\s\S]*?)\}/m)?.[1] ?? '';
57
+ const tags = Array.from(tagsBlock.matchAll(/"([^"]+)"/g)).map(match => match[1]).filter((tag) => !!tag);
58
+ const dependenciesBlock = content.match(/^dependencies\s*=\s*\{([\s\S]*?)\}/m)?.[1] ?? '';
59
+ const dependencies = Array.from(dependenciesBlock.matchAll(/"([^"]+)"/g))
60
+ .map(match => match[1]).filter((value) => !!value)
61
+ .filter((value, index, values) => values.indexOf(value) === index);
62
+ if (content.includes('supported_version') && !supportedVersion)
63
+ warnings.push('descriptor.mod declares supported_version but it could not be parsed.');
64
+ if (content.includes('remote_file_id') && !remoteFileId)
65
+ warnings.push('descriptor.mod declares remote_file_id but it could not be parsed.');
66
+ if (content.includes('dependencies') && dependencies.length === 0)
67
+ warnings.push('descriptor.mod declares dependencies but none could be parsed.');
68
+ return { exists: true, name, version, tags, supportedVersion, remoteFileId, dependencies, warnings };
69
+ }
@@ -0,0 +1,11 @@
1
+ import type { HostServices } from '../host/hostServices';
2
+ import type { SharedToolResult } from '../tools/schema';
3
+ export interface InitializeProjectArgs {
4
+ mode?: 'full' | 'incremental';
5
+ changedFiles?: string[];
6
+ domains?: string[];
7
+ }
8
+ /** Initialize the current host workspace; concurrent calls share one bounded export. */
9
+ export declare function initializeProjectWithHost(host: HostServices, rawArgs?: InitializeProjectArgs, context?: {
10
+ signal?: AbortSignal;
11
+ }): Promise<SharedToolResult>;