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/CHANGELOG.md +53 -0
- package/LICENSE +21 -0
- package/README.md +182 -2
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.md +93 -0
- package/icon.svg +9 -0
- package/index.js +538 -0
- package/lib/builder.js +617 -0
- package/lib/docs.js +196 -0
- package/lib/inventory.js +304 -0
- package/lib/scope.js +199 -0
- package/link-deps.ps1 +36 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +51 -4
- package/test/smoke.mjs +343 -0
package/lib/builder.js
ADDED
|
@@ -0,0 +1,617 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scaffolds Unreal Python tools from a description plus verified API symbols.
|
|
3
|
+
*
|
|
4
|
+
* The emitted code follows the ToolsetRegistry shape: one `@unreal.uclass()`
|
|
5
|
+
* class inheriting `unreal.ToolsetDefinition`, one `@toolset_registry.tool_call`
|
|
6
|
+
* static method per tool, annotated parameters, and manual registration. Tool
|
|
7
|
+
* bodies are deliberately unimplemented, and every Unreal symbol the tool needs
|
|
8
|
+
* is recorded next to the body with the documentation page it was verified in.
|
|
9
|
+
*
|
|
10
|
+
* Four styles are supported: a ToolsetRegistry toolset (default), a plain editor
|
|
11
|
+
* script, MCP tool descriptors together with their Python handler module, and a
|
|
12
|
+
* DSH plugin tool module whose definitions register through defineTool.
|
|
13
|
+
*
|
|
14
|
+
* @module dsh-unreal-python-api/builder
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** Parameter types callers may declare, mapped onto Python annotations. */
|
|
18
|
+
const TYPE_MAP = new Map([
|
|
19
|
+
['str', 'str'],
|
|
20
|
+
['string', 'str'],
|
|
21
|
+
['int', 'int'],
|
|
22
|
+
['integer', 'int'],
|
|
23
|
+
['float', 'float'],
|
|
24
|
+
['number', 'float'],
|
|
25
|
+
['bool', 'bool'],
|
|
26
|
+
['boolean', 'bool'],
|
|
27
|
+
['none', 'None'],
|
|
28
|
+
['null', 'None'],
|
|
29
|
+
['any', 'typing.Any'],
|
|
30
|
+
])
|
|
31
|
+
|
|
32
|
+
/** Import line assumed for the ToolsetRegistry Python decorator module. */
|
|
33
|
+
export const DEFAULT_REGISTRY_IMPORT = 'from toolset_registry import toolset_registry'
|
|
34
|
+
|
|
35
|
+
/** Base class assumed for a generated toolset. */
|
|
36
|
+
export const DEFAULT_BASE_CLASS = 'unreal.ToolsetDefinition'
|
|
37
|
+
|
|
38
|
+
/** Styles buildToolset can emit. */
|
|
39
|
+
const STYLES = new Set(['toolset', 'editor_script', 'mcp_tool', 'dsh_tool'])
|
|
40
|
+
|
|
41
|
+
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
42
|
+
const DOTTED = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Map a declared parameter type onto a Python annotation.
|
|
46
|
+
* @param {string} [declared] Declared type such as str, int, float, bool, or unreal.Vector.
|
|
47
|
+
* @returns {string} Python annotation.
|
|
48
|
+
*/
|
|
49
|
+
export function pythonType(declared) {
|
|
50
|
+
const raw = String(declared ?? 'str').trim()
|
|
51
|
+
if (raw === '') return 'str'
|
|
52
|
+
const mapped = TYPE_MAP.get(raw.toLowerCase())
|
|
53
|
+
if (mapped !== undefined) return mapped
|
|
54
|
+
if (/^list\[[A-Za-z_][\w.\[\], ]*\]$/.test(raw)) return raw
|
|
55
|
+
if (/^dict\[[^\]]+\]$/.test(raw)) return raw
|
|
56
|
+
if (DOTTED.test(raw)) return raw
|
|
57
|
+
throw new Error(`unsupported parameter type '${declared}'; use str, int, float, bool, list[...], dict[...], or a dotted unreal type`)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Convert a name to snake_case.
|
|
62
|
+
* @param {string} value Source name.
|
|
63
|
+
* @returns {string} snake_case form.
|
|
64
|
+
*/
|
|
65
|
+
export function snakeCase(value) {
|
|
66
|
+
return String(value)
|
|
67
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
|
|
68
|
+
.replace(/[^A-Za-z0-9]+/g, '_')
|
|
69
|
+
.replace(/^_+|_+$/g, '')
|
|
70
|
+
.toLowerCase()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Convert a name to PascalCase.
|
|
75
|
+
* @param {string} value Source name.
|
|
76
|
+
* @returns {string} PascalCase form.
|
|
77
|
+
*/
|
|
78
|
+
export function pascalCase(value) {
|
|
79
|
+
return snakeCase(value)
|
|
80
|
+
.split('_')
|
|
81
|
+
.filter((part) => part !== '')
|
|
82
|
+
.map((part) => part[0].toUpperCase() + part.slice(1))
|
|
83
|
+
.join('')
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Value types shared by the JSON Schema and DSH schema styles. */
|
|
87
|
+
const SIMPLE_SCHEMA_TYPES = new Map([
|
|
88
|
+
['str', 'string'],
|
|
89
|
+
['string', 'string'],
|
|
90
|
+
['int', 'integer'],
|
|
91
|
+
['integer', 'integer'],
|
|
92
|
+
['float', 'number'],
|
|
93
|
+
['number', 'number'],
|
|
94
|
+
['bool', 'boolean'],
|
|
95
|
+
['boolean', 'boolean'],
|
|
96
|
+
])
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Shape one declared type as a schema value shared by the JSON Schema and DSH
|
|
100
|
+
* styles, whose object, array, and item keys are deliberately identical.
|
|
101
|
+
*
|
|
102
|
+
* @param {string} [declared] Declared type such as str, int, float, bool, list[str], or unreal.Vector.
|
|
103
|
+
* @returns {object} Schema value.
|
|
104
|
+
*/
|
|
105
|
+
export function schemaShape(declared) {
|
|
106
|
+
const raw = String(declared ?? 'str').trim()
|
|
107
|
+
if (raw === '') return { type: 'string' }
|
|
108
|
+
const simple = SIMPLE_SCHEMA_TYPES.get(raw.toLowerCase())
|
|
109
|
+
if (simple !== undefined) return { type: simple }
|
|
110
|
+
const list = /^list\[(.+)\]$/.exec(raw)
|
|
111
|
+
if (list !== null) return { type: 'array', items: schemaShape(list[1].trim()) }
|
|
112
|
+
if (/^dict\[.+\]$/.test(raw)) return { type: 'object', additionalProperties: true }
|
|
113
|
+
if (DOTTED.test(raw)) return { type: 'string' }
|
|
114
|
+
throw new Error(`unsupported parameter type '${declared}' for this style; use str, int, float, bool, list[...], dict[...], or a dotted unreal type`)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Whether a declared type is an Unreal object type (a dotted Python name) rather
|
|
119
|
+
* than a builder primitive, list, or dict.
|
|
120
|
+
* @param {unknown} declared Declared type.
|
|
121
|
+
* @returns {boolean} True for a dotted unreal type.
|
|
122
|
+
*/
|
|
123
|
+
function isObjectType(declared) {
|
|
124
|
+
const raw = String(declared ?? '').trim()
|
|
125
|
+
if (raw === '') return false
|
|
126
|
+
if (SIMPLE_SCHEMA_TYPES.has(raw.toLowerCase())) return false
|
|
127
|
+
if (/^list\[/i.test(raw) || /^dict\[/i.test(raw)) return false
|
|
128
|
+
return DOTTED.test(raw)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Build the schema value for one declared parameter, keeping its description.
|
|
133
|
+
* @param {object} parameter Normalized parameter.
|
|
134
|
+
* @returns {object} Schema value.
|
|
135
|
+
*/
|
|
136
|
+
function parameterShape(parameter) {
|
|
137
|
+
const shape = schemaShape(parameter.type)
|
|
138
|
+
const description = String(parameter.description ?? '').trim()
|
|
139
|
+
if (description !== '') shape.description = description
|
|
140
|
+
else if (isObjectType(parameter.type)) shape.description = `Unreal ${parameter.type} object path`
|
|
141
|
+
return shape
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Render a plain JavaScript literal for generated source, with a deterministic
|
|
146
|
+
* key order.
|
|
147
|
+
* @param {*} value Value to render.
|
|
148
|
+
* @returns {string} JavaScript source for the value.
|
|
149
|
+
*/
|
|
150
|
+
function renderJsValue(value) {
|
|
151
|
+
if (value === null) return 'null'
|
|
152
|
+
if (Array.isArray(value)) return `[${value.map(renderJsValue).join(', ')}]`
|
|
153
|
+
if (typeof value === 'object') {
|
|
154
|
+
const parts = Object.entries(value)
|
|
155
|
+
.filter(([, item]) => item !== undefined)
|
|
156
|
+
.map(([key, item]) => `${IDENTIFIER.test(key) ? key : JSON.stringify(key)}: ${renderJsValue(item)}`)
|
|
157
|
+
return `{ ${parts.join(', ')} }`
|
|
158
|
+
}
|
|
159
|
+
if (typeof value === 'string') return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`
|
|
160
|
+
return String(value)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Require a valid Python identifier.
|
|
165
|
+
* @param {string} label What the value names, for the error message.
|
|
166
|
+
* @param {string} value Candidate identifier.
|
|
167
|
+
* @returns {string} The identifier.
|
|
168
|
+
*/
|
|
169
|
+
function requireIdentifier(label, value) {
|
|
170
|
+
if (!IDENTIFIER.test(value)) throw new Error(`${label} '${value}' is not a valid Python identifier`)
|
|
171
|
+
return value
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Keep only symbols that were verified against the inventory, so an unverified
|
|
176
|
+
* name never reaches the generated code.
|
|
177
|
+
* @param {string[]} symbols Requested symbols.
|
|
178
|
+
* @param {Map<string, string>} urls Verified symbol URLs.
|
|
179
|
+
* @returns {string[]} Verified symbols.
|
|
180
|
+
*/
|
|
181
|
+
function verifiedOnly(symbols, urls) {
|
|
182
|
+
return symbols.filter((symbol) => urls.has(symbol))
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Render the documentation comment listing the verified API calls.
|
|
187
|
+
* @param {string[]} symbols Verified symbol names.
|
|
188
|
+
* @param {Map<string, string>} urls Symbol to documentation URL.
|
|
189
|
+
* @param {string} indent Leading whitespace for each line.
|
|
190
|
+
* @returns {string[]} Comment lines.
|
|
191
|
+
*/
|
|
192
|
+
function symbolComments(symbols, urls, indent, prefix = '#') {
|
|
193
|
+
if (symbols.length === 0) return []
|
|
194
|
+
const lines = [`${indent}${prefix} Unreal Python API calls this tool needs, verified in the published inventory:`]
|
|
195
|
+
for (const symbol of symbols) lines.push(`${indent}${prefix} ${symbol} ${urls.get(symbol)}`)
|
|
196
|
+
return lines
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Render one tool method.
|
|
201
|
+
* @param {object} tool Tool definition.
|
|
202
|
+
* @param {Map<string, string>} urls Verified symbol URLs.
|
|
203
|
+
* @returns {string[]} Method lines.
|
|
204
|
+
*/
|
|
205
|
+
function renderTool(tool, urls) {
|
|
206
|
+
const lines = []
|
|
207
|
+
lines.push(' @toolset_registry.tool_call')
|
|
208
|
+
lines.push(' @staticmethod')
|
|
209
|
+
const parameters = (tool.parameters ?? []).map((parameter) => {
|
|
210
|
+
const name = requireIdentifier(`parameter name in tool '${tool.name}'`, snakeCase(parameter.name))
|
|
211
|
+
return `${name}: ${pythonType(parameter.type)}`
|
|
212
|
+
})
|
|
213
|
+
const returns = pythonType(tool.returns ?? 'None')
|
|
214
|
+
lines.push(` def ${tool.fnName}(${parameters.join(', ')}) -> ${returns}:`)
|
|
215
|
+
const summary = String(tool.description).trim().replace(/\s+/g, ' ')
|
|
216
|
+
const documented = (tool.parameters ?? []).filter((parameter) => String(parameter.description ?? '').trim() !== '')
|
|
217
|
+
if (documented.length === 0) {
|
|
218
|
+
lines.push(` """${summary}"""`)
|
|
219
|
+
} else {
|
|
220
|
+
lines.push(` """${summary}`)
|
|
221
|
+
lines.push('')
|
|
222
|
+
lines.push(' Args:')
|
|
223
|
+
for (const parameter of documented) {
|
|
224
|
+
lines.push(` ${snakeCase(parameter.name)}: ${String(parameter.description).trim()}`)
|
|
225
|
+
}
|
|
226
|
+
lines.push(' """')
|
|
227
|
+
}
|
|
228
|
+
lines.push(...symbolComments(verifiedOnly(tool.symbols ?? [], urls), urls, ' '))
|
|
229
|
+
lines.push(` raise NotImplementedError('${tool.fnName} is not implemented')`)
|
|
230
|
+
lines.push('')
|
|
231
|
+
return lines
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Render a Python toolset module.
|
|
236
|
+
* @param {object} input Builder input.
|
|
237
|
+
* @param {Map<string, string>} urls Verified symbol URLs.
|
|
238
|
+
* @returns {string} Module source.
|
|
239
|
+
*/
|
|
240
|
+
function renderToolset(input, urls) {
|
|
241
|
+
const className = requireIdentifier('toolset_name', input.className)
|
|
242
|
+
const lines = []
|
|
243
|
+
lines.push(`"""${input.description}`)
|
|
244
|
+
lines.push('')
|
|
245
|
+
lines.push('Scaffold generated by dsh-unreal-python-api from the published Unreal Python API')
|
|
246
|
+
lines.push('inventory. Tool bodies raise NotImplementedError until they are implemented.')
|
|
247
|
+
lines.push('"""')
|
|
248
|
+
lines.push('')
|
|
249
|
+
lines.push('import unreal')
|
|
250
|
+
lines.push('')
|
|
251
|
+
if (input.registryImport !== '') {
|
|
252
|
+
lines.push(input.registryImport)
|
|
253
|
+
lines.push('')
|
|
254
|
+
}
|
|
255
|
+
lines.push('')
|
|
256
|
+
lines.push('@unreal.uclass()')
|
|
257
|
+
lines.push(`class ${className}(${input.baseClass}):`)
|
|
258
|
+
lines.push(` """${input.description}"""`)
|
|
259
|
+
lines.push('')
|
|
260
|
+
for (const tool of input.tools) lines.push(...renderTool(tool, urls))
|
|
261
|
+
lines.push('')
|
|
262
|
+
lines.push(`def register_toolsets() -> None:`)
|
|
263
|
+
lines.push(` """Register ${className} with the ToolsetRegistry."""`)
|
|
264
|
+
lines.push(` unreal.ToolsetRegistry.register_toolset_class(${className})`)
|
|
265
|
+
lines.push('')
|
|
266
|
+
lines.push('')
|
|
267
|
+
lines.push('def unregister_toolsets() -> None:')
|
|
268
|
+
lines.push(` """Unregister ${className} from the ToolsetRegistry."""`)
|
|
269
|
+
lines.push(` unreal.ToolsetRegistry.unregister_toolset_class(${className})`)
|
|
270
|
+
lines.push('')
|
|
271
|
+
return lines.join('\n')
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Render a plain editor script instead of a toolset.
|
|
276
|
+
* @param {object} input Builder input.
|
|
277
|
+
* @param {Map<string, string>} urls Verified symbol URLs.
|
|
278
|
+
* @returns {string} Script source.
|
|
279
|
+
*/
|
|
280
|
+
function renderEditorScript(input, urls) {
|
|
281
|
+
const lines = []
|
|
282
|
+
lines.push(`"""${input.description}`)
|
|
283
|
+
lines.push('')
|
|
284
|
+
lines.push('Scaffold generated by dsh-unreal-python-api. The body raises NotImplementedError')
|
|
285
|
+
lines.push('until it is implemented.')
|
|
286
|
+
lines.push('"""')
|
|
287
|
+
lines.push('')
|
|
288
|
+
lines.push('import unreal')
|
|
289
|
+
lines.push('')
|
|
290
|
+
lines.push('')
|
|
291
|
+
lines.push('def main() -> None:')
|
|
292
|
+
lines.push(` """${input.description}"""`)
|
|
293
|
+
const symbols = verifiedOnly([...new Set(input.tools.flatMap((tool) => tool.symbols ?? []))], urls)
|
|
294
|
+
lines.push(...symbolComments(symbols, urls, ' '))
|
|
295
|
+
lines.push(" raise NotImplementedError('main is not implemented')")
|
|
296
|
+
lines.push('')
|
|
297
|
+
lines.push('')
|
|
298
|
+
lines.push("if __name__ == '__main__':")
|
|
299
|
+
lines.push(' main()')
|
|
300
|
+
lines.push('')
|
|
301
|
+
return lines.join('\n')
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Build the MCP tool descriptors for the requested tools.
|
|
306
|
+
* @param {object} input Builder input.
|
|
307
|
+
* @returns {Array<object>} Tool descriptors with a JSON Schema inputSchema.
|
|
308
|
+
*/
|
|
309
|
+
function mcpDescriptors(input) {
|
|
310
|
+
return input.tools.map((tool) => ({
|
|
311
|
+
name: tool.fnName,
|
|
312
|
+
description: tool.description,
|
|
313
|
+
inputSchema: {
|
|
314
|
+
type: 'object',
|
|
315
|
+
properties: Object.fromEntries(tool.parameters.map((parameter) => [parameter.fnName, parameterShape(parameter)])),
|
|
316
|
+
required: tool.parameters.map((parameter) => parameter.fnName),
|
|
317
|
+
additionalProperties: false,
|
|
318
|
+
},
|
|
319
|
+
}))
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Render MCP tool descriptors as JSON, ready for an MCP server's tools/list.
|
|
324
|
+
* @param {object} input Builder input.
|
|
325
|
+
* @returns {string} Descriptor document.
|
|
326
|
+
*/
|
|
327
|
+
function renderMcpTool(input) {
|
|
328
|
+
return `${JSON.stringify({ tools: mcpDescriptors(input) }, null, 2)}\n`
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Render the Python handler module that serves the MCP descriptors.
|
|
333
|
+
* @param {object} input Builder input.
|
|
334
|
+
* @param {Map<string, string>} urls Verified symbol URLs.
|
|
335
|
+
* @returns {string} Module source.
|
|
336
|
+
*/
|
|
337
|
+
function renderMcpHandlers(input, urls) {
|
|
338
|
+
const document = JSON.stringify({ tools: mcpDescriptors(input) }, null, 2)
|
|
339
|
+
if (document.includes('"""')) throw new Error('a tool description contains a triple quote; reword it for the Python handler module')
|
|
340
|
+
const lines = []
|
|
341
|
+
lines.push(`"""Handlers for the MCP tools in ${input.className}.json.`)
|
|
342
|
+
lines.push('')
|
|
343
|
+
lines.push('Scaffold generated by dsh-unreal-python-api from the published Unreal Python API')
|
|
344
|
+
lines.push('inventory. Handler bodies raise NotImplementedError until they are implemented,')
|
|
345
|
+
lines.push('and TOOL_SPEC is the same descriptor list the server advertises in tools/list.')
|
|
346
|
+
lines.push('"""')
|
|
347
|
+
lines.push('')
|
|
348
|
+
lines.push('import json')
|
|
349
|
+
lines.push('')
|
|
350
|
+
lines.push('import unreal')
|
|
351
|
+
lines.push('')
|
|
352
|
+
lines.push('TOOL_SPEC = json.loads(r"""')
|
|
353
|
+
lines.push(document)
|
|
354
|
+
lines.push('""".strip())')
|
|
355
|
+
lines.push('')
|
|
356
|
+
for (const tool of input.tools) {
|
|
357
|
+
lines.push('')
|
|
358
|
+
const parameters = tool.parameters.map((parameter) => `${parameter.fnName}: ${pythonType(parameter.type)}`)
|
|
359
|
+
lines.push(`def ${tool.fnName}(${parameters.join(', ')}) -> ${pythonType(tool.returns ?? 'None')}:`)
|
|
360
|
+
const summary = String(tool.description).trim().replace(/\s+/g, ' ')
|
|
361
|
+
const documented = tool.parameters.filter((parameter) => String(parameter.description ?? '').trim() !== '')
|
|
362
|
+
if (documented.length === 0) {
|
|
363
|
+
lines.push(` """${summary}"""`)
|
|
364
|
+
} else {
|
|
365
|
+
lines.push(` """${summary}`)
|
|
366
|
+
lines.push('')
|
|
367
|
+
lines.push(' Args:')
|
|
368
|
+
for (const parameter of documented) {
|
|
369
|
+
lines.push(` ${parameter.fnName}: ${String(parameter.description).trim()}`)
|
|
370
|
+
}
|
|
371
|
+
lines.push(' """')
|
|
372
|
+
}
|
|
373
|
+
lines.push(...symbolComments(verifiedOnly(tool.symbols ?? [], urls), urls, ' '))
|
|
374
|
+
lines.push(` raise NotImplementedError('${tool.fnName} is not implemented')`)
|
|
375
|
+
lines.push('')
|
|
376
|
+
}
|
|
377
|
+
lines.push('')
|
|
378
|
+
lines.push('HANDLERS = {')
|
|
379
|
+
for (const tool of input.tools) lines.push(` '${tool.fnName}': ${tool.fnName},`)
|
|
380
|
+
lines.push('}')
|
|
381
|
+
lines.push('')
|
|
382
|
+
lines.push('')
|
|
383
|
+
lines.push('def handle(name: str, arguments: dict) -> object:')
|
|
384
|
+
lines.push(' """Dispatch one MCP tools/call to its handler."""')
|
|
385
|
+
lines.push(' handler = HANDLERS.get(name)')
|
|
386
|
+
lines.push(' if handler is None:')
|
|
387
|
+
lines.push(" raise KeyError(f'unknown tool {name!r}')")
|
|
388
|
+
lines.push(' return handler(**arguments)')
|
|
389
|
+
lines.push('')
|
|
390
|
+
return lines.join('\n')
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Render a DSH plugin tool module whose definitions register through defineTool.
|
|
395
|
+
* @param {object} input Builder input.
|
|
396
|
+
* @param {Map<string, string>} urls Verified symbol URLs.
|
|
397
|
+
* @returns {string} Module source.
|
|
398
|
+
*/
|
|
399
|
+
function renderDshTool(input, urls) {
|
|
400
|
+
const lines = []
|
|
401
|
+
lines.push('/**')
|
|
402
|
+
lines.push(` * ${input.description}`)
|
|
403
|
+
lines.push(' *')
|
|
404
|
+
lines.push(' * Scaffold generated by dsh-unreal-python-api from the published Unreal Python API')
|
|
405
|
+
lines.push(' * inventory. Call registerTools(ctx) from a plugin apply() body; every execute')
|
|
406
|
+
lines.push(' * body throws until it is implemented.')
|
|
407
|
+
lines.push(' */')
|
|
408
|
+
lines.push('')
|
|
409
|
+
lines.push("import { defineTool } from '@deepseek-ai/dsh-tools'")
|
|
410
|
+
lines.push('')
|
|
411
|
+
lines.push('export const tools = [')
|
|
412
|
+
for (const tool of input.tools) {
|
|
413
|
+
lines.push(' defineTool({')
|
|
414
|
+
lines.push(` name: '${tool.fnName}',`)
|
|
415
|
+
lines.push(` description: ${renderJsValue(String(tool.description).trim().replace(/\s+/g, ' '))},`)
|
|
416
|
+
lines.push(' parameters: {')
|
|
417
|
+
for (const parameter of tool.parameters) {
|
|
418
|
+
const shape = { ...parameterShape(parameter), required: true }
|
|
419
|
+
lines.push(` ${parameter.fnName}: ${renderJsValue(shape)},`)
|
|
420
|
+
}
|
|
421
|
+
lines.push(' },')
|
|
422
|
+
lines.push(' output: {')
|
|
423
|
+
lines.push(" schema: { type: 'object', additionalProperties: false, properties: { ok: { type: 'boolean', required: true }, detail: { type: 'string', required: true } } },")
|
|
424
|
+
lines.push(' render: (_args, value) => [{ type: \'text\', text: JSON.stringify(value, null, 2) }],')
|
|
425
|
+
lines.push(' },')
|
|
426
|
+
lines.push(' async execute(_args) {')
|
|
427
|
+
lines.push(...symbolComments(verifiedOnly(tool.symbols ?? [], urls), urls, ' ', '//'))
|
|
428
|
+
lines.push(` throw new Error('${tool.fnName} is not implemented')`)
|
|
429
|
+
lines.push(' },')
|
|
430
|
+
lines.push(' }),')
|
|
431
|
+
}
|
|
432
|
+
lines.push(']')
|
|
433
|
+
lines.push('')
|
|
434
|
+
lines.push('export const toolNames = tools.map((tool) => tool.name)')
|
|
435
|
+
lines.push('')
|
|
436
|
+
lines.push('/** Register every tool above with a DSH plugin tool registry. */')
|
|
437
|
+
lines.push('export function registerTools(ctx) {')
|
|
438
|
+
lines.push(' for (const tool of tools) ctx.tools.register(tool)')
|
|
439
|
+
lines.push(' return toolNames.length')
|
|
440
|
+
lines.push('}')
|
|
441
|
+
lines.push('')
|
|
442
|
+
return lines.join('\n')
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Render the Node test module for a generated DSH tool module.
|
|
447
|
+
* @param {object} input Builder input.
|
|
448
|
+
* @returns {string} Test module source.
|
|
449
|
+
*/
|
|
450
|
+
function renderDshTests(input) {
|
|
451
|
+
const lines = []
|
|
452
|
+
lines.push(`/** Tests for ${input.testModule}: registration and declared shapes. */`)
|
|
453
|
+
lines.push('')
|
|
454
|
+
lines.push("import assert from 'node:assert/strict'")
|
|
455
|
+
lines.push("import test from 'node:test'")
|
|
456
|
+
lines.push('')
|
|
457
|
+
lines.push(`import { registerTools, toolNames, tools } from './${input.testModule}.mjs'`)
|
|
458
|
+
lines.push('')
|
|
459
|
+
lines.push(`test('${input.testModule} registers every declared tool', () => {`)
|
|
460
|
+
lines.push(' assert.ok(tools.length > 0)')
|
|
461
|
+
lines.push(' assert.equal(toolNames.length, tools.length)')
|
|
462
|
+
lines.push(' for (const name of toolNames) assert.equal(typeof name, \'string\')')
|
|
463
|
+
lines.push(' const received = []')
|
|
464
|
+
lines.push(' const registered = registerTools({ tools: { register: (definition) => received.push(definition) } })')
|
|
465
|
+
lines.push(' assert.equal(registered, toolNames.length)')
|
|
466
|
+
lines.push(' assert.deepEqual(received.map((definition) => definition.name), toolNames)')
|
|
467
|
+
lines.push('})')
|
|
468
|
+
lines.push('')
|
|
469
|
+
lines.push(`// Every execute body throws until it is implemented; replace this test with one that`)
|
|
470
|
+
lines.push(`// calls the tool in the editor and asserts the returned value.`)
|
|
471
|
+
lines.push('')
|
|
472
|
+
return lines.join('\n')
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Render the test module required for a generated toolset.
|
|
477
|
+
* @param {object} input Builder input.
|
|
478
|
+
* @returns {string} Test module source.
|
|
479
|
+
*/
|
|
480
|
+
function renderTests(input) {
|
|
481
|
+
const className = input.className
|
|
482
|
+
const lines = []
|
|
483
|
+
lines.push(`"""Tests for ${className}, covering each tool's success and failure path."""`)
|
|
484
|
+
lines.push('')
|
|
485
|
+
lines.push(`from ${input.testModule} import ${className}`)
|
|
486
|
+
lines.push('# Import the project\'s ToolCallTestCase base from its ToolsetRegistry plugin.')
|
|
487
|
+
lines.push('')
|
|
488
|
+
lines.push('')
|
|
489
|
+
lines.push(`class ${className}TestCase(ToolCallTestCase):`)
|
|
490
|
+
lines.push(` """Tests ${className}."""`)
|
|
491
|
+
lines.push('')
|
|
492
|
+
for (const tool of input.tools) {
|
|
493
|
+
lines.push(` def test_${tool.fnName}_returns_expected(self) -> None:`)
|
|
494
|
+
lines.push(` """${String(tool.description).trim()}"""`)
|
|
495
|
+
lines.push(` raise NotImplementedError('assert the ${tool.fnName} result')`)
|
|
496
|
+
lines.push('')
|
|
497
|
+
}
|
|
498
|
+
return lines.join('\n')
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* Build a Unreal Python scaffold from a description and verified symbols.
|
|
503
|
+
*
|
|
504
|
+
* @param {object} input Toolset description, tools, and style.
|
|
505
|
+
* @param {(symbol: string) => {found: boolean, url?: string, kind?: string}} resolve Symbol lookup used to verify API calls.
|
|
506
|
+
* @returns {{style: string, codeLabel: string, testLabel: string, code: string, testCode: string, verified: Array<{symbol: string, url: string, kind: string}>, unresolved: string[], notes: string[]}} Scaffold and verification report.
|
|
507
|
+
*/
|
|
508
|
+
export function buildToolset(input, resolve) {
|
|
509
|
+
const requestedStyle = String(input.style ?? '').trim()
|
|
510
|
+
const style = requestedStyle === '' ? 'toolset' : requestedStyle
|
|
511
|
+
if (!STYLES.has(style)) throw new Error(`unsupported style '${style}'; use ${[...STYLES].join(', ')}`)
|
|
512
|
+
const requested = input.tools ?? []
|
|
513
|
+
if (requested.length === 0) throw new Error('tools must contain at least one tool')
|
|
514
|
+
|
|
515
|
+
const seen = new Set()
|
|
516
|
+
const verified = []
|
|
517
|
+
const unresolved = []
|
|
518
|
+
const urls = new Map()
|
|
519
|
+
// Caller arguments arrive frozen, so every tool is normalized into a copy.
|
|
520
|
+
const tools = requested.map((tool) => {
|
|
521
|
+
const name = String(tool.name ?? '').trim()
|
|
522
|
+
if (name === '') throw new Error('every tool needs a name')
|
|
523
|
+
const description = String(tool.description ?? '').trim()
|
|
524
|
+
if (description === '') throw new Error(`tool '${name}' needs a description`)
|
|
525
|
+
const fnName = requireIdentifier(`tool name '${name}' as a function`, snakeCase(name))
|
|
526
|
+
if (seen.has(fnName)) throw new Error(`two tools map onto the same function name '${fnName}'`)
|
|
527
|
+
seen.add(fnName)
|
|
528
|
+
const parameters = (tool.parameters ?? []).map((parameter) => {
|
|
529
|
+
const parameterName = String(parameter?.name ?? '').trim()
|
|
530
|
+
if (parameterName === '') throw new Error(`parameter name in tool '${name}' must not be empty`)
|
|
531
|
+
return {
|
|
532
|
+
name: parameterName,
|
|
533
|
+
fnName: requireIdentifier(`parameter name in tool '${name}'`, snakeCase(parameterName)),
|
|
534
|
+
type: parameter?.type,
|
|
535
|
+
description: String(parameter?.description ?? '').trim(),
|
|
536
|
+
}
|
|
537
|
+
})
|
|
538
|
+
const symbols = [...new Set(
|
|
539
|
+
(tool.symbols ?? []).map((symbol) => String(symbol).trim()).filter((symbol) => symbol !== ''),
|
|
540
|
+
)]
|
|
541
|
+
for (const symbol of symbols) {
|
|
542
|
+
const found = resolve(symbol)
|
|
543
|
+
if (!found.found) {
|
|
544
|
+
unresolved.push(`${symbol} (tool ${name})`)
|
|
545
|
+
continue
|
|
546
|
+
}
|
|
547
|
+
urls.set(symbol, found.url)
|
|
548
|
+
if (!verified.some((entry) => entry.symbol === symbol)) {
|
|
549
|
+
verified.push({ symbol, url: found.url, kind: found.kind })
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
return { name, description, fnName, parameters, returns: tool.returns, symbols }
|
|
553
|
+
})
|
|
554
|
+
|
|
555
|
+
const normalized = {
|
|
556
|
+
description: String(input.description ?? '').trim(),
|
|
557
|
+
className: pascalCase(input.toolsetName ?? ''),
|
|
558
|
+
baseClass: String(input.baseClass ?? '').trim() === '' ? DEFAULT_BASE_CLASS : input.baseClass.trim(),
|
|
559
|
+
registryImport: input.registryImport === undefined ? DEFAULT_REGISTRY_IMPORT : String(input.registryImport).trim(),
|
|
560
|
+
testModule: String(input.testModule ?? snakeCase(input.toolsetName ?? '')).trim(),
|
|
561
|
+
tools,
|
|
562
|
+
}
|
|
563
|
+
if (normalized.description === '') throw new Error('description must not be empty')
|
|
564
|
+
if (!DOTTED.test(normalized.baseClass)) throw new Error(`base_class '${normalized.baseClass}' must be a dotted Python name`)
|
|
565
|
+
|
|
566
|
+
const notes = [
|
|
567
|
+
'Tool bodies raise NotImplementedError; implement them before registering.',
|
|
568
|
+
`Registry decorator import: ${normalized.registryImport === '' ? 'omitted (supply the line for your ToolsetRegistry plugin)' : normalized.registryImport}.`,
|
|
569
|
+
`Base class: ${normalized.baseClass}.`,
|
|
570
|
+
]
|
|
571
|
+
if (unresolved.length > 0) {
|
|
572
|
+
notes.push(`${unresolved.length} requested symbol(s) are not in the published inventory and were not written into the code; confirm them against the editor before use.`)
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const renderer = {
|
|
576
|
+
toolset: {
|
|
577
|
+
codeLabel: 'Toolset module (Python)',
|
|
578
|
+
testLabel: 'Test module (Python)',
|
|
579
|
+
code: renderToolset,
|
|
580
|
+
tests: renderTests,
|
|
581
|
+
note: 'Registry decorator import and base class are the ToolsetRegistry defaults; change registry_import or base_class when your plugin differs.',
|
|
582
|
+
},
|
|
583
|
+
editor_script: {
|
|
584
|
+
codeLabel: 'Editor script (Python)',
|
|
585
|
+
testLabel: '',
|
|
586
|
+
code: renderEditorScript,
|
|
587
|
+
tests: null,
|
|
588
|
+
note: 'The script defines main(); run it from the editor’s Python console or a startup script.',
|
|
589
|
+
},
|
|
590
|
+
mcp_tool: {
|
|
591
|
+
codeLabel: 'MCP tool descriptors (JSON)',
|
|
592
|
+
testLabel: 'Handler module (Python)',
|
|
593
|
+
code: renderMcpTool,
|
|
594
|
+
tests: renderMcpHandlers,
|
|
595
|
+
note: 'Every declared parameter is marked required in the JSON Schema; the handler module mirrors the same descriptors in TOOL_SPEC and dispatches through handle().',
|
|
596
|
+
},
|
|
597
|
+
dsh_tool: {
|
|
598
|
+
codeLabel: 'DSH tool module (JavaScript)',
|
|
599
|
+
testLabel: 'Test module (JavaScript)',
|
|
600
|
+
code: renderDshTool,
|
|
601
|
+
tests: renderDshTests,
|
|
602
|
+
note: 'DSH parameters are emitted with required: true; drop it for optional ones, and replace the output schema with the shape the tool returns.',
|
|
603
|
+
},
|
|
604
|
+
}[style]
|
|
605
|
+
|
|
606
|
+
notes.push(renderer.note)
|
|
607
|
+
return {
|
|
608
|
+
style,
|
|
609
|
+
codeLabel: renderer.codeLabel,
|
|
610
|
+
testLabel: renderer.testLabel,
|
|
611
|
+
code: renderer.code(normalized, urls),
|
|
612
|
+
testCode: renderer.tests === null ? '' : renderer.tests(normalized, urls),
|
|
613
|
+
verified,
|
|
614
|
+
unresolved,
|
|
615
|
+
notes,
|
|
616
|
+
}
|
|
617
|
+
}
|