dsh-unreal-python-api 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,49 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0 — 2026-11-30
4
+
5
+ - Split the tools into two tiers. **general** — `unreal_python_tools_list`,
6
+ `unreal_python_search`, `unreal_python_syntax` — register unconditionally and
7
+ are offered in every workspace. **development** — `unreal_python_tool_builder`
8
+ — is admitted only inside `scope`, so a normal workspace keeps the lookups and
9
+ the code-generating tool appears only where you develop. `scope: anywhere`
10
+ (the default) still offers everything everywhere.
11
+ - The prompt section now names the general tier and says where the development
12
+ tier applies instead of implying all four tools behave alike.
13
+ - Tests assert the tier split: three unconditional tools, exactly one gated, and
14
+ the gated one is the builder.
15
+
16
+ ## 1.1.1 — 2026-11-30
17
+
18
+ - Fixed the test suite on a machine without the harness packages: the export,
19
+ configuration and `apply()` checks now run only when `@deepseek-ai/dsh-tools`
20
+ and `@deepseek-ai/schemastery` resolve, and the data-path checks always run.
21
+ `v1.1.0` was tagged but its publish run failed before reaching npm, so 1.1.1 is
22
+ the first published 1.1.x.
23
+
24
+ ## 1.1.0 — 2026-11-30
25
+
26
+ Workspace-specific activation.
27
+
28
+ - Added `scope` (`anywhere` | `unreal-project` | `workspaces`), `workspaces`
29
+ and `projectMarkers`. With a non-default scope the four tools are registered
30
+ behind a step-time activation condition, so they only appear in the model's
31
+ tool list inside the configured workspaces or an Unreal project.
32
+ - The system-prompt section now states where the tools are admitted instead of
33
+ implying they are always available.
34
+ - `lib/scope.js`: segment-aware, case-insensitive path matching, `.uproject`
35
+ ancestor detection with configurable markers, a ten-second per-directory
36
+ cache, and a gate that rejects rather than throws.
37
+ - Tests: workspace matching (including a shared-prefix sibling such as `TDA2`),
38
+ Unreal project detection in a temporary directory, a custom marker list, the
39
+ failing-lookup path, and the plugin module's exports plus configuration
40
+ defaults.
41
+ - Fixed: the tool builder advertised a single-tool shortcut (`tool_name`,
42
+ `tool_description`, `tool_parameters`, `tool_returns`, `tool_symbols`) that
43
+ the handler never read, and `tools` was required — so a one-tool call was
44
+ rejected before it ran. `tools` is now optional, the shortcut is implemented,
45
+ and a shortcut without `tool_description` fails with a plain message.
46
+
3
47
  ## 1.0.0 — 2026-11-30
4
48
 
5
49
  First release.
@@ -18,3 +62,5 @@ First release.
18
62
  reported instead of being written into the code.
19
63
  - Inventory downloaded from Epic's `objects.inv`, cached locally, refreshed every
20
64
  24 hours by default.
65
+ - Published from a `v1.0.0` tag through GitHub Actions with npm provenance;
66
+ `latest` on npm since 2026-11-30.
package/README.md CHANGED
@@ -6,6 +6,8 @@ scaffolding in four flavours — from the symbol inventory Epic publishes beside
6
6
  Python API documentation. See [docs/DETAIL.md](docs/DETAIL.md) for what each tool
7
7
  returns and how the data is kept.
8
8
 
9
+ Source: <https://github.com/TaimoorSiddiquiOfficial/dsh-unreal-python-api> · MIT.
10
+
9
11
  ## What the agent gets
10
12
 
11
13
  | Tool | What it does |
@@ -51,12 +53,15 @@ Do not expect:
51
53
 
52
54
  From the plugin market or an index source: install `dsh-unreal-python-api`.
53
55
 
54
- From npm after publishing:
56
+ Live on npm since 2026-11-30 (published with provenance from the `v1.0.0` tag):
55
57
 
56
58
  ```powershell
57
59
  dsh plugin --profile web add dsh-unreal-python-api
58
60
  ```
59
61
 
62
+ npm held the name with a `0.0.0-stage` staging placeholder for about a minute while
63
+ it released that first publish; `latest` is now `1.0.0`.
64
+
60
65
  From a local checkout (no publish needed):
61
66
 
62
67
  ```powershell
@@ -80,7 +85,10 @@ Removing it: `dsh plugin --profile web remove dsh-unreal-python-api`.
80
85
  - DeepSeek Harness with the `tools` and `systemPrompt` services (0.2.2-rc.5 or
81
86
  newer). `@deepseek-ai/dsh-tools` is host-provided: the version on npm
82
87
  (`0.0.1-rc.1`) is older than the one the harness ships, so it is deliberately
83
- not declared as a dependency.
88
+ not declared as a dependency. That bare import resolves by walking up from the
89
+ installed package to the DSH install; if your profile's `node_modules` does not
90
+ sit under the DSH install or its parents, install from a linked checkout and run
91
+ `link-deps.ps1` instead.
84
92
  - Node 20+ (global `fetch`, `node:zlib`) — no third-party dependencies.
85
93
  - Network access on the first run (the inventory is 612 KB, then cached).
86
94
  - Optional: Python on PATH, so the smoke test can parse-check the Python
@@ -121,6 +129,43 @@ locale/, icon.svg Host display metadata
121
129
  | `maxResults` | `30` | Upper bound on rows a tool returns. |
122
130
  | `fetchTimeoutMs` | `30000` | Page and inventory timeout. |
123
131
  | `promptSection` | `true` | Register the system-prompt section. |
132
+ | `scope` | `anywhere` | Where the development tier is offered: `anywhere`, `unreal-project`, or `workspaces`. |
133
+ | `workspaces` | `[]` | Absolute roots admitted by `scope: workspaces`. |
134
+ | `projectMarkers` | `['.uproject']` | Files that identify a project root; replaces the default list. |
135
+
136
+ ### Two tiers, and workspace scoping
137
+
138
+ One profile install serves every workspace, so the tools come in two tiers:
139
+
140
+ | Tier | Tools | Offered |
141
+ |---|---|---|
142
+ | general | `unreal_python_tools_list`, `unreal_python_search`, `unreal_python_syntax` | every workspace, always |
143
+ | development | `unreal_python_tool_builder` | only inside `scope` |
144
+
145
+ `scope` decides where the development tier is admitted:
146
+
147
+ | `scope` | The development tier is offered when |
148
+ |---|---|
149
+ | `anywhere` (default) | always — the 1.0/1.1 behaviour, nothing gated |
150
+ | `unreal-project` | the session's working directory, or a parent, holds a `*.uproject` |
151
+ | `workspaces` | the working directory is inside one of the `workspaces` roots |
152
+
153
+ ```yaml
154
+ # the dsh-unreal-python-api row's config (profile cordis.patch.yml, or the
155
+ # plugin's settings panel in the GUI when it offers one)
156
+ config:
157
+ scope: workspaces
158
+ workspaces:
159
+ - D:\HOP TRENDY UNREAL\Unreal Projects\TDA
160
+ ```
161
+
162
+ The check runs once per prepared step against the session's committed working
163
+ directory, is cached for ten seconds, and never throws: an unknown directory or
164
+ a failing lookup counts as not admitted. Comparison is segment-aware and
165
+ case-insensitive, so `…\TDA` admits `…\TDA\Source` but not `…\TDA2`. Outside the
166
+ scope the development tool is absent from the model's tool list entirely rather
167
+ than refused at call time, and the prompt section says so. The general tier is
168
+ never gated, so documentation lookups keep working in every workspace.
124
169
 
125
170
  ## Publishing to the market
126
171
 
package/docs/DETAIL.md CHANGED
@@ -66,6 +66,26 @@ grounded starting point, not finished code.
66
66
  | `maxResults` | `30` | Default row cap per call; a caller may ask for fewer or more, up to 200. |
67
67
  | `fetchTimeoutMs` | `30000` | Per-request timeout for the inventory and documentation pages. |
68
68
  | `promptSection` | `true` | Adds one line to the system prompt naming the tools and the documentation root. |
69
+ | `scope` | `anywhere` | `anywhere`, `unreal-project`, or `workspaces`; where the development tier is admitted. |
70
+ | `workspaces` | `[]` | Absolute roots admitted by `scope: workspaces`; required by that mode. |
71
+ | `projectMarkers` | `['.uproject']` | File names (or `.extension` suffixes) that mark a project root. Replaces, never extends, the default. |
72
+
73
+ ### Scope gate
74
+
75
+ The tools form two tiers. `unreal_python_tools_list`, `unreal_python_search` and
76
+ `unreal_python_syntax` are general: they register unconditionally and stay
77
+ available in every workspace. `unreal_python_tool_builder` is development: it
78
+ writes code, so it is the tool `scope` gates.
79
+
80
+ Gating uses the tool runtime's step-time activation condition —
81
+ `ctx.tools.register(definition, { when })`, where `when` receives the preparing
82
+ agent. The plugin reads the session's committed working directory through the
83
+ `workingDirectory` service (`ctx.workingDirectory.get(agent.session)`), so the
84
+ decision follows a directory change without restarting anything. Each directory
85
+ is checked at most once every ten seconds, and a lookup failure rejects that
86
+ step's admission instead of throwing, because a throwing condition fails step
87
+ preparation. The default `scope: anywhere` attaches no condition at all, so
88
+ 1.0.0 behaviour is preserved exactly.
69
89
 
70
90
  ## Failure behaviour
71
91
 
package/index.js CHANGED
@@ -23,10 +23,17 @@ import {
23
23
  } from './lib/inventory.js'
24
24
  import { readSymbolDoc } from './lib/docs.js'
25
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'
26
33
 
27
34
  export const name = 'unreal-python-api'
28
35
 
29
- export const inject = ['tools', 'systemPrompt']
36
+ export const inject = ['tools', 'systemPrompt', 'workingDirectory']
30
37
 
31
38
  export const Config = z.object({
32
39
  docBaseUrl: z.string().default(DEFAULT_DOC_BASE_URL),
@@ -35,6 +42,9 @@ export const Config = z.object({
35
42
  maxResults: z.number().default(30),
36
43
  fetchTimeoutMs: z.number().default(30_000),
37
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),
38
48
  })
39
49
 
40
50
  /** Largest row count any tool returns, whatever a caller asks for. */
@@ -53,6 +63,28 @@ function clampLimit(requested, fallback) {
53
63
  return Math.min(value, ROW_CEILING)
54
64
  }
55
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
+
56
88
  /** Build a fresh symbol-row schema. @returns {object} Row schema. */
57
89
  function rowSchema() {
58
90
  return {
@@ -109,6 +141,31 @@ export function apply(ctx, config) {
109
141
  if (!Number.isFinite(fetchTimeoutMs) || fetchTimeoutMs < 1_000) throw new Error('fetchTimeoutMs must be at least 1000')
110
142
  if (!Number.isFinite(refreshHours) || refreshHours < 0) throw new Error('refreshHours must not be negative')
111
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
+ // Two tiers: the general lookup tools are offered in every workspace, the
160
+ // development tools (scaffold generation) only inside the configured scope.
161
+ // A condition must never fail step preparation, so the default scope attaches
162
+ // none and the general tier never carries one.
163
+ const registerGeneral = (definition) => ctx.tools.register(definition)
164
+ const registerDevelopment =
165
+ scope.scope === 'anywhere'
166
+ ? registerGeneral
167
+ : (definition) => ctx.tools.register(definition, { when: (context) => gate.admits(context.agent) })
168
+
112
169
  let loaded = null
113
170
  /**
114
171
  * Load the inventory once per process, re-reading it when a caller asks to refresh.
@@ -131,7 +188,7 @@ export function apply(ctx, config) {
131
188
  return loaded
132
189
  }
133
190
 
134
- ctx.tools.register(defineTool({
191
+ registerGeneral(defineTool({
135
192
  name: 'unreal_python_tools_list',
136
193
  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.',
137
194
  parameters: {
@@ -196,7 +253,7 @@ export function apply(ctx, config) {
196
253
  },
197
254
  }))
198
255
 
199
- ctx.tools.register(defineTool({
256
+ registerGeneral(defineTool({
200
257
  name: 'unreal_python_search',
201
258
  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.',
202
259
  parameters: {
@@ -247,7 +304,7 @@ export function apply(ctx, config) {
247
304
  },
248
305
  }))
249
306
 
250
- ctx.tools.register(defineTool({
307
+ registerGeneral(defineTool({
251
308
  name: 'unreal_python_syntax',
252
309
  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.',
253
310
  parameters: {
@@ -355,7 +412,7 @@ export function apply(ctx, config) {
355
412
  },
356
413
  }))
357
414
 
358
- ctx.tools.register(defineTool({
415
+ registerDevelopment(defineTool({
359
416
  name: 'unreal_python_tool_builder',
360
417
  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.',
361
418
  parameters: {
@@ -363,8 +420,7 @@ export function apply(ctx, config) {
363
420
  description: { type: 'string', required: true, description: 'What the toolset does; becomes its docstring.' },
364
421
  tools: {
365
422
  type: 'array',
366
- required: true,
367
- description: 'Tools to scaffold.',
423
+ description: 'Tools to scaffold. Omit it to describe a single tool with the tool_name fields below.',
368
424
  items: {
369
425
  type: 'object',
370
426
  additionalProperties: false,
@@ -456,7 +512,7 @@ export function apply(ctx, config) {
456
512
  registryImport: args.registry_import,
457
513
  baseClass: args.base_class,
458
514
  testModule: args.test_module,
459
- tools: args.tools,
515
+ tools: Array.isArray(args.tools) && args.tools.length > 0 ? args.tools : singleTool(args),
460
516
  },
461
517
  (symbol) => {
462
518
  const position = api.index.get(symbol)
@@ -476,7 +532,10 @@ export function apply(ctx, config) {
476
532
  ctx.systemPrompt.section({
477
533
  name: 'plugin:unreal-python-api',
478
534
  order: 350,
479
- text: `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
+ text:
536
+ scope.scope === 'anywhere'
537
+ ? `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}`
538
+ : `Unreal Python API (published 5.8 documentation): unreal_python_tools_list, unreal_python_search and unreal_python_syntax are available here; unreal_python_tool_builder is admitted only inside ${describeScope(scope)}, so it is absent when you work elsewhere. Documentation root: ${docBaseUrl}`,
480
539
  })
481
540
  }
482
541
  }
package/lib/builder.js CHANGED
@@ -114,6 +114,20 @@ export function schemaShape(declared) {
114
114
  throw new Error(`unsupported parameter type '${declared}' for this style; use str, int, float, bool, list[...], dict[...], or a dotted unreal type`)
115
115
  }
116
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
+
117
131
  /**
118
132
  * Build the schema value for one declared parameter, keeping its description.
119
133
  * @param {object} parameter Normalized parameter.
@@ -123,7 +137,7 @@ function parameterShape(parameter) {
123
137
  const shape = schemaShape(parameter.type)
124
138
  const description = String(parameter.description ?? '').trim()
125
139
  if (description !== '') shape.description = description
126
- else if (DOTTED.test(String(parameter.type ?? '').trim())) shape.description = `Unreal ${parameter.type} object path`
140
+ else if (isObjectType(parameter.type)) shape.description = `Unreal ${parameter.type} object path`
127
141
  return shape
128
142
  }
129
143
 
package/lib/scope.js ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Workspace scoping for the Unreal Python API tools.
3
+ *
4
+ * The published documentation is only useful while the agent works inside an
5
+ * Unreal project. This module decides, once per prepared step, whether the
6
+ * session's current working directory belongs to such a project (or to one of
7
+ * the configured roots), so the four tools can stay out of unrelated
8
+ * workspaces instead of being offered everywhere.
9
+ *
10
+ * The decision is pure apart from one directory listing per level of the
11
+ * working directory, and every check is cached briefly so a long session does
12
+ * not stat the disk on every step.
13
+ */
14
+ import { readdirSync } from 'node:fs'
15
+ import path from 'node:path'
16
+
17
+ /** Value used when no scope is configured: admit the tools in every workspace. */
18
+ export const DEFAULT_SCOPE = 'anywhere'
19
+
20
+ /** Supported scope modes. */
21
+ export const SCOPES = ['anywhere', 'unreal-project', 'workspaces']
22
+
23
+ /**
24
+ * Default project markers. An entry that starts with `.` is matched as a file
25
+ * extension (any file ending with it), anything else must match the file name
26
+ * exactly.
27
+ */
28
+ export const DEFAULT_PROJECT_MARKERS = ['.uproject']
29
+
30
+ const DEFAULT_MAX_DEPTH = 12
31
+
32
+ /**
33
+ * Normalize a directory for comparison: drop the Windows device prefix, unify
34
+ * separators, remove trailing separators, and lower-case the result so
35
+ * `D:\HOP TRENDY UNREAL\TDA` and `d:/hop trendy unreal/tda/` compare equal.
36
+ * @param {unknown} value
37
+ * @returns {string} the normalized path, or `''` when the input was not a path
38
+ */
39
+ export function normalizePath(value) {
40
+ if (typeof value !== 'string') return ''
41
+ const trimmed = value.trim()
42
+ if (trimmed === '') return ''
43
+ const withoutDevice = trimmed.replace(/^\\\\\?\\/, '').replace(/^\/\/\?\//, '')
44
+ return withoutDevice.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
45
+ }
46
+
47
+ /**
48
+ * Whether a directory is the root itself or sits below it. Segment-aware, so
49
+ * `D:/Project` never matches `D:/Project2`.
50
+ * @param {unknown} directory
51
+ * @param {unknown} root
52
+ * @returns {boolean}
53
+ */
54
+ export function isInside(directory, root) {
55
+ const dir = normalizePath(directory)
56
+ const base = normalizePath(root)
57
+ if (dir === '' || base === '') return false
58
+ return dir === base || dir.startsWith(`${base}/`)
59
+ }
60
+
61
+ /**
62
+ * Whether a directory sits inside any configured workspace root.
63
+ * @param {unknown} directory
64
+ * @param {readonly string[]} workspaces
65
+ * @returns {boolean}
66
+ */
67
+ export function inWorkspaces(directory, workspaces) {
68
+ if (!Array.isArray(workspaces) || workspaces.length === 0) return false
69
+ return workspaces.some((root) => isInside(directory, root))
70
+ }
71
+
72
+ /**
73
+ * Walk up from a directory and return the first ancestor that carries one of
74
+ * the project markers, or `undefined` when none is found.
75
+ * @param {unknown} directory
76
+ * @param {{ fs?: { readdirSync: (dir: string) => readonly string[] }, projectMarkers?: readonly string[], maxDepth?: number }} [options]
77
+ * @returns {string | undefined}
78
+ */
79
+ export function findProjectRoot(directory, options = {}) {
80
+ const fs = options.fs ?? { readdirSync }
81
+ const markers = (options.projectMarkers ?? DEFAULT_PROJECT_MARKERS).map((marker) => String(marker).toLowerCase())
82
+ const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH
83
+ if (typeof directory !== 'string' || directory.trim() === '') return undefined
84
+
85
+ let current = path.resolve(directory)
86
+ for (let depth = 0; depth <= maxDepth; depth += 1) {
87
+ let entries
88
+ try {
89
+ entries = fs.readdirSync(current)
90
+ } catch {
91
+ return undefined
92
+ }
93
+ const names = Array.from(entries, (entry) => String(entry).toLowerCase())
94
+ const found = markers.some((marker) =>
95
+ marker.startsWith('.') ? names.some((entry) => entry.endsWith(marker)) : names.includes(marker),
96
+ )
97
+ if (found) return current
98
+ const parent = path.dirname(current)
99
+ if (parent === current) return undefined
100
+ current = parent
101
+ }
102
+ return undefined
103
+ }
104
+
105
+ /**
106
+ * Validate and normalize the scope configuration.
107
+ * @param {{ scope?: unknown, workspaces?: unknown, projectMarkers?: unknown }} [input]
108
+ * @returns {{ scope: string, workspaces: string[], projectMarkers: string[] }}
109
+ */
110
+ export function resolveScope(input = {}) {
111
+ const scope = String(input.scope ?? DEFAULT_SCOPE).trim()
112
+ if (!SCOPES.includes(scope)) {
113
+ throw new Error(`unsupported scope ${JSON.stringify(scope)}; use one of ${SCOPES.join(', ')}`)
114
+ }
115
+ const workspaces = (Array.isArray(input.workspaces) ? input.workspaces : [])
116
+ .map((value) => String(value ?? '').trim())
117
+ .filter((value) => value !== '')
118
+ if (scope === 'workspaces' && workspaces.length === 0) {
119
+ throw new Error("scope 'workspaces' needs at least one entry in workspaces")
120
+ }
121
+ const configured = Array.isArray(input.projectMarkers) ? input.projectMarkers : []
122
+ const projectMarkers = (configured.length > 0 ? configured : DEFAULT_PROJECT_MARKERS)
123
+ .map((marker) => String(marker).trim())
124
+ .filter((marker) => marker !== '')
125
+ return { scope, workspaces, projectMarkers }
126
+ }
127
+
128
+ /**
129
+ * Human-readable description of an effective scope, used in the prompt
130
+ * section so the model knows why the tools may be missing.
131
+ * @param {{ scope: string, workspaces: string[], projectMarkers: string[] }} resolved
132
+ * @returns {string}
133
+ */
134
+ export function describeScope(resolved) {
135
+ if (!resolved || resolved.scope === 'anywhere') return 'every workspace'
136
+ if (resolved.scope === 'workspaces') return `a configured workspace (${resolved.workspaces.join(', ')})`
137
+ return `an Unreal project (a ${resolved.projectMarkers.join(' or ')} file in the working directory or one of its parents)`
138
+ }
139
+
140
+ /**
141
+ * Whether a directory is admitted by the effective scope.
142
+ * @param {unknown} directory
143
+ * @param {{ scope: string, workspaces: string[], projectMarkers: string[] }} resolved
144
+ * @param {{ fs?: { readdirSync: (dir: string) => readonly string[] }, maxDepth?: number }} [options]
145
+ * @returns {boolean}
146
+ */
147
+ export function inScope(directory, resolved, options = {}) {
148
+ if (!resolved || resolved.scope === 'anywhere') return true
149
+ if (typeof directory !== 'string' || directory.trim() === '') return false
150
+ if (resolved.scope === 'workspaces') return inWorkspaces(directory, resolved.workspaces)
151
+ return Boolean(
152
+ findProjectRoot(directory, {
153
+ fs: options.fs,
154
+ projectMarkers: resolved.projectMarkers,
155
+ maxDepth: options.maxDepth,
156
+ }),
157
+ )
158
+ }
159
+
160
+ /**
161
+ * Build a per-step gate that caches its answer briefly.
162
+ * @param {{
163
+ * resolved: { scope: string, workspaces: string[], projectMarkers: string[] },
164
+ * directoryOf: (agent: unknown) => string | undefined,
165
+ * fs?: { readdirSync: (dir: string) => readonly string[] },
166
+ * ttlMs?: number,
167
+ * now?: () => number,
168
+ * }} options
169
+ * @returns {{ scope: string, describe: () => string, admits: (agent: unknown) => boolean }}
170
+ */
171
+ export function createScopeGate(options) {
172
+ const { resolved, directoryOf, fs } = options
173
+ const ttlMs = options.ttlMs ?? 10_000
174
+ const now = options.now ?? (() => Date.now())
175
+ const cache = new Map()
176
+
177
+ return {
178
+ scope: resolved.scope,
179
+ describe: () => describeScope(resolved),
180
+ admits(agent) {
181
+ if (!resolved || resolved.scope === 'anywhere') return true
182
+ let directory
183
+ try {
184
+ directory = directoryOf(agent)
185
+ } catch {
186
+ // A tool activation condition must never fail step preparation.
187
+ return false
188
+ }
189
+ if (typeof directory !== 'string' || directory === '') return false
190
+ const key = normalizePath(directory)
191
+ const stamp = now()
192
+ const hit = cache.get(key)
193
+ if (hit !== undefined && stamp - hit.at < ttlMs) return hit.value
194
+ const value = inScope(directory, resolved, { fs })
195
+ cache.set(key, { value, at: stamp })
196
+ return value
197
+ },
198
+ }
199
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-unreal-python-api",
3
- "version": "1.0.0",
3
+ "version": "1.2.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
@@ -11,7 +11,7 @@ import { listChildren, loadInventory, pageUrl, resolveCacheDir, searchSymbols, s
11
11
  import { readSymbolDoc } from '../lib/docs.js'
12
12
  import { buildToolset } from '../lib/builder.js'
13
13
  import { execFileSync } from 'node:child_process'
14
- import { mkdtempSync, writeFileSync } from 'node:fs'
14
+ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
15
15
  import { tmpdir } from 'node:os'
16
16
  import { join } from 'node:path'
17
17
 
@@ -199,9 +199,137 @@ assert.ok(dsh.code.includes('additionalProperties: false'), 'DSH output schema i
199
199
  assert.ok(dsh.code.includes('export function registerTools(ctx)'), 'DSH module registers through ctx.tools')
200
200
  assert.ok(!dsh.code.includes('NotARealSymbol'), 'unverified symbol stays out of the DSH module')
201
201
  assert.ok(dsh.testCode.includes('registerTools'), 'DSH test exercises registration')
202
+ assert.ok(!/object path/.test(dsh.code), 'an undescribed primitive parameter gets no invented description')
203
+ assert.ok(!/object path/.test(built.code), 'the toolset module invents no description either')
202
204
 
203
205
  assert.throws(() => buildToolset(builderInput('nope'), resolveSymbol), /unsupported style/)
204
206
 
207
+ // --- workspace scope: the setting that makes the plugin workspace specific ----
208
+ import { createScopeGate, describeScope, inScope, resolveScope } from '../lib/scope.js'
209
+
210
+ const TDA = 'D:\\HOP TRENDY UNREAL\\Unreal Projects\\TDA'
211
+ const anywhere = resolveScope({ scope: 'anywhere' })
212
+ assert.equal(inScope('D:/anywhere/at/all', anywhere), true, 'anywhere admits every directory')
213
+ assert.equal(inScope(undefined, anywhere), true, 'anywhere admits even an unknown directory')
214
+
215
+ const listed = resolveScope({ scope: 'workspaces', workspaces: [TDA] })
216
+ assert.equal(inScope(join(TDA, 'Source'), listed), true, 'a subdirectory of a listed workspace is admitted')
217
+ assert.equal(inScope(TDA, listed), true, 'the workspace root is admitted')
218
+ assert.equal(inScope('D:\\HOP TRENDY UNREAL\\Unreal Projects\\TDA2', listed), false, 'a sibling with a shared prefix is not admitted')
219
+ assert.equal(inScope('D:\\HOP TRENDY UNREAL\\DSH Plugins', listed), false, 'an unrelated directory is not admitted')
220
+ assert.equal(inScope(undefined, listed), false, 'an unknown directory is not admitted')
221
+ assert.throws(() => resolveScope({ scope: 'workspaces' }), /needs at least one entry/, 'workspaces scope needs roots')
222
+ assert.throws(() => resolveScope({ scope: 'sometimes' }), /unsupported scope/, 'unknown scopes are rejected')
223
+
224
+ const projectRoot = mkdtempSync(join(tmpdir(), 'unreal-project-'))
225
+ writeFileSync(join(projectRoot, 'Smoke.uproject'), '{}')
226
+ const nested = join(projectRoot, 'Source', 'Smoke')
227
+ mkdirSync(nested, { recursive: true })
228
+ const projectScope = resolveScope({ scope: 'unreal-project' })
229
+ assert.equal(inScope(nested, projectScope), true, 'a directory inside an Unreal project is admitted')
230
+ assert.equal(inScope(projectRoot, projectScope), true, 'the project root is admitted')
231
+ assert.equal(inScope(mkdtempSync(join(tmpdir(), 'unreal-plain-')), projectScope), false, 'a directory without a .uproject is not admitted')
232
+ assert.equal(inScope(projectRoot, resolveScope({ scope: 'unreal-project', projectMarkers: ['MyPlugin.uplugin'] })), false, 'a configured marker list replaces the default')
233
+
234
+ let fakeDirectory = TDA
235
+ const gate = createScopeGate({ resolved: listed, directoryOf: () => fakeDirectory })
236
+ const agent = { session: { id: 'smoke' } }
237
+ assert.equal(gate.admits(agent), true, 'the gate admits the configured workspace')
238
+ fakeDirectory = 'D:\\somewhere\\else'
239
+ assert.equal(gate.admits(agent), false, 'the gate rejects another workspace')
240
+ const broken = createScopeGate({
241
+ resolved: listed,
242
+ directoryOf: () => {
243
+ throw new Error('no directory')
244
+ },
245
+ })
246
+ assert.equal(broken.admits(agent), false, 'a failing directory lookup rejects instead of throwing')
247
+ console.log(`scope: ${describeScope(projectScope)}`)
248
+
249
+ // --- the plugin module itself: exports and configuration defaults -------------
250
+ // The module imports the host-provided '@deepseek-ai/*' packages, which are not
251
+ // present on a bare checkout or in CI, so these checks run only where the harness
252
+ // is installed.
253
+ import { createRequire } from 'node:module'
254
+
255
+ const requireHost = createRequire(import.meta.url)
256
+
257
+ /** Whether the host packages this module imports can be resolved. */
258
+ function hostPackagesAvailable() {
259
+ try {
260
+ requireHost.resolve('@deepseek-ai/dsh-tools/package.json')
261
+ requireHost.resolve('@deepseek-ai/schemastery/package.json')
262
+ return true
263
+ } catch {
264
+ return false
265
+ }
266
+ }
267
+
268
+ const hostReady = hostPackagesAvailable()
269
+ if (!hostReady) {
270
+ console.log('host packages (@deepseek-ai/*) are not installed here; export, configuration and apply() checks skipped')
271
+ }
272
+
273
+ if (hostReady) {
274
+ const plugin = await import('../index.js')
275
+ assert.equal(plugin.name, 'unreal-python-api')
276
+ assert.deepEqual(plugin.inject, ['tools', 'systemPrompt', 'workingDirectory'])
277
+ assert.equal(typeof plugin.apply, 'function')
278
+ const defaults = plugin.Config({})
279
+ assert.equal(defaults.scope, 'anywhere', 'tools stay available everywhere by default')
280
+ assert.deepEqual(defaults.workspaces, [])
281
+ assert.deepEqual(defaults.projectMarkers, ['.uproject'])
282
+ const configured = plugin.Config({ scope: 'workspaces', workspaces: [TDA] })
283
+ assert.equal(configured.scope, 'workspaces')
284
+ assert.deepEqual(configured.workspaces, [TDA])
285
+ console.log('scope + configuration defaults: OK')
286
+
287
+ // --- apply(): the registration path, with and without a scope ----------------
288
+ function fakeContext(directoryOf) {
289
+ const registered = []
290
+ const sections = []
291
+ return {
292
+ registered,
293
+ sections,
294
+ tools: {
295
+ register(definition, options = {}) {
296
+ registered.push({ definition, options })
297
+ },
298
+ },
299
+ systemPrompt: {
300
+ section(section) {
301
+ sections.push(section)
302
+ return () => {}
303
+ },
304
+ },
305
+ workingDirectory: { get: directoryOf },
306
+ }
307
+ }
308
+
309
+ const openContext = fakeContext(() => TDA)
310
+ plugin.apply(openContext, plugin.Config({}))
311
+ assert.equal(openContext.registered.length, 4, 'default scope registers four tools')
312
+ assert.ok(openContext.registered.every((entry) => entry.options.when === undefined), 'default scope attaches no condition')
313
+ assert.equal(openContext.sections.length, 1, 'default scope registers one prompt section')
314
+
315
+ const scopedContext = fakeContext((session) => (session.id === 'inside' ? join(TDA, 'Source') : 'D:\\elsewhere'))
316
+ plugin.apply(scopedContext, plugin.Config({ scope: 'workspaces', workspaces: [TDA] }))
317
+ assert.equal(scopedContext.registered.length, 4, 'a scoped install still registers four tools')
318
+ const gated = scopedContext.registered.filter((entry) => typeof entry.options.when === 'function')
319
+ assert.equal(gated.length, 1, 'only the development tier is gated')
320
+ assert.equal(gated[0].definition.name, 'unreal_python_tool_builder', 'the development tier is the tool builder')
321
+ const general = scopedContext.registered
322
+ .filter((entry) => entry.options.when === undefined)
323
+ .map((entry) => entry.definition.name)
324
+ .sort()
325
+ assert.deepEqual(general, ['unreal_python_search', 'unreal_python_syntax', 'unreal_python_tools_list'], 'the general tier carries no condition')
326
+ const condition = gated[0].options.when
327
+ assert.equal(await condition({ agent: { session: { id: 'inside' } } }), true, 'the condition admits the configured workspace')
328
+ assert.equal(await condition({ agent: { session: { id: 'outside' } } }), false, 'the condition rejects another workspace')
329
+ assert.match(scopedContext.sections[0].text, /admitted only inside/, 'the prompt section says where the development tool applies')
330
+ console.log('apply(): general tier always on, development tier scoped: OK')
331
+ }
332
+
205
333
  // --- every generated artifact must parse in its own language -------------------
206
334
  console.log('parse checks:')
207
335
  assertParses('toolset module', built.code, 'py')