dsh-unreal-python-api 0.0.0-stage → 1.1.1

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/index.js ADDED
@@ -0,0 +1,538 @@
1
+ /**
2
+ * Unreal Engine Python API context for agents.
3
+ *
4
+ * Publishes the documented Unreal Python 5.8 surface as four tools — list,
5
+ * search, syntax, and tool builder — backed by the symbol inventory Epic
6
+ * publishes beside the Python API documentation. Nothing here guesses at an
7
+ * API: a symbol that is not in the inventory is reported as unresolved.
8
+ *
9
+ * @module dsh-unreal-python-api
10
+ */
11
+
12
+ import z from '@deepseek-ai/schemastery'
13
+ import { defineTool } from '@deepseek-ai/dsh-tools'
14
+ import {
15
+ DEFAULT_DOC_BASE_URL,
16
+ friendlyKind,
17
+ listChildren,
18
+ loadInventory,
19
+ pageUrl,
20
+ resolveCacheDir,
21
+ searchSymbols,
22
+ summarize,
23
+ } from './lib/inventory.js'
24
+ import { readSymbolDoc } from './lib/docs.js'
25
+ import { DEFAULT_REGISTRY_IMPORT, buildToolset } from './lib/builder.js'
26
+ import {
27
+ DEFAULT_PROJECT_MARKERS,
28
+ DEFAULT_SCOPE,
29
+ createScopeGate,
30
+ describeScope,
31
+ resolveScope,
32
+ } from './lib/scope.js'
33
+
34
+ export const name = 'unreal-python-api'
35
+
36
+ export const inject = ['tools', 'systemPrompt', 'workingDirectory']
37
+
38
+ export const Config = z.object({
39
+ docBaseUrl: z.string().default(DEFAULT_DOC_BASE_URL),
40
+ cacheDir: z.string().default(''),
41
+ refreshHours: z.number().default(24),
42
+ maxResults: z.number().default(30),
43
+ fetchTimeoutMs: z.number().default(30_000),
44
+ promptSection: z.boolean().default(true),
45
+ scope: z.string().default(DEFAULT_SCOPE),
46
+ workspaces: z.array(z.string()).default([]),
47
+ projectMarkers: z.array(z.string()).default(DEFAULT_PROJECT_MARKERS),
48
+ })
49
+
50
+ /** Largest row count any tool returns, whatever a caller asks for. */
51
+ const ROW_CEILING = 200
52
+
53
+ /**
54
+ * Resolve a requested row cap.
55
+ * @param {number | undefined} requested Caller value.
56
+ * @param {number} fallback Configured default.
57
+ * @returns {number} Effective row cap.
58
+ */
59
+ function clampLimit(requested, fallback) {
60
+ if (requested === undefined || requested === null) return fallback
61
+ const value = Math.floor(Number(requested))
62
+ if (!Number.isFinite(value) || value < 1) throw new Error('limit must be a positive number')
63
+ return Math.min(value, ROW_CEILING)
64
+ }
65
+
66
+ /**
67
+ * Translate the single-tool shortcut (`tool_name` and friends) into the `tools`
68
+ * array `buildToolset` takes.
69
+ * @param {object} args Validated tool arguments.
70
+ * @returns {object[]} One tool description, or an empty list when neither form was used.
71
+ */
72
+ function singleTool(args) {
73
+ if (args.tool_name === undefined) return []
74
+ if (typeof args.tool_description !== 'string' || args.tool_description.trim() === '') {
75
+ throw new Error('tool_description is required when tool_name is set')
76
+ }
77
+ return [
78
+ {
79
+ name: args.tool_name,
80
+ description: args.tool_description,
81
+ parameters: args.tool_parameters,
82
+ returns: args.tool_returns,
83
+ symbols: args.tool_symbols,
84
+ },
85
+ ]
86
+ }
87
+
88
+ /** Build a fresh symbol-row schema. @returns {object} Row schema. */
89
+ function rowSchema() {
90
+ return {
91
+ type: 'object',
92
+ additionalProperties: false,
93
+ properties: {
94
+ name: { type: 'string', required: true },
95
+ kind: { type: 'string', required: true },
96
+ url: { type: 'string', required: true },
97
+ },
98
+ }
99
+ }
100
+
101
+ /** Build a fresh kind-count schema. @returns {object} Count schema. */
102
+ function countSchema() {
103
+ return {
104
+ type: 'object',
105
+ additionalProperties: false,
106
+ properties: {
107
+ kind: { type: 'string', required: true },
108
+ count: { type: 'number', required: true },
109
+ },
110
+ }
111
+ }
112
+
113
+ /**
114
+ * Render symbol rows as compact lines.
115
+ * @param {string} header First line.
116
+ * @param {Array<{name: string, kind: string, url: string}>} rows Symbol rows.
117
+ * @param {string} [footer] Closing line.
118
+ * @returns {string} Rendered text.
119
+ */
120
+ function renderRows(header, rows, footer) {
121
+ const lines = [header]
122
+ for (const row of rows) lines.push(` ${row.name} [${row.kind}] ${row.url}`)
123
+ if (footer) lines.push(footer)
124
+ return lines.join('\n')
125
+ }
126
+
127
+ /**
128
+ * Register the Unreal Python API tools.
129
+ * @param {object} ctx Plugin context.
130
+ * @param {object} config Resolved plugin configuration.
131
+ * @returns {void}
132
+ */
133
+ export function apply(ctx, config) {
134
+ const docBaseUrl = String(config.docBaseUrl ?? DEFAULT_DOC_BASE_URL)
135
+ if (!/^https?:\/\//.test(docBaseUrl)) throw new Error('docBaseUrl must be an http(s) URL')
136
+ const cacheDir = resolveCacheDir(config.cacheDir)
137
+ const maxResults = config.maxResults
138
+ const fetchTimeoutMs = config.fetchTimeoutMs
139
+ const refreshHours = config.refreshHours
140
+ if (!Number.isFinite(maxResults) || maxResults < 1) throw new Error('maxResults must be a positive number')
141
+ if (!Number.isFinite(fetchTimeoutMs) || fetchTimeoutMs < 1_000) throw new Error('fetchTimeoutMs must be at least 1000')
142
+ if (!Number.isFinite(refreshHours) || refreshHours < 0) throw new Error('refreshHours must not be negative')
143
+
144
+ const scope = resolveScope({
145
+ scope: config.scope,
146
+ workspaces: config.workspaces,
147
+ projectMarkers: config.projectMarkers,
148
+ })
149
+ const gate = createScopeGate({
150
+ resolved: scope,
151
+ directoryOf: (agent) => {
152
+ try {
153
+ return ctx.workingDirectory.get(agent.session)
154
+ } catch {
155
+ return undefined
156
+ }
157
+ },
158
+ })
159
+ // A scope condition must never fail step preparation, so only a non-default
160
+ // scope attaches one; the default registers exactly as before.
161
+ const register =
162
+ scope.scope === 'anywhere'
163
+ ? (definition) => ctx.tools.register(definition)
164
+ : (definition) => ctx.tools.register(definition, { when: (context) => gate.admits(context.agent) })
165
+
166
+ let loaded = null
167
+ /**
168
+ * Load the inventory once per process, re-reading it when a caller asks to refresh.
169
+ * @param {boolean} refresh Force a download.
170
+ * @returns {Promise<object>} Loaded inventory.
171
+ */
172
+ function inventory(refresh) {
173
+ if (refresh === true) loaded = null
174
+ if (loaded === null) {
175
+ loaded = loadInventory({
176
+ docBaseUrl,
177
+ cacheDir,
178
+ refreshHours: refresh === true ? 0 : refreshHours,
179
+ timeoutMs: fetchTimeoutMs,
180
+ }).catch((error) => {
181
+ loaded = null
182
+ throw error
183
+ })
184
+ }
185
+ return loaded
186
+ }
187
+
188
+ register(defineTool({
189
+ name: 'unreal_python_tools_list',
190
+ description: 'List Unreal Engine Python API symbols. Without a parent it reports how many symbols the published documentation holds and their kinds; with a parent such as unreal.Actor it lists that namespace or class direct members.',
191
+ parameters: {
192
+ parent: { type: 'string', description: 'Dotted symbol whose direct members to list, for example unreal.EditorAssetLibrary.' },
193
+ kind: { type: 'string', description: 'Restrict rows to class, method, property, attribute, function, doc, or label.' },
194
+ limit: { type: 'number', description: 'Row cap; defaults to the configured result limit.' },
195
+ refresh: { type: 'boolean', description: 'Download the symbol inventory again instead of using the cached copy.' },
196
+ },
197
+ output: {
198
+ schema: {
199
+ type: 'object',
200
+ additionalProperties: false,
201
+ properties: {
202
+ apiVersion: { type: 'string', required: true },
203
+ source: { type: 'string', required: true },
204
+ total: { type: 'number', required: true },
205
+ shown: { type: 'number', required: true },
206
+ truncated: { type: 'boolean', required: true },
207
+ counts: { type: 'array', required: true, items: countSchema() },
208
+ rows: { type: 'array', required: true, items: rowSchema() },
209
+ parent: { type: 'string' },
210
+ hint: { type: 'string' },
211
+ },
212
+ },
213
+ render: (_args, value) => {
214
+ const counts = value.counts.map((entry) => `${entry.kind} ${entry.count}`).join(', ')
215
+ const header = `Unreal Python ${value.apiVersion} API: ${value.total} symbols, inventory from ${value.source}\nkinds: ${counts}`
216
+ if (value.rows.length === 0) return [{ type: 'text', text: `${header}\n${value.hint ?? ''}`.trim() }]
217
+ const footer = `${value.shown} of ${value.total} direct members of ${value.parent}${value.truncated ? ' (truncated)' : ''}`
218
+ return [{ type: 'text', text: renderRows(header, value.rows, footer) }]
219
+ },
220
+ },
221
+ timeoutMs: fetchTimeoutMs + 5_000,
222
+ async execute(args) {
223
+ const limit = clampLimit(args.limit, maxResults)
224
+ const current = await inventory(args.refresh === true)
225
+ const counts = summarize(current.inventory)
226
+ const parent = args.parent === undefined ? '' : String(args.parent).trim()
227
+ if (parent === '') {
228
+ return {
229
+ apiVersion: current.version,
230
+ source: current.source,
231
+ total: current.inventory.names.length,
232
+ shown: 0,
233
+ truncated: false,
234
+ counts,
235
+ rows: [],
236
+ hint: "Pass parent (for example unreal.EditorAssetLibrary or unreal.Actor) to list direct members; use unreal_python_search to find symbols by name.",
237
+ }
238
+ }
239
+ const listing = listChildren(current.inventory, { parent, kind: args.kind, limit })
240
+ return {
241
+ apiVersion: current.version,
242
+ source: current.source,
243
+ total: listing.total,
244
+ shown: listing.rows.length,
245
+ truncated: listing.truncated,
246
+ counts: listing.counts,
247
+ rows: listing.rows,
248
+ parent,
249
+ }
250
+ },
251
+ }))
252
+
253
+ register(defineTool({
254
+ name: 'unreal_python_search',
255
+ description: 'Search Unreal Python API symbol names. Ranks an exact name first, then a member name that starts with the query, then any containing name, and returns each match with its documentation URL.',
256
+ parameters: {
257
+ query: { type: 'string', required: true, description: 'Symbol text to find, for example save_asset or unreal.Actor.' },
258
+ kind: { type: 'string', description: 'Restrict matches to class, method, property, attribute, function, doc, or label.' },
259
+ parent: { type: 'string', description: 'Restrict matches to members of this dotted symbol.' },
260
+ limit: { type: 'number', description: 'Match cap; defaults to the configured result limit.' },
261
+ },
262
+ output: {
263
+ schema: {
264
+ type: 'object',
265
+ additionalProperties: false,
266
+ properties: {
267
+ apiVersion: { type: 'string', required: true },
268
+ query: { type: 'string', required: true },
269
+ total: { type: 'number', required: true },
270
+ shown: { type: 'number', required: true },
271
+ truncated: { type: 'boolean', required: true },
272
+ rows: { type: 'array', required: true, items: rowSchema() },
273
+ },
274
+ },
275
+ render: (_args, value) => {
276
+ if (value.rows.length === 0) {
277
+ return [{ type: 'text', text: `No Unreal Python ${value.apiVersion} symbol matches "${value.query}". Try a shorter query, or unreal_python_tools_list for the documented namespaces.` }]
278
+ }
279
+ const header = `${value.total} symbols match "${value.query}" in the Unreal Python ${value.apiVersion} API; showing ${value.shown}${value.truncated ? ' (truncated)' : ''}`
280
+ return [{ type: 'text', text: renderRows(header, value.rows) }]
281
+ },
282
+ },
283
+ timeoutMs: fetchTimeoutMs + 5_000,
284
+ async execute(args) {
285
+ const limit = clampLimit(args.limit, maxResults)
286
+ const current = await inventory(false)
287
+ const result = searchSymbols(current.inventory, {
288
+ query: args.query,
289
+ kind: args.kind,
290
+ parent: args.parent,
291
+ limit,
292
+ })
293
+ return {
294
+ apiVersion: current.version,
295
+ query: String(args.query).trim(),
296
+ total: result.total,
297
+ shown: result.matches.length,
298
+ truncated: result.truncated,
299
+ rows: result.matches,
300
+ }
301
+ },
302
+ }))
303
+
304
+ register(defineTool({
305
+ name: 'unreal_python_syntax',
306
+ description: 'Return the exact documented syntax of Unreal Python symbols: signature, description, parameters, and return value, read from the published documentation page that carries the symbol.',
307
+ parameters: {
308
+ symbols: {
309
+ type: 'array',
310
+ required: true,
311
+ items: { type: 'string' },
312
+ description: 'Dotted symbol names, for example unreal.Actor.set_actor_scale3d.',
313
+ },
314
+ },
315
+ output: {
316
+ schema: {
317
+ type: 'object',
318
+ additionalProperties: false,
319
+ properties: {
320
+ apiVersion: { type: 'string', required: true },
321
+ entries: {
322
+ type: 'array',
323
+ required: true,
324
+ items: {
325
+ type: 'object',
326
+ additionalProperties: false,
327
+ properties: {
328
+ symbol: { type: 'string', required: true },
329
+ kind: { type: 'string', required: true },
330
+ url: { type: 'string', required: true },
331
+ resolved: { type: 'boolean', required: true },
332
+ signature: { type: 'string', required: true },
333
+ description: { type: 'string', required: true },
334
+ parameters: {
335
+ type: 'array',
336
+ required: true,
337
+ items: {
338
+ type: 'object',
339
+ additionalProperties: false,
340
+ properties: {
341
+ name: { type: 'string', required: true },
342
+ text: { type: 'string', required: true },
343
+ },
344
+ },
345
+ },
346
+ returns: { type: 'string', required: true },
347
+ note: { type: 'string', required: true },
348
+ },
349
+ },
350
+ },
351
+ unresolved: {
352
+ type: 'array',
353
+ required: true,
354
+ items: {
355
+ type: 'object',
356
+ additionalProperties: false,
357
+ properties: {
358
+ symbol: { type: 'string', required: true },
359
+ reason: { type: 'string', required: true },
360
+ },
361
+ },
362
+ },
363
+ },
364
+ },
365
+ render: (_args, value) => {
366
+ const blocks = []
367
+ for (const entry of value.entries) {
368
+ const lines = [`${entry.symbol} [${entry.kind}]`]
369
+ lines.push(` signature: ${entry.signature === '' ? '(not on the page)' : entry.signature}`)
370
+ if (entry.description !== '') lines.push(` summary: ${entry.description}`)
371
+ for (const parameter of entry.parameters) {
372
+ lines.push(` param: ${parameter.name === '' ? parameter.text : `${parameter.name} - ${parameter.text}`}`)
373
+ }
374
+ if (entry.returns !== '') lines.push(` returns: ${entry.returns}`)
375
+ lines.push(` docs: ${entry.url}`)
376
+ if (entry.resolved === false) lines.push(` note: ${entry.note}`)
377
+ blocks.push(lines.join('\n'))
378
+ }
379
+ for (const missing of value.unresolved) {
380
+ blocks.push(`${missing.symbol}: unresolved - ${missing.reason}`)
381
+ }
382
+ return [{ type: 'text', text: `Unreal Python ${value.apiVersion} API\n\n${blocks.join('\n\n')}` }]
383
+ },
384
+ },
385
+ timeoutMs: fetchTimeoutMs + 10_000,
386
+ async execute(args) {
387
+ const current = await inventory(false)
388
+ const { inventory: api } = current
389
+ const requested = [...new Set((args.symbols ?? []).map((symbol) => String(symbol).trim()).filter((symbol) => symbol !== ''))]
390
+ if (requested.length === 0) throw new Error('symbols must contain at least one symbol name')
391
+ const entries = []
392
+ const unresolved = []
393
+ const reads = requested.map(async (symbol) => {
394
+ const position = api.index.get(symbol)
395
+ if (position === undefined) {
396
+ unresolved.push({ symbol, reason: `not in the Unreal Python ${current.version} inventory` })
397
+ return null
398
+ }
399
+ return readSymbolDoc({
400
+ docBaseUrl,
401
+ symbol,
402
+ uri: api.uris[position],
403
+ kind: friendlyKind(api.kinds[position]),
404
+ timeoutMs: fetchTimeoutMs,
405
+ })
406
+ })
407
+ for (const read of await Promise.all(reads)) if (read !== null) entries.push(read)
408
+ return { apiVersion: current.version, entries, unresolved }
409
+ },
410
+ }))
411
+
412
+ register(defineTool({
413
+ name: 'unreal_python_tool_builder',
414
+ description: 'Scaffold an Unreal Python tool from a description plus verified API symbols. Styles: toolset (a ToolsetRegistry toolset class with its test module), editor_script (a plain editor script), mcp_tool (MCP tool descriptors in JSON plus the Python handler module that serves them), and dsh_tool (a DSH plugin tool module whose definitions register through defineTool, with a Node test module). Every Unreal API symbol the tool asks for is verified against the published inventory and recorded with its documentation URL; unverified symbols are reported instead of written into the code.',
415
+ parameters: {
416
+ toolset_name: { type: 'string', required: true, description: 'Class name for the toolset, for example TerritoryTools.' },
417
+ description: { type: 'string', required: true, description: 'What the toolset does; becomes its docstring.' },
418
+ tools: {
419
+ type: 'array',
420
+ description: 'Tools to scaffold. Omit it to describe a single tool with the tool_name fields below.',
421
+ items: {
422
+ type: 'object',
423
+ additionalProperties: false,
424
+ properties: {
425
+ name: { type: 'string', required: true, description: 'Tool function name, for example save_dirty_assets.' },
426
+ description: { type: 'string', required: true, description: 'What the tool does; becomes its docstring.' },
427
+ parameters: {
428
+ type: 'array',
429
+ description: 'Tool parameters.',
430
+ items: {
431
+ type: 'object',
432
+ additionalProperties: false,
433
+ properties: {
434
+ name: { type: 'string', required: true },
435
+ type: { type: 'string', required: true, description: 'str, int, float, bool, list[...], dict[...], or a dotted unreal type.' },
436
+ description: { type: 'string' },
437
+ },
438
+ },
439
+ },
440
+ returns: { type: 'string', description: 'Return annotation; defaults to None.' },
441
+ symbols: {
442
+ type: 'array',
443
+ items: { type: 'string' },
444
+ description: 'Unreal Python symbols the body will call, for example unreal.EditorAssetLibrary.save_asset.',
445
+ },
446
+ },
447
+ },
448
+ },
449
+ style: { type: 'string', description: 'toolset (default), editor_script, mcp_tool, or dsh_tool.' },
450
+ registry_import: { type: 'string', description: `Import line for the ToolsetRegistry decorator module; defaults to ${DEFAULT_REGISTRY_IMPORT}.` },
451
+ base_class: { type: 'string', description: 'Toolset base class; defaults to unreal.ToolsetDefinition.' },
452
+ test_module: { type: 'string', description: 'Module exporting the generated class, used by the generated test import; defaults to the snake_case toolset name.' },
453
+ },
454
+ output: {
455
+ schema: {
456
+ type: 'object',
457
+ additionalProperties: false,
458
+ properties: {
459
+ apiVersion: { type: 'string', required: true },
460
+ inventorySource: { type: 'string', required: true },
461
+ style: { type: 'string', required: true },
462
+ codeLabel: { type: 'string', required: true },
463
+ testLabel: { type: 'string', required: true },
464
+ code: { type: 'string', required: true },
465
+ testCode: { type: 'string', required: true },
466
+ verified: {
467
+ type: 'array',
468
+ required: true,
469
+ items: {
470
+ type: 'object',
471
+ additionalProperties: false,
472
+ properties: {
473
+ symbol: { type: 'string', required: true },
474
+ kind: { type: 'string', required: true },
475
+ url: { type: 'string', required: true },
476
+ },
477
+ },
478
+ },
479
+ unresolved: { type: 'array', required: true, items: { type: 'string' } },
480
+ notes: { type: 'array', required: true, items: { type: 'string' } },
481
+ },
482
+ },
483
+ render: (_args, value) => {
484
+ const fence = (label) => (label.includes('JSON') ? 'json' : label.includes('JavaScript') ? 'js' : 'python')
485
+ const lines = [`Scaffold built against the Unreal Python ${value.apiVersion} inventory (${value.inventorySource}).`]
486
+ for (const note of value.notes) lines.push(`- ${note}`)
487
+ if (value.verified.length > 0) {
488
+ lines.push(`Verified API calls (${value.verified.length}):`)
489
+ for (const entry of value.verified) lines.push(` ${entry.symbol} [${entry.kind}] ${entry.url}`)
490
+ }
491
+ if (value.unresolved.length > 0) {
492
+ lines.push(`Unresolved (${value.unresolved.length}):`)
493
+ for (const symbol of value.unresolved) lines.push(` ${symbol}`)
494
+ }
495
+ lines.push('', `${value.codeLabel}:`, '```' + fence(value.codeLabel), value.code, '```')
496
+ if (value.testCode !== '') lines.push(`${value.testLabel}:`, '```' + fence(value.testLabel), value.testCode, '```')
497
+ return [{ type: 'text', text: lines.join('\n') }]
498
+ },
499
+ },
500
+ timeoutMs: fetchTimeoutMs + 5_000,
501
+ async execute(args) {
502
+ const current = await inventory(false)
503
+ const { inventory: api } = current
504
+ const result = buildToolset(
505
+ {
506
+ toolsetName: args.toolset_name,
507
+ description: args.description,
508
+ style: args.style,
509
+ registryImport: args.registry_import,
510
+ baseClass: args.base_class,
511
+ testModule: args.test_module,
512
+ tools: Array.isArray(args.tools) && args.tools.length > 0 ? args.tools : singleTool(args),
513
+ },
514
+ (symbol) => {
515
+ const position = api.index.get(symbol)
516
+ if (position === undefined) return { found: false }
517
+ return {
518
+ found: true,
519
+ kind: friendlyKind(api.kinds[position]),
520
+ url: pageUrl(docBaseUrl, api.uris[position], symbol),
521
+ }
522
+ },
523
+ )
524
+ return { apiVersion: current.version, inventorySource: current.source, ...result }
525
+ },
526
+ }))
527
+
528
+ if (config.promptSection) {
529
+ ctx.systemPrompt.section({
530
+ name: 'plugin:unreal-python-api',
531
+ order: 350,
532
+ text:
533
+ scope.scope === 'anywhere'
534
+ ? `Unreal Python API (published 5.8 documentation): unreal_python_tools_list and unreal_python_search find documented symbols, unreal_python_syntax returns their exact signatures and parameters, and unreal_python_tool_builder scaffolds a tool from verified symbols in one of four styles — a ToolsetRegistry toolset, an editor script, MCP tool descriptors with their Python handlers, or a DSH tool module built on defineTool. Documentation root: ${docBaseUrl}`
535
+ : `Unreal Python API (published 5.8 documentation). The unreal_python_* tools are admitted only inside ${describeScope(scope)}; in other workspaces they are not offered. Inside one they list documented symbols, search them, return exact signatures and parameters, and scaffold tools from verified symbols in four styles. Documentation root: ${docBaseUrl}`,
536
+ })
537
+ }
538
+ }