dsh-unreal-python-api 1.3.0 → 1.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.
package/lib/project.js ADDED
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Read-only project inventory.
3
+ *
4
+ * Two kinds of truth are kept apart and labelled:
5
+ * - what the project *declares* (`.uproject`, `Source/`, `Plugins/`), read from
6
+ * the filesystem without loading the editor;
7
+ * - what the editor *indexed* (asset counts, symbol counts, tags), read from
8
+ * Monolith inside the running editor.
9
+ *
10
+ * When the editor is unreachable the declared half is still returned, and the
11
+ * indexed half is `null` with the exact error. Nothing is invented to fill the
12
+ * gap.
13
+ *
14
+ * @module
15
+ */
16
+
17
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+ import { findProjectFile, readUproject } from './engine.js'
20
+
21
+ /** Files per module before the scan stops counting (a safety bound, not a total). */
22
+ const MODULE_FILE_CAP = 5000
23
+
24
+ /** `.uplugin` files visited below the project's plugins directory. */
25
+ const PLUGIN_SCAN_CAP = 500
26
+
27
+ /** Depth below `Plugins/` that is searched for `.uplugin` files. */
28
+ const PLUGIN_SCAN_DEPTH = 6
29
+
30
+ /**
31
+ * Count source files below a directory, bounded.
32
+ *
33
+ * @param {string} directory
34
+ * @returns {{ files: number, truncated: boolean }}
35
+ */
36
+ function countSourceFiles(directory) {
37
+ let files = 0
38
+ const stack = [{ path: directory, depth: 0 }]
39
+ while (stack.length > 0) {
40
+ const current = stack.pop()
41
+ if (!current) continue
42
+ let entries
43
+ try {
44
+ entries = readdirSync(current.path, { withFileTypes: true })
45
+ } catch {
46
+ continue
47
+ }
48
+ for (const entry of entries) {
49
+ if (entry.isDirectory()) {
50
+ if (current.depth < PLUGIN_SCAN_DEPTH) stack.push({ path: join(current.path, entry.name), depth: current.depth + 1 })
51
+ continue
52
+ }
53
+ if (!entry.isFile()) continue
54
+ if (entry.name.endsWith('.h') || entry.name.endsWith('.cpp') || entry.name.endsWith('.cs')) {
55
+ files += 1
56
+ if (files >= MODULE_FILE_CAP) return { files, truncated: true }
57
+ }
58
+ }
59
+ }
60
+ return { files, truncated: false }
61
+ }
62
+
63
+ /**
64
+ * Count plugin descriptors below `Plugins/`, bounded.
65
+ *
66
+ * @param {string} directory
67
+ */
68
+ function scanPlugins(directory) {
69
+ /** @type {string[]} */
70
+ const names = []
71
+ let truncated = false
72
+ const stack = [{ path: directory, depth: 0 }]
73
+ while (stack.length > 0) {
74
+ const current = stack.pop()
75
+ if (!current) continue
76
+ let entries
77
+ try {
78
+ entries = readdirSync(current.path, { withFileTypes: true })
79
+ } catch {
80
+ continue
81
+ }
82
+ for (const entry of entries) {
83
+ if (entry.isDirectory()) {
84
+ if (current.depth < PLUGIN_SCAN_DEPTH) {
85
+ stack.push({ path: join(current.path, entry.name), depth: current.depth + 1 })
86
+ }
87
+ continue
88
+ }
89
+ if (!entry.isFile() || !entry.name.endsWith('.uplugin')) continue
90
+ names.push(entry.name.replace(/\.uplugin$/, ''))
91
+ if (names.length >= PLUGIN_SCAN_CAP) {
92
+ truncated = true
93
+ return { count: names.length, names, truncated }
94
+ }
95
+ }
96
+ }
97
+ return { count: names.length, names, truncated }
98
+ }
99
+
100
+ /**
101
+ * Split Monolith's `level_index_state` into a state and its detail.
102
+ *
103
+ * @param {unknown} value
104
+ */
105
+ function readIndexHealth(value) {
106
+ if (typeof value !== 'string' || value === '') return null
107
+ const separator = value.indexOf(':')
108
+ if (separator === -1) return { state: value, detail: '' }
109
+ return { state: value.slice(0, separator).trim(), detail: value.slice(separator + 1).trim() }
110
+ }
111
+
112
+ /**
113
+ * Collect the inventory of one project directory.
114
+ *
115
+ * @param {{
116
+ * directory: string,
117
+ * client: ReturnType<import('./monolith.js').createMonolithClient>,
118
+ * }} input
119
+ */
120
+ export async function inspectProject(input) {
121
+ const directory = input.directory
122
+ const file = findProjectFile(directory)
123
+ if (!file) {
124
+ throw new Error(`no .uproject file found in ${directory}`)
125
+ }
126
+ const project = readUproject(file)
127
+
128
+ const sourceRoot = join(directory, 'Source')
129
+ const modules = project.modules.map((module) => {
130
+ // Unreal accepts two source layouts: one directory per module
131
+ // (Source/<Module>/) or the module's files flat in Source/ (Source/<Module>.cpp …).
132
+ const moduleDirectory = join(sourceRoot, module.name)
133
+ if (existsSync(moduleDirectory)) {
134
+ const counted = countSourceFiles(moduleDirectory)
135
+ return {
136
+ name: module.name,
137
+ type: module.type,
138
+ loadingPhase: module.loadingPhase,
139
+ sourceDirectory: moduleDirectory,
140
+ sourceLayout: 'directory',
141
+ sourceFiles: counted.files,
142
+ sourceFilesTruncated: counted.truncated,
143
+ }
144
+ }
145
+ let files = 0
146
+ for (const extension of ['.h', '.cpp', '.cs', '.Build.cs']) {
147
+ if (existsSync(join(sourceRoot, `${module.name}${extension}`))) files += 1
148
+ }
149
+ const flat = files > 0
150
+ return {
151
+ name: module.name,
152
+ type: module.type,
153
+ loadingPhase: module.loadingPhase,
154
+ sourceDirectory: flat ? sourceRoot : null,
155
+ sourceLayout: flat ? 'flat' : null,
156
+ sourceFiles: files,
157
+ sourceFilesTruncated: false,
158
+ }
159
+ })
160
+
161
+ const pluginsDirectory = join(directory, 'Plugins')
162
+ const onDisk = existsSync(pluginsDirectory) ? scanPlugins(pluginsDirectory) : { count: 0, names: [], truncated: false }
163
+ const declared = project.plugins
164
+ const declaredNames = new Set(declared.map((plugin) => plugin.name))
165
+ const unlistedOnDisk = onDisk.names.filter((name) => !declaredNames.has(name))
166
+
167
+ /** @type {{ connected: boolean, projectName: string | null, engineVersion: string | null, serverVersion: string | null, actions: number | null, error: { code: string, message: string } | null }} */
168
+ let editor = {
169
+ connected: false,
170
+ projectName: null,
171
+ engineVersion: null,
172
+ serverVersion: null,
173
+ actions: null,
174
+ error: null,
175
+ }
176
+ /** @type {Record<string, number> | null} */
177
+ let index = null
178
+ /** @type {{ state: string, detail: string } | null} */
179
+ let indexHealth = null
180
+
181
+ try {
182
+ const status = await input.client.status()
183
+ editor = {
184
+ connected: true,
185
+ projectName: typeof status?.project_name === 'string' ? status.project_name : null,
186
+ engineVersion: typeof status?.engine_version === 'string' ? status.engine_version : null,
187
+ serverVersion: typeof status?.version === 'string' ? status.version : null,
188
+ actions: typeof status?.total_actions === 'number' ? status.total_actions : null,
189
+ error: null,
190
+ }
191
+ const stats = await input.client.callReadOnly('project_query', { action: 'get_stats', params: {} })
192
+ const values = stats?.stats
193
+ if (values && typeof values === 'object') {
194
+ index = {}
195
+ for (const [key, value] of Object.entries(values)) {
196
+ if (typeof value === 'number') index[key] = value
197
+ if (key === 'level_index_state') indexHealth = readIndexHealth(value)
198
+ }
199
+ }
200
+ } catch (error) {
201
+ editor.error = {
202
+ code: error?.code ?? 'error',
203
+ message: error instanceof Error ? error.message : String(error),
204
+ }
205
+ index = null
206
+ indexHealth = null
207
+ }
208
+
209
+ return {
210
+ directory,
211
+ project: {
212
+ file: project.file,
213
+ name: (project.file.split(/[\\/]/).pop() ?? '').replace(/\.uproject$/i, ''),
214
+ engineAssociation: project.engineAssociation,
215
+ description: project.description,
216
+ modules,
217
+ },
218
+ plugins: {
219
+ declared,
220
+ onDisk: { count: onDisk.count, truncated: onDisk.truncated, unlisted: unlistedOnDisk },
221
+ },
222
+ editor,
223
+ index,
224
+ indexHealth,
225
+ provenance: {
226
+ modules: 'uproject + Source/',
227
+ plugins: 'uproject + Plugins/*.uplugin',
228
+ contentCounts: editor.connected ? 'monolith index' : null,
229
+ editor: editor.connected ? 'monolith server' : null,
230
+ },
231
+ readOnly: true,
232
+ }
233
+ }
234
+
235
+ /** Re-exported for callers that only need to know whether a path is a directory. */
236
+ export function directoryExists(path) {
237
+ try {
238
+ return statSync(path).isDirectory()
239
+ } catch {
240
+ return false
241
+ }
242
+ }
243
+
244
+ /** Read the `.uproject` text directly (used by tests and callers that verify parsing). */
245
+ export function readProjectText(file) {
246
+ return readFileSync(file, 'utf8')
247
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-unreal-python-api",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "type": "module",
5
5
  "description": "Unreal Engine Python API context for DSH agents: symbol inventory listing, symbol search, exact syntax from the Epic docs, and tool scaffolding in four styles (ToolsetRegistry toolset, editor script, MCP tool descriptors, DSH defineTool module).",
6
6
  "license": "MIT",
package/test/smoke.mjs CHANGED
@@ -10,6 +10,8 @@ import assert from 'node:assert/strict'
10
10
  import { listChildren, loadInventory, pageUrl, resolveCacheDir, searchSymbols, summarize } from '../lib/inventory.js'
11
11
  import { readSymbolDoc } from '../lib/docs.js'
12
12
  import { buildToolset } from '../lib/builder.js'
13
+ import { detectEngine } from '../lib/engine.js'
14
+ import { inspectProject } from '../lib/project.js'
13
15
  import { execFileSync } from 'node:child_process'
14
16
  import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
15
17
  import { tmpdir } from 'node:os'
@@ -341,13 +343,24 @@ function fakeContext(directoryOf) {
341
343
 
342
344
  const openContext = fakeContext(() => TDA)
343
345
  plugin.apply(openContext, plugin.Config({}))
344
- assert.equal(openContext.registered.length, 4, 'default scope registers four tools')
346
+ assert.equal(openContext.registered.length, 6, 'default scope registers six tools')
347
+ const registeredNames = openContext.registered.map((entry) => entry.definition.name)
348
+ for (const expected of [
349
+ 'unreal_python_tools_list',
350
+ 'unreal_python_search',
351
+ 'unreal_python_syntax',
352
+ 'unreal_python_tool_builder',
353
+ 'unreal_engine_detect',
354
+ 'unreal_project_inspect',
355
+ ]) {
356
+ assert.ok(registeredNames.includes(expected), `${expected} is registered`)
357
+ }
345
358
  assert.ok(openContext.registered.every((entry) => entry.options.when === undefined), 'default scope attaches no condition')
346
359
  assert.equal(openContext.sections.length, 1, 'default scope registers one prompt section')
347
360
 
348
361
  const scopedContext = fakeContext((session) => (session.id === 'inside' ? join(TDA, 'Source') : 'D:\\elsewhere'))
349
362
  plugin.apply(scopedContext, plugin.Config({ scope: 'workspaces', workspaces: [TDA] }))
350
- assert.equal(scopedContext.registered.length, 4, 'a scoped install still registers four tools')
363
+ assert.equal(scopedContext.registered.length, 6, 'a scoped install still registers six tools')
351
364
  const gated = scopedContext.registered.filter((entry) => typeof entry.options.when === 'function')
352
365
  assert.equal(gated.length, 1, 'only the development tier is gated')
353
366
  assert.equal(gated[0].definition.name, 'unreal_python_tool_builder', 'the development tier is the tool builder')
@@ -355,7 +368,17 @@ const general = scopedContext.registered
355
368
  .filter((entry) => entry.options.when === undefined)
356
369
  .map((entry) => entry.definition.name)
357
370
  .sort()
358
- assert.deepEqual(general, ['unreal_python_search', 'unreal_python_syntax', 'unreal_python_tools_list'], 'the general tier carries no condition')
371
+ assert.deepEqual(
372
+ general,
373
+ [
374
+ 'unreal_engine_detect',
375
+ 'unreal_project_inspect',
376
+ 'unreal_python_search',
377
+ 'unreal_python_syntax',
378
+ 'unreal_python_tools_list',
379
+ ],
380
+ 'the general tier carries no condition',
381
+ )
359
382
  const condition = gated[0].options.when
360
383
  assert.equal(await condition({ agent: { session: { id: 'inside' } } }), true, 'the condition admits the configured workspace')
361
384
  assert.equal(await condition({ agent: { session: { id: 'outside' } } }), false, 'the condition rejects another workspace')
@@ -363,6 +386,117 @@ assert.match(scopedContext.sections[0].text, /admitted only inside/, 'the prompt
363
386
  console.log('apply(): general tier always on, development tier scoped: OK')
364
387
  }
365
388
 
389
+ // --- engine detection and project inspection, without a running editor --------
390
+ const fixture = mkdtempSync(join(tmpdir(), 'unreal-engine-detect-'))
391
+ const engineRoot = join(fixture, 'UE_5.4')
392
+ mkdirSync(join(engineRoot, 'Engine', 'Build'), { recursive: true })
393
+ writeFileSync(
394
+ join(engineRoot, 'Engine', 'Build', 'Build.version'),
395
+ JSON.stringify({ MajorVersion: 5, MinorVersion: 4, PatchVersion: 4, Changelist: 35576357, BranchName: '++UE5+Release-5.4' }),
396
+ )
397
+ const launcherManifest = join(fixture, 'LauncherInstalled.dat')
398
+ writeFileSync(
399
+ launcherManifest,
400
+ JSON.stringify({ InstallationList: [{ InstallLocation: engineRoot, AppName: 'UE_5.4', AppVersion: '5.4.4-35576357' }] }),
401
+ )
402
+ const projectDir = join(fixture, 'ShopifyApp')
403
+ mkdirSync(join(projectDir, 'Source', 'ShopifyApp'), { recursive: true })
404
+ writeFileSync(
405
+ join(projectDir, 'ShopifyApp.uproject'),
406
+ JSON.stringify({
407
+ FileVersion: 3,
408
+ EngineAssociation: '5.4',
409
+ Modules: [{ Name: 'ShopifyApp', Type: 'Runtime' }],
410
+ Plugins: [{ Name: 'PythonScriptPlugin' }, { Name: 'DisabledThing', Enabled: false }],
411
+ }),
412
+ )
413
+ writeFileSync(join(projectDir, 'Source', 'ShopifyApp', 'ShopifyApp.h'), '// header\n')
414
+ writeFileSync(join(projectDir, 'Source', 'ShopifyApp', 'ShopifyApp.cpp'), '// source\n')
415
+ mkdirSync(join(projectDir, 'Plugins', 'LocalThing'), { recursive: true })
416
+ writeFileSync(join(projectDir, 'Plugins', 'LocalThing', 'LocalThing.uplugin'), '{}')
417
+
418
+ /** A Monolith client that cannot connect: every call reports the connection error. */
419
+ function offlineClient() {
420
+ const refuse = async () => {
421
+ throw Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:9316'), { code: 'disconnected' })
422
+ }
423
+ return { status: refuse, callTool: refuse, callReadOnly: refuse }
424
+ }
425
+
426
+ const detected = await detectEngine({
427
+ directory: projectDir,
428
+ engines: { '5.4': engineRoot },
429
+ launcherManifestPath: launcherManifest,
430
+ client: offlineClient(),
431
+ docBaseUrl: DOC_BASE_URL,
432
+ })
433
+ assert.equal(detected.project.engineAssociation, '5.4', 'the association is reported as written in the .uproject')
434
+ assert.equal(detected.installation.path, engineRoot, 'the installation resolves from the launcher manifest entry')
435
+ assert.ok(/^5\.4/.test(detected.installation.build.version), `the installation build version is read, saw ${detected.installation.build.version}`)
436
+ assert.equal(detected.editor.connected, false, 'an unreachable editor is reported, not invented')
437
+ assert.equal(detected.editor.error.code, 'disconnected', 'the connection error is preserved')
438
+ assert.equal(detected.documentation.status, 'unavailable_for_version', 'a 5.4 project has no published Python API inventory')
439
+ assert.ok(detected.documentation.note.includes('5.8'), 'the note names the version that does have documentation')
440
+ assert.deepEqual(detected.conflicts, [], 'agreeing sources report no conflict')
441
+ console.log(' engine: 5.4 project, 5.4 installation, editor unreachable, documentation unavailable_for_version: OK')
442
+
443
+ const conflicted = await detectEngine({
444
+ directory: projectDir,
445
+ engines: { '5.4': engineRoot },
446
+ launcherManifestPath: launcherManifest,
447
+ client: { status: async () => ({ engine_version: '++UE5+Release-5.8-CL-58902052', project_name: 'ShopifyApp', version: '0.25.0', total_actions: 1570 }) },
448
+ docBaseUrl: DOC_BASE_URL,
449
+ })
450
+ assert.ok(conflicted.conflicts.length > 0, 'a 5.4 project with a 5.8 editor reports a conflict')
451
+ assert.equal(conflicted.editor.version, '5.8', 'the editor keeps its own version value')
452
+ assert.ok(/^5\.4/.test(conflicted.installation.build.version), 'the installation keeps its own version value')
453
+ console.log(` engine conflict reported: ${conflicted.conflicts.join(' | ')}`)
454
+
455
+ const inspected = await inspectProject({ directory: projectDir, client: offlineClient() })
456
+ assert.equal(inspected.project.modules[0].name, 'ShopifyApp', 'the declared module is reported')
457
+ assert.equal(inspected.project.modules[0].sourceFiles, 2, 'the module source files are counted')
458
+ assert.equal(inspected.project.modules[0].sourceLayout, 'directory', 'the per-module directory layout is reported')
459
+ assert.equal(inspected.project.modules[0].sourceDirectory, join(projectDir, 'Source', 'ShopifyApp'), 'the module source directory is reported')
460
+ assert.equal(inspected.plugins.onDisk.count, 1, 'the local plugin descriptor is found')
461
+ assert.deepEqual(inspected.plugins.onDisk.unlisted, ['LocalThing'], 'a plugin on disk that the .uproject does not declare is reported')
462
+ assert.equal(inspected.editor.connected, false, 'the editor half reports the connection error')
463
+ assert.equal(inspected.index, null, 'no indexed counts are reported without an editor')
464
+ assert.equal(inspected.readOnly, true, 'the inventory is read-only')
465
+ console.log(' project: declared modules/plugins counted, no indexed counts without an editor: OK')
466
+
467
+ const fakeEditor = {
468
+ status: async () => ({
469
+ project_name: 'ShopifyApp',
470
+ engine_version: '++UE5+Release-5.8-CL-58902052',
471
+ version: '0.25.0',
472
+ total_actions: 1570,
473
+ }),
474
+ callReadOnly: async () => ({
475
+ success: true,
476
+ stats: { assets: 12, nodes: 34, tags: 5, level_index_state: 'degraded: processed 1/2 levels' },
477
+ }),
478
+ }
479
+ const indexed = await inspectProject({ directory: projectDir, client: fakeEditor })
480
+ assert.equal(indexed.index.assets, 12, 'indexed asset count comes from Monolith')
481
+ assert.equal(indexed.index.tags, 5, 'indexed tag count comes from Monolith')
482
+ assert.deepEqual(indexed.indexHealth, { state: 'degraded', detail: 'processed 1/2 levels' }, 'the index health degrades verbatim')
483
+ assert.equal(indexed.provenance.contentCounts, 'monolith index', 'the indexed half is labelled with its provenance')
484
+ console.log(' project: indexed counts and health separated from declared facts: OK')
485
+
486
+ // A module may also live flat in Source/ (Source/<Module>.cpp), which is how TDA
487
+ // itself is laid out; the count must follow the layout the project uses.
488
+ const flatProject = join(fixture, 'FlatProject')
489
+ mkdirSync(join(flatProject, 'Source'), { recursive: true })
490
+ writeFileSync(join(flatProject, 'FlatProject.uproject'), JSON.stringify({ FileVersion: 3, EngineAssociation: '5.8', Modules: [{ Name: 'FlatProject', Type: 'Runtime' }] }))
491
+ writeFileSync(join(flatProject, 'Source', 'FlatProject.cpp'), '// source\n')
492
+ writeFileSync(join(flatProject, 'Source', 'FlatProject.h'), '// header\n')
493
+ writeFileSync(join(flatProject, 'Source', 'FlatProject.Build.cs'), '// build\n')
494
+ const flatInspected = await inspectProject({ directory: flatProject, client: offlineClient() })
495
+ assert.equal(flatInspected.project.modules[0].sourceLayout, 'flat', 'a flat Source/ layout is detected')
496
+ assert.equal(flatInspected.project.modules[0].sourceFiles, 3, 'flat module files are counted')
497
+ assert.equal(flatInspected.project.modules[0].sourceDirectory, join(flatProject, 'Source'), 'the flat layout reports the Source directory')
498
+ console.log(' project: flat Source/ layout counted too: OK')
499
+
366
500
  // --- every generated artifact must parse in its own language -------------------
367
501
  console.log('parse checks:')
368
502
  assertParses('toolset module', built.code, 'py')