dsh-unreal-python-api 1.0.0 → 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 CHANGED
@@ -1,5 +1,36 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.1 — 2026-11-30
4
+
5
+ - Fixed the test suite on a machine without the harness packages: the export,
6
+ configuration and `apply()` checks now run only when `@deepseek-ai/dsh-tools`
7
+ and `@deepseek-ai/schemastery` resolve, and the data-path checks always run.
8
+ `v1.1.0` was tagged but its publish run failed before reaching npm, so 1.1.1 is
9
+ the first published 1.1.x.
10
+
11
+ ## 1.1.0 — 2026-11-30
12
+
13
+ Workspace-specific activation.
14
+
15
+ - Added `scope` (`anywhere` | `unreal-project` | `workspaces`), `workspaces`
16
+ and `projectMarkers`. With a non-default scope the four tools are registered
17
+ behind a step-time activation condition, so they only appear in the model's
18
+ tool list inside the configured workspaces or an Unreal project.
19
+ - The system-prompt section now states where the tools are admitted instead of
20
+ implying they are always available.
21
+ - `lib/scope.js`: segment-aware, case-insensitive path matching, `.uproject`
22
+ ancestor detection with configurable markers, a ten-second per-directory
23
+ cache, and a gate that rejects rather than throws.
24
+ - Tests: workspace matching (including a shared-prefix sibling such as `TDA2`),
25
+ Unreal project detection in a temporary directory, a custom marker list, the
26
+ failing-lookup path, and the plugin module's exports plus configuration
27
+ defaults.
28
+ - Fixed: the tool builder advertised a single-tool shortcut (`tool_name`,
29
+ `tool_description`, `tool_parameters`, `tool_returns`, `tool_symbols`) that
30
+ the handler never read, and `tools` was required — so a one-tool call was
31
+ rejected before it ran. `tools` is now optional, the shortcut is implemented,
32
+ and a shortcut without `tool_description` fails with a plain message.
33
+
3
34
  ## 1.0.0 — 2026-11-30
4
35
 
5
36
  First release.
@@ -18,3 +49,5 @@ First release.
18
49
  reported instead of being written into the code.
19
50
  - Inventory downloaded from Epic's `objects.inv`, cached locally, refreshed every
20
51
  24 hours by default.
52
+ - Published from a `v1.0.0` tag through GitHub Actions with npm provenance;
53
+ `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,39 @@ 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 tools are 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
+ ### Workspace scoping
137
+
138
+ One profile install serves every workspace, so the four tools are offered
139
+ everywhere by default. Set `scope` to make them appear only where they are
140
+ useful:
141
+
142
+ | `scope` | Tools are offered when |
143
+ |---|---|
144
+ | `anywhere` (default) | always — unchanged from 1.0.0 |
145
+ | `unreal-project` | the session's working directory, or a parent, holds a `*.uproject` |
146
+ | `workspaces` | the working directory is inside one of the `workspaces` roots |
147
+
148
+ ```yaml
149
+ # the dsh-unreal-python-api row's config (profile cordis.patch.yml, or the
150
+ # plugin's settings panel in the GUI when it offers one)
151
+ config:
152
+ scope: unreal-project
153
+ # or name the roots yourself:
154
+ # scope: workspaces
155
+ # workspaces:
156
+ # - D:\HOP TRENDY UNREAL\Unreal Projects\TDA
157
+ ```
158
+
159
+ The check runs once per prepared step against the session's committed working
160
+ directory, is cached for ten seconds, and never throws: an unknown directory or
161
+ a failing lookup counts as not admitted. Path comparison is segment-aware and
162
+ case-insensitive, so `…\TDA` admits `…\TDA\Source` but not `…\TDA2`. Outside the
163
+ scope the tools are absent from the model's tool list entirely rather than
164
+ refused at call time, and the prompt section says where they apply.
124
165
 
125
166
  ## Publishing to the market
126
167
 
package/docs/DETAIL.md CHANGED
@@ -66,6 +66,21 @@ 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`; see the scope gate below. |
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
+ `scope` is enforced with the tool runtime's step-time activation condition —
76
+ `ctx.tools.register(definition, { when })`, where `when` receives the preparing
77
+ agent. The plugin reads the session's committed working directory through the
78
+ `workingDirectory` service (`ctx.workingDirectory.get(agent.session)`), so the
79
+ decision follows a directory change without restarting anything. Each directory
80
+ is checked at most once every ten seconds, and a lookup failure rejects that
81
+ step's admission instead of throwing, because a throwing condition fails step
82
+ preparation. The default `scope: anywhere` attaches no condition at all, so
83
+ 1.0.0 behaviour is preserved exactly.
69
84
 
