dsh-reverse-engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/service.js ADDED
@@ -0,0 +1,454 @@
1
+ /**
2
+ * Orchestration shared by the JSON routes and the agent tools: one engine, one
3
+ * settings store, one runtime installer, and one HTTP endpoint.
4
+ */
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import { ClientManager } from './clients.js'
9
+ import { familiesOf, familyOf, searchTools, schemaBytes, exposedToolNames } from './catalog.js'
10
+ import { ReaEngine } from './engine.js'
11
+ import { HttpEndpoint, isLoopback } from './http-endpoint.js'
12
+ import { engineEnvironment, normalizeSettings } from './settings.js'
13
+ import { findNodeRuntime, findReaPackage, inspectRuntime, installReaPackage, mcpCommand, REA_REQUIREMENT, versionNotice } from './runtime.js'
14
+ import { ReaError, readJsonFile, runCommand, shortError, text } from './util.js'
15
+
16
+ const CLI_CACHE_MS = 5 * 60_000
17
+ const CAPABILITY_CACHE_MS = 60_000
18
+
19
+ export class ReaService {
20
+ #logger
21
+ #store
22
+ #dataDirectory
23
+ #engine
24
+ #http
25
+ #clients
26
+ #runtime = null
27
+ #runtimeError = null
28
+ #install = { running: false, log: [], error: null, startedAt: null, finishedAt: null }
29
+ #capabilities = null
30
+ #capabilitiesAt = 0
31
+ #cli = null
32
+ #cliAt = 0
33
+ #clientsSummary = null
34
+ #onToolsChanged = null
35
+
36
+ constructor(options) {
37
+ this.#logger = options.logger ?? {}
38
+ this.#store = options.store
39
+ this.#dataDirectory = options.dataDirectory
40
+ this.#engine = new ReaEngine({
41
+ settings: this.settings,
42
+ logger: this.#logger,
43
+ dataDirectory: this.#dataDirectory,
44
+ })
45
+ this.#http = new HttpEndpoint({
46
+ settings: this.settings,
47
+ logger: this.#logger,
48
+ resolveRuntime: () => this.resolveRuntime(),
49
+ })
50
+ this.#clients = new ClientManager({
51
+ logger: this.#logger,
52
+ resolveRuntime: () => this.resolveRuntime(),
53
+ })
54
+ this.#engine.on('catalog', () => this.#onToolsChanged?.())
55
+ }
56
+
57
+ get settings() {
58
+ return this.#store.current
59
+ }
60
+
61
+ get engine() {
62
+ return this.#engine
63
+ }
64
+
65
+ get dataDirectory() {
66
+ return this.#dataDirectory
67
+ }
68
+
69
+ onToolsChanged(callback) {
70
+ this.#onToolsChanged = callback
71
+ }
72
+
73
+ async init() {
74
+ await this.#store.load()
75
+ this.#engine.setSettings(this.settings)
76
+ this.#http.setSettings(this.settings)
77
+ this.#runtime = await inspectRuntime(this.settings, this.#dataDirectory)
78
+ this.#runtimeError = this.#runtime.errors[0]?.message ?? null
79
+ this.#logger.info?.(`[dsh-reverse-engine] data: ${this.#dataDirectory}`)
80
+ if (this.settings.connectOnStart && !this.#runtime.errors.length) {
81
+ this.startEngine().catch(error => this.#logger.warn?.(`[dsh-reverse-engine] engine start failed: ${shortError(error)}`))
82
+ }
83
+ if (!this.#runtime.errors.length) {
84
+ this.clients().catch(error => this.#logger.warn?.(`[dsh-reverse-engine] client detection failed: ${shortError(error)}`))
85
+ }
86
+ }
87
+
88
+ /** Resolve the engine runtime for one-off commands (setup, doctor, capabilities). */
89
+ async resolveRuntime() {
90
+ const current = this.#engine.runtime
91
+ if (current && this.#engine.status === 'ready') {
92
+ return { ...current, env: engineEnvironment(this.settings) }
93
+ }
94
+ const [node, rea] = await Promise.all([
95
+ findNodeRuntime(this.settings),
96
+ findReaPackage(this.settings, this.#dataDirectory),
97
+ ])
98
+ this.#runtime = { node, rea, errors: [] }
99
+ return { node, rea, env: engineEnvironment(this.settings) }
100
+ }
101
+
102
+ async startEngine() {
103
+ return this.#engine.start()
104
+ }
105
+
106
+ async restartEngine() {
107
+ return this.#engine.restart()
108
+ }
109
+
110
+ async stopEngine() {
111
+ await this.#engine.stop()
112
+ }
113
+
114
+ async state() {
115
+ const settings = this.settings
116
+ const runtime = this.#runtime ?? { node: null, rea: null, errors: [] }
117
+ const clientsSummary = this.#clientsSummary
118
+ return {
119
+ ok: true,
120
+ engine: this.#engine.snapshot(),
121
+ runtime: {
122
+ requirement: REA_REQUIREMENT,
123
+ node: runtime.node
124
+ ? { path: runtime.node.path, version: runtime.node.version, source: runtime.node.source, supported: true }
125
+ : null,
126
+ rea: runtime.rea
127
+ ? { path: runtime.rea.dir, script: runtime.rea.script, version: runtime.rea.version, source: runtime.rea.source, notice: versionNotice(runtime.rea.version) }
128
+ : null,
129
+ errors: runtime.errors ?? [],
130
+ },
131
+ settings: this.publicSettings(),
132
+ catalog: {
133
+ tools: this.#engine.tools.length,
134
+ prompts: this.#engine.prompts.length,
135
+ families: familiesOf(this.#engine.tools),
136
+ exposed: this.exposedToolNames(),
137
+ exposedSchemaBytes: schemaBytes(this.#engine.tools, this.exposedToolNames()),
138
+ },
139
+ http: this.#http.snapshot(),
140
+ install: this.#installSnapshot(),
141
+ clients: clientsSummary,
142
+ installSkill: runtime.rea
143
+ ? {
144
+ target: path.join(process.env.DSH_AGENTS_HOME?.trim() || path.join(os.homedir(), '.agents'), 'skills', 'reverse-engineer-anything'),
145
+ installed: fs.existsSync(path.join(process.env.DSH_AGENTS_HOME?.trim() || path.join(os.homedir(), '.agents'), 'skills', 'reverse-engineer-anything')),
146
+ }
147
+ : null,
148
+ mcp: runtime.node && runtime.rea ? mcpCommand(runtime.node, runtime.rea) : null,
149
+ notices: await this.notices(runtime),
150
+ activity: this.#engine.activity.slice(0, 20),
151
+ logs: this.#engine.logs.slice(-40),
152
+ }
153
+ }
154
+
155
+ /** Settings safe to return to the browser: never include inherited process state. */
156
+ publicSettings() {
157
+ const settings = this.settings
158
+ return {
159
+ reaPackagePath: settings.reaPackagePath,
160
+ nodePath: settings.nodePath,
161
+ toolExposure: settings.toolExposure,
162
+ toolFamilies: settings.toolFamilies,
163
+ toolCallTimeoutMs: settings.toolCallTimeoutMs,
164
+ startupTimeoutMs: settings.startupTimeoutMs,
165
+ connectOnStart: settings.connectOnStart,
166
+ httpEnabled: settings.httpEnabled,
167
+ httpHost: settings.httpHost,
168
+ httpPort: settings.httpPort,
169
+ env: settings.env,
170
+ dataDirectory: settings.dataDirectory,
171
+ }
172
+ }
173
+
174
+ async notices(runtimeOverride) {
175
+ const runtime = runtimeOverride ?? this.#runtime ?? { errors: [] }
176
+ const notices = []
177
+ if (this.#runtimeError) notices.push({ level: 'error', code: 'runtime-missing', message: this.#runtimeError })
178
+ for (const error of runtime.errors ?? []) {
179
+ if (error.part === 'rea' && error.code === 'version-mismatch') notices.push({ level: 'warn', code: error.code, message: error.message })
180
+ }
181
+ if (this.#engine.status === 'error' && this.#engine.snapshot().lastError) {
182
+ notices.push({ level: 'error', code: 'engine-error', message: this.#engine.snapshot().lastError })
183
+ }
184
+ if (!isLoopback(this.settings.httpHost) && this.#http.snapshot().running) {
185
+ notices.push({ level: 'warn', code: 'http-public', message: 'The HTTP MCP endpoint is bound to a non-loopback address and has no authentication.' })
186
+ }
187
+ const patch = path.join(process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'), 'cordis.patch.yml')
188
+ try {
189
+ const content = fs.readFileSync(patch, 'utf8')
190
+ if (/id:\s*rea-mcp/.test(content) || /serverName:\s*rea\b/.test(content)) {
191
+ notices.push({
192
+ level: 'warn',
193
+ code: 'dsh-home-registration',
194
+ message: 'The DSH home patch already registers a "rea" MCP client (rea-mcp). This plugin also registers REA tools, so REA may appear twice; remove one registration to avoid two engine processes.',
195
+ })
196
+ }
197
+ } catch {
198
+ // No home patch is normal.
199
+ }
200
+ return notices
201
+ }
202
+
203
+ exposedToolNames() {
204
+ return exposedToolNames(this.#engine.tools, this.settings)
205
+ }
206
+
207
+ toolsPage(query = '', options = {}) {
208
+ const page = searchTools(this.#engine.tools, query, options)
209
+ return {
210
+ ...page,
211
+ families: familiesOf(this.#engine.tools),
212
+ }
213
+ }
214
+
215
+ tool(name) {
216
+ return this.#engine.tools.find(tool => tool.name === name) ?? null
217
+ }
218
+
219
+ families() {
220
+ return familiesOf(this.#engine.tools)
221
+ }
222
+
223
+ async callTool(name, args, options = {}) {
224
+ return this.#engine.callTool(name, args, options)
225
+ }
226
+
227
+ async getPrompt(name, args) {
228
+ return this.#engine.getPrompt(name, args)
229
+ }
230
+
231
+ prompts() {
232
+ return this.#engine.prompts
233
+ }
234
+
235
+ async updateSettings(patch) {
236
+ const previous = this.settings
237
+ const next = await this.#store.save(patch)
238
+ this.#engine.setSettings(next)
239
+ this.#http.setSettings(next)
240
+ const runtimeKeys = ['reaPackagePath', 'nodePath', 'env', 'startupTimeoutMs']
241
+ const runtimeChanged = runtimeKeys.some(key => JSON.stringify(previous[key]) !== JSON.stringify(next[key]))
242
+ const exposureChanged = previous.toolExposure !== next.toolExposure || JSON.stringify(previous.toolFamilies) !== JSON.stringify(next.toolFamilies)
243
+ const httpChanged = previous.httpEnabled !== next.httpEnabled || previous.httpHost !== next.httpHost || previous.httpPort !== next.httpPort || previous.connectOnStart !== next.connectOnStart
244
+
245
+ if (runtimeChanged) {
246
+ this.#runtime = await inspectRuntime(next, this.#dataDirectory)
247
+ this.#runtimeError = this.#runtime.errors[0]?.message ?? null
248
+ try {
249
+ await this.#engine.stop()
250
+ await this.#engine.start()
251
+ } catch (error) {
252
+ this.#logger.warn?.(`[dsh-reverse-engine] engine restart failed: ${shortError(error)}`)
253
+ }
254
+ }
255
+ if (exposureChanged) this.#onToolsChanged?.()
256
+ if (httpChanged) {
257
+ if (next.httpEnabled) {
258
+ this.#http.restart().catch(error => this.#logger.warn?.(`[dsh-reverse-engine] HTTP endpoint restart failed: ${shortError(error)}`))
259
+ } else {
260
+ this.#http.stop().catch(() => {})
261
+ }
262
+ }
263
+ return this.publicSettings()
264
+ }
265
+
266
+ async installRuntime() {
267
+ if (this.#install.running) throw new ReaError('busy', 'The REA runtime is already being installed.')
268
+ const pinned = '7.0.0'
269
+ this.#install = { running: true, log: [], error: null, startedAt: new Date().toISOString(), finishedAt: null }
270
+ const push = chunk => {
271
+ for (const line of String(chunk).split(/\r?\n/)) {
272
+ if (!line.trim()) continue
273
+ this.#install.log.push(line.slice(0, 500))
274
+ if (this.#install.log.length > 200) this.#install.log.shift()
275
+ }
276
+ }
277
+ this.#installRuntimeAsync(pinned, push).catch(() => {})
278
+ return this.#installSnapshot()
279
+ }
280
+
281
+ async #installRuntimeAsync(version, push) {
282
+ try {
283
+ const found = await installReaPackage(this.#dataDirectory, version, { onLog: push })
284
+ this.#install.log.push(`Installed ${found.dir} (${found.version}).`)
285
+ this.#install.running = false
286
+ this.#install.finishedAt = new Date().toISOString()
287
+ this.#runtime = await inspectRuntime(this.settings, this.#dataDirectory)
288
+ this.#runtimeError = this.#runtime.errors[0]?.message ?? null
289
+ await this.#engine.restart().catch(() => {})
290
+ } catch (error) {
291
+ this.#install.running = false
292
+ this.#install.error = shortError(error)
293
+ this.#install.finishedAt = new Date().toISOString()
294
+ this.#install.log.push(`FAILED: ${shortError(error)}`)
295
+ this.#logger.warn?.(`[dsh-reverse-engine] runtime install failed: ${shortError(error)}`)
296
+ }
297
+ }
298
+
299
+ #installSnapshot() {
300
+ return { ...this.#install, log: this.#install.log.slice(-80) }
301
+ }
302
+
303
+ async installSkill(options = {}) {
304
+ return this.#clients.installSkill(options)
305
+ }
306
+
307
+ async clients(options = {}) {
308
+ const list = await this.#clients.list(options)
309
+ this.#clientsSummary = {
310
+ total: list.total,
311
+ registered: list.clients.filter(client => client.state === 'registered').length,
312
+ detected: list.clients.filter(client => client.detected).length,
313
+ skill: list.skill,
314
+ error: list.detection.ok ? null : list.detection.message,
315
+ checkedAt: list.detection.checkedAt,
316
+ }
317
+ return list
318
+ }
319
+
320
+ async doctor(options = {}) {
321
+ const doctor = await this.#clients.doctor(options)
322
+ const registrations = doctor.identity?.registrations ?? []
323
+ return {
324
+ ok: doctor.healthy === true,
325
+ healthy: doctor.healthy === true,
326
+ environmentHealthy: doctor.environment_healthy === true,
327
+ checks: (doctor.checks ?? []).map(check => ({
328
+ name: check.name,
329
+ ok: check.ok === true,
330
+ classification: check.classification ?? null,
331
+ detail: check.detail ?? null,
332
+ remediation: check.remediation ?? null,
333
+ })),
334
+ skill: doctor.identity?.skill ?? null,
335
+ registrations,
336
+ catalog: doctor.identity?.catalog ?? null,
337
+ server: doctor.identity?.live_server ?? null,
338
+ }
339
+ }
340
+
341
+ async previewClient(clientId) {
342
+ return this.#clients.preview(clientId)
343
+ }
344
+
345
+ async registerClient(clientId, options = {}) {
346
+ const result = await this.#clients.register(clientId, options)
347
+ await this.#refreshAfterSetup()
348
+ return result
349
+ }
350
+
351
+ async registerDetected(options = {}) {
352
+ const result = await this.#clients.registerDetected(options)
353
+ await this.#refreshAfterSetup()
354
+ return result
355
+ }
356
+
357
+ async #refreshAfterSetup() {
358
+ this.#runtime = await inspectRuntime(this.settings, this.#dataDirectory)
359
+ }
360
+
361
+ async providers(options = {}) {
362
+ const now = Date.now()
363
+ if (!options.refresh && this.#capabilities && now - this.#capabilitiesAt < CAPABILITY_CACHE_MS) {
364
+ return { ...this.#capabilities, cached: true }
365
+ }
366
+ const runtime = await this.resolveRuntime()
367
+ const result = await runCommand(runtime.node.path, [runtime.rea.script, 'capabilities', '--json'], {
368
+ env: runtime.env,
369
+ timeoutMs: 180_000,
370
+ maxOutputBytes: 24 * 1024 * 1024,
371
+ })
372
+ if (result.code !== 0) {
373
+ throw new ReaError('capabilities-failed', `rea capabilities exited with code ${result.code}.`, { output: (result.stderr || result.stdout).slice(-4000) })
374
+ }
375
+ const parsed = JSON.parse(result.stdout.replace(/^\uFEFF/, '').trim())
376
+ const summary = {
377
+ ok: true,
378
+ selected: parsed.analysis_provider_binding?.provider_id ?? parsed.analysis_provider_binding ?? null,
379
+ candidates: (parsed.analysis_provider_candidates ?? []).map(candidate => ({
380
+ id: candidate.provider?.id ?? null,
381
+ name: candidate.provider?.name ?? null,
382
+ version: candidate.provider?.version ?? null,
383
+ status: candidate.availability?.status ?? null,
384
+ code: candidate.availability?.code ?? null,
385
+ reason: candidate.availability?.reason ?? null,
386
+ remediation: candidate.availability?.remediation ?? null,
387
+ selected: candidate.selected === true,
388
+ })),
389
+ providers: (parsed.capabilities ?? []).map(provider => ({
390
+ id: provider.provider?.id ?? null,
391
+ name: provider.provider?.name ?? null,
392
+ version: provider.provider?.version ?? null,
393
+ availableGroups: (provider.groups ?? []).filter(group => group.available === true).length,
394
+ totalGroups: (provider.groups ?? []).length,
395
+ })),
396
+ investigation: parsed.investigation ?? null,
397
+ server: parsed.server_identity ?? null,
398
+ cached: false,
399
+ checkedAt: new Date().toISOString(),
400
+ }
401
+ this.#capabilities = summary
402
+ this.#capabilitiesAt = now
403
+ return summary
404
+ }
405
+
406
+ async cliCatalog(options = {}) {
407
+ const now = Date.now()
408
+ if (!options.refresh && this.#cli && now - this.#cliAt < CLI_CACHE_MS) return { ...this.#cli, cached: true }
409
+ const runtime = await this.resolveRuntime()
410
+ const result = await runCommand(runtime.node.path, [runtime.rea.script, '--llms'], {
411
+ env: runtime.env,
412
+ timeoutMs: 60_000,
413
+ maxOutputBytes: 8 * 1024 * 1024,
414
+ })
415
+ if (result.code !== 0) throw new ReaError('cli-failed', `rea --llms exited with code ${result.code}.`)
416
+ const commands = []
417
+ for (const line of result.stdout.split(/\r?\n/)) {
418
+ const match = /^\|\s*`rea\s+([^`]+)`\s*\|\s*(.*?)\s*\|$/.exec(line)
419
+ if (!match) continue
420
+ const usage = match[1].trim()
421
+ const name = usage.split(/\s+/)[0]
422
+ if (!name) continue
423
+ commands.push({ name, usage: `rea ${usage}`, description: match[2] })
424
+ }
425
+ this.#cli = { commands, total: commands.length, checkedAt: new Date().toISOString() }
426
+ this.#cliAt = now
427
+ return this.#cli
428
+ }
429
+
430
+ async httpEndpoint(action) {
431
+ if (action === 'start') {
432
+ if (!this.settings.httpEnabled) await this.#store.save({ httpEnabled: true })
433
+ return this.#http.start()
434
+ }
435
+ if (action === 'stop') return this.#http.stop().then(() => this.#http.snapshot())
436
+ if (action === 'restart') return this.#http.restart()
437
+ const snapshot = this.#http.snapshot()
438
+ if (this.settings.httpEnabled && !snapshot.running) {
439
+ this.#http.start().catch(error => this.#logger.warn?.(`[dsh-reverse-engine] HTTP endpoint start failed: ${shortError(error)}`))
440
+ }
441
+ return snapshot
442
+ }
443
+
444
+ async shutdown() {
445
+ await this.#http.close().catch(() => {})
446
+ await this.#engine.stop().catch(() => {})
447
+ }
448
+
449
+ installSnapshot() {
450
+ return this.#installSnapshot()
451
+ }
452
+ }
453
+
454
+ export { normalizeSettings, familyOf, text, readJsonFile }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Persisted plugin settings. The DSH profile patch owns plugin activation, so
3
+ * mutable console settings live in the plugin data directory instead: users
4
+ * change them in the sidebar and they survive plugin upgrades.
5
+ */
6
+ import path from 'node:path'
7
+ import { clampInteger, readJsonFile, ReaError, resolveUserPath, writeJsonAtomic } from './util.js'
8
+
9
+ /**
10
+ * Tools registered directly on `ctx.tools` in the default `core` exposure. They
11
+ * cover the first hop of every investigation workflow; `rea_tools` searches the
12
+ * rest of the catalog and `rea_call` runs any tool, so the context cost stays
13
+ * bounded while every REA operation remains reachable.
14
+ */
15
+ export const CORE_TOOLS = [
16
+ 'binary_session',
17
+ 'open_binary',
18
+ 'close_binary',
19
+ 'inspect_artifact',
20
+ 'analyze_javascript_application',
21
+ 'analyze_function',
22
+ 'inspect_analysis_view',
23
+ 'list_procedures',
24
+ 'procedure_pseudo_code',
25
+ 'search_strings',
26
+ 'get_evidence_bundle',
27
+ ]
28
+
29
+ export const TOOL_EXPOSURES = ['core', 'families', 'all']
30
+
31
+ /** Environment names a user may set from the console. Provider paths and REA_* knobs only. */
32
+ export const ENV_ALLOWLIST = [
33
+ 'REA_ANALYSIS_PROVIDER',
34
+ 'REA_MCP_OUTPUT_SCHEMA_PROFILE',
35
+ 'REA_MCP_MAX_RESPONSE_BYTES',
36
+ 'REA_MCP_TOOL_CATALOG_PROFILE',
37
+ 'REA_MCP_TOOL_FAMILIES',
38
+ 'REA_GHIDRA_PROJECT_PATH',
39
+ 'REA_GHIDRA_CHECKPOINT_DIR',
40
+ 'REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS',
41
+ 'REA_KUNA_COMMAND',
42
+ 'REA_IDA_MCP_CONFIG',
43
+ 'REA_JADX_MCP_JAR',
44
+ 'REA_FRIDA_COMMAND',
45
+ 'REA_ANDROID_SDK_ROOT',
46
+ 'REA_APKTOOL_JAR',
47
+ 'REA_JEB_PATH',
48
+ 'GHIDRA_INSTALL_DIR',
49
+ 'HOPPER_LAUNCHER_PATH',
50
+ 'JAVA_HOME',
51
+ ]
52
+
53
+ export function defaultSettings(dataDirectory) {
54
+ return {
55
+ version: 1,
56
+ reaPackagePath: '',
57
+ nodePath: '',
58
+ toolExposure: 'core',
59
+ toolFamilies: [],
60
+ toolCallTimeoutMs: 450_000,
61
+ startupTimeoutMs: 120_000,
62
+ connectOnStart: true,
63
+ httpEnabled: false,
64
+ httpHost: '127.0.0.1',
65
+ httpPort: 0,
66
+ env: {},
67
+ dataDirectory,
68
+ }
69
+ }
70
+
71
+ function normalizeEnv(input) {
72
+ const env = {}
73
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return env
74
+ for (const [key, value] of Object.entries(input)) {
75
+ if (!ENV_ALLOWLIST.includes(key)) continue
76
+ if (typeof value !== 'string') continue
77
+ const trimmed = value.trim()
78
+ if (!trimmed) continue
79
+ env[key] = trimmed.slice(0, 4096)
80
+ }
81
+ return env
82
+ }
83
+
84
+ export function normalizeSettings(input, dataDirectory) {
85
+ const defaults = defaultSettings(dataDirectory)
86
+ const value = input && typeof input === 'object' && !Array.isArray(input) ? input : {}
87
+ const families = Array.isArray(value.toolFamilies)
88
+ ? [...new Set(value.toolFamilies.filter(item => typeof item === 'string' && /^[a-z][a-z-]{1,31}$/.test(item)))].slice(0, 32)
89
+ : []
90
+ return {
91
+ version: 1,
92
+ reaPackagePath: typeof value.reaPackagePath === 'string' ? value.reaPackagePath.trim().slice(0, 4096) : '',
93
+ nodePath: typeof value.nodePath === 'string' ? value.nodePath.trim().slice(0, 4096) : '',
94
+ toolExposure: TOOL_EXPOSURES.includes(value.toolExposure) ? value.toolExposure : 'core',
95
+ toolFamilies: families,
96
+ toolCallTimeoutMs: clampInteger(value.toolCallTimeoutMs, 5_000, 3_600_000, defaults.toolCallTimeoutMs),
97
+ startupTimeoutMs: clampInteger(value.startupTimeoutMs, 10_000, 600_000, defaults.startupTimeoutMs),
98
+ connectOnStart: value.connectOnStart !== false,
99
+ httpEnabled: value.httpEnabled === true,
100
+ httpHost: typeof value.httpHost === 'string' && value.httpHost.trim() ? value.httpHost.trim().slice(0, 255) : '127.0.0.1',
101
+ httpPort: clampInteger(value.httpPort, 0, 65_535, 0),
102
+ env: normalizeEnv(value.env),
103
+ dataDirectory,
104
+ }
105
+ }
106
+
107
+ /** The provider/runtime environment the engine child inherits in addition to the process environment. */
108
+ export function engineEnvironment(settings) {
109
+ const env = { ...process.env }
110
+ for (const [key, value] of Object.entries(settings.env ?? {})) env[key] = value
111
+ // The engine is a plain Node.js program. When the plugin runs inside Electron,
112
+ // ELECTRON_RUN_AS_NODE must be cleared for a separately resolved Node binary.
113
+ delete env.ELECTRON_RUN_AS_NODE
114
+ return env
115
+ }
116
+
117
+ export class SettingsStore {
118
+ #file
119
+ #dataDirectory
120
+ #logger
121
+ #value
122
+
123
+ constructor(dataDirectory, options = {}) {
124
+ this.#dataDirectory = dataDirectory
125
+ this.#file = path.join(dataDirectory, 'settings.json')
126
+ this.#logger = options.logger ?? {}
127
+ this.#value = null
128
+ }
129
+
130
+ get file() {
131
+ return this.#file
132
+ }
133
+
134
+ async load() {
135
+ const stored = await readJsonFile(this.#file, null)
136
+ this.#value = normalizeSettings(stored, this.#dataDirectory)
137
+ return this.#value
138
+ }
139
+
140
+ get current() {
141
+ if (!this.#value) this.#value = normalizeSettings(null, this.#dataDirectory)
142
+ return this.#value
143
+ }
144
+
145
+ async save(patch) {
146
+ const candidate = { ...this.current, ...patch }
147
+ // Never let the console move the data directory that stores this file.
148
+ candidate.dataDirectory = this.#dataDirectory
149
+ const next = normalizeSettings(candidate, this.#dataDirectory)
150
+ validatePaths(next)
151
+ await writeJsonAtomic(this.#file, next)
152
+ this.#value = next
153
+ this.#logger.info?.('[dsh-reverse-engine] settings saved')
154
+ return next
155
+ }
156
+ }
157
+
158
+ function validatePaths(settings) {
159
+ for (const key of ['reaPackagePath', 'nodePath']) {
160
+ if (!settings[key]) continue
161
+ const resolved = resolveUserPath(settings[key])
162
+ if (!resolved) throw new ReaError('invalid-path', `${key} is not a valid path.`)
163
+ settings[key] = resolved
164
+ }
165
+ }