70
85
  ## Failure behaviour
71
86
 
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,28 @@ 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
+ // 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
+
112
166
  let loaded = null
113
167
  /**
114
168
  * Load the inventory once per process, re-reading it when a caller asks to refresh.
@@ -131,7 +185,7 @@ export function apply(ctx, config) {
131
185
  return loaded
132
186
  }
133
187
 
134
- ctx.tools.register(defineTool({
188
+ register(defineTool({
135
189
  name: 'unreal_python_tools_list',
136
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.',
137
191
  parameters: {
@@ -196,7 +250,7 @@ export function apply(ctx, config) {
196
250
  },
197
251
  }))
198
252
 
199
- ctx.tools.register(defineTool({
253
+ register(defineTool({
200
254
  name: 'unreal_python_search',
201
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.',
202
256
  parameters: {
@@ -247,7 +301,7 @@ export function apply(ctx, config) {
247
301
  },
248
302
  }))
249
303
 
250
- ctx.tools.register(defineTool({
304
+ register(defineTool({
251
305
  name: 'unreal_python_syntax',
252
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.',
253
307
  parameters: {
@@ -355,7 +409,7 @@ export function apply(ctx, config) {
355
409
  },
356
410
  }))
357
411
 
358
- ctx.tools.register(defineTool({
412
+ register(defineTool({
359
413
  name: 'unreal_python_tool_builder',
360
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.',
361
415
  parameters: {
@@ -363,8 +417,7 @@ export function apply(ctx, config) {
363
417
  description: { type: 'string', required: true, description: 'What the toolset does; becomes its docstring.' },
364
418
  tools: {
365
419
  type: 'array',
366
- required: true,
367
- description: 'Tools to scaffold.',
420
+ description: 'Tools to scaffold. Omit it to describe a single tool with the tool_name fields below.',
368
421
  items: {
369
422
  type: 'object',
370
423
  additionalProperties: false,
@@ -456,7 +509,7 @@ export function apply(ctx, config) {
456
509
  registryImport: args.registry_import,
457
510
  baseClass: args.base_class,
458
511
  testModule: args.test_module,
459
- tools: args.tools,
512
+ tools: Array.isArray(args.tools) && args.tools.length > 0 ? args.tools : singleTool(args),
460
513
  },
461
514
  (symbol) => {
462
515
  const position = api.index.get(symbol)
@@ -476,7 +529,10 @@ export function apply(ctx, config) {
476
529
  ctx.systemPrompt.section({
477
530
  name: 'plugin:unreal-python-api',
478
531
  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}`,
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}`,
480
536
  })
481
537
  }
482
538
  }
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.1.1",
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,130 @@ 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
+ assert.ok(scopedContext.registered.every((entry) => typeof entry.options.when === 'function'), 'a scoped install attaches a condition')
319
+ const condition = scopedContext.registered[0].options.when
320
+ assert.equal(await condition({ agent: { session: { id: 'inside' } } }), true, 'the condition admits the configured workspace')
321
+ assert.equal(await condition({ agent: { session: { id: 'outside' } } }), false, 'the condition rejects another workspace')
322
+ assert.match(scopedContext.sections[0].text, /admitted only inside/, 'the prompt section says where the tools apply')
323
+ console.log('apply(): default and scoped registration: OK')
324
+ }
325
+
205
326
  // --- every generated artifact must parse in its own language -------------------
206
327
  console.log('parse checks:')
207
328
  assertParses('toolset module', built.code, 'py')