dsh-reverse-engine 0.0.0-stage → 0.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/lib/service.js ADDED
@@ -0,0 +1,458 @@
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
+ import { readJsonFileSync } from './util.js'
16
+
17
+ const CLI_CACHE_MS = 5 * 60_000
18
+ const CAPABILITY_CACHE_MS = 60_000
19
+ const PROVIDER_GUIDES = readJsonFileSync(new URL('./provider-guides.json', import.meta.url), { version: 1, providers: {} })
20
+
21
+ export class ReaService {
22
+ #logger
23
+ #store
24
+ #dataDirectory
25
+ #engine
26
+ #http
27
+ #clients
28
+ #runtime = null
29
+ #runtimeError = null
30
+ #install = { running: false, log: [], error: null, startedAt: null, finishedAt: null }
31
+ #capabilities = null
32
+ #capabilitiesAt = 0
33
+ #cli = null
34
+ #cliAt = 0
35
+ #clientsSummary = null
36
+ #onToolsChanged = null
37
+
38
+ constructor(options) {
39
+ this.#logger = options.logger ?? {}
40
+ this.#store = options.store
41
+ this.#dataDirectory = options.dataDirectory
42
+ this.#engine = new ReaEngine({
43
+ settings: this.settings,
44
+ logger: this.#logger,
45
+ dataDirectory: this.#dataDirectory,
46
+ })
47
+ this.#http = new HttpEndpoint({
48
+ settings: this.settings,
49
+ logger: this.#logger,
50
+ resolveRuntime: () => this.resolveRuntime(),
51
+ })
52
+ this.#clients = new ClientManager({
53
+ logger: this.#logger,
54
+ resolveRuntime: () => this.resolveRuntime(),
55
+ })
56
+ this.#engine.on('catalog', () => this.#onToolsChanged?.())
57
+ }
58
+
59
+ get settings() {
60
+ return this.#store.current
61
+ }
62
+
63
+ get engine() {
64
+ return this.#engine
65
+ }
66
+
67
+ get dataDirectory() {
68
+ return this.#dataDirectory
69
+ }
70
+
71
+ onToolsChanged(callback) {
72
+ this.#onToolsChanged = callback
73
+ }
74
+
75
+ async init() {
76
+ await this.#store.load()
77
+ this.#engine.setSettings(this.settings)
78
+ this.#http.setSettings(this.settings)
79
+ this.#runtime = await inspectRuntime(this.settings, this.#dataDirectory)
80
+ this.#runtimeError = this.#runtime.errors[0]?.message ?? null
81
+ this.#logger.info?.(`[dsh-reverse-engine] data: ${this.#dataDirectory}`)
82
+ if (this.settings.connectOnStart && !this.#runtime.errors.length) {
83
+ this.startEngine().catch(error => this.#logger.warn?.(`[dsh-reverse-engine] engine start failed: ${shortError(error)}`))
84
+ }
85
+ if (!this.#runtime.errors.length) {
86
+ this.clients().catch(error => this.#logger.warn?.(`[dsh-reverse-engine] client detection failed: ${shortError(error)}`))
87
+ }
88
+ }
89
+
90
+ /** Resolve the engine runtime for one-off commands (setup, doctor, capabilities). */
91
+ async resolveRuntime() {
92
+ const current = this.#engine.runtime
93
+ if (current && this.#engine.status === 'ready') {
94
+ return { ...current, env: engineEnvironment(this.settings) }
95
+ }
96
+ const [node, rea] = await Promise.all([
97
+ findNodeRuntime(this.settings),
98
+ findReaPackage(this.settings, this.#dataDirectory),
99
+ ])
100
+ this.#runtime = { node, rea, errors: [] }
101
+ return { node, rea, env: engineEnvironment(this.settings) }
102
+ }
103
+
104
+ async startEngine() {
105
+ return this.#engine.start()
106
+ }
107
+
108
+ async restartEngine() {
109
+ return this.#engine.restart()
110
+ }
111
+
112
+ async stopEngine() {
113
+ await this.#engine.stop()
114
+ }
115
+
116
+ async state() {
117
+ const settings = this.settings
118
+ const runtime = this.#runtime ?? { node: null, rea: null, errors: [] }
119
+ const clientsSummary = this.#clientsSummary
120
+ return {
121
+ ok: true,
122
+ engine: this.#engine.snapshot(),
123
+ runtime: {
124
+ requirement: REA_REQUIREMENT,
125
+ node: runtime.node
126
+ ? { path: runtime.node.path, version: runtime.node.version, source: runtime.node.source, supported: true }
127
+ : null,
128
+ rea: runtime.rea
129
+ ? { path: runtime.rea.dir, script: runtime.rea.script, version: runtime.rea.version, source: runtime.rea.source, notice: versionNotice(runtime.rea.version) }
130
+ : null,
131
+ errors: runtime.errors ?? [],
132
+ },
133
+ settings: this.publicSettings(),
134
+ catalog: {
135
+ tools: this.#engine.tools.length,
136
+ prompts: this.#engine.prompts.length,
137
+ families: familiesOf(this.#engine.tools),
138
+ exposed: this.exposedToolNames(),
139
+ exposedSchemaBytes: schemaBytes(this.#engine.tools, this.exposedToolNames()),
140
+ },
141
+ http: this.#http.snapshot(),
142
+ install: this.#installSnapshot(),
143
+ clients: clientsSummary,
144
+ installSkill: runtime.rea
145
+ ? {
146
+ target: path.join(process.env.DSH_AGENTS_HOME?.trim() || path.join(os.homedir(), '.agents'), 'skills', 'reverse-engineer-anything'),
147
+ installed: fs.existsSync(path.join(process.env.DSH_AGENTS_HOME?.trim() || path.join(os.homedir(), '.agents'), 'skills', 'reverse-engineer-anything')),
148
+ }
149
+ : null,
150
+ mcp: runtime.node && runtime.rea ? mcpCommand(runtime.node, runtime.rea) : null,
151
+ notices: await this.notices(runtime),
152
+ activity: this.#engine.activity.slice(0, 20),
153
+ logs: this.#engine.logs.slice(-40),
154
+ }
155
+ }
156
+
157
+ /** Settings safe to return to the browser: never include inherited process state. */
158
+ publicSettings() {
159
+ const settings = this.settings
160
+ return {
161
+ reaPackagePath: settings.reaPackagePath,
162
+ nodePath: settings.nodePath,
163
+ toolExposure: settings.toolExposure,
164
+ toolFamilies: settings.toolFamilies,
165
+ toolCallTimeoutMs: settings.toolCallTimeoutMs,
166
+ startupTimeoutMs: settings.startupTimeoutMs,
167
+ connectOnStart: settings.connectOnStart,
168
+ httpEnabled: settings.httpEnabled,
169
+ httpHost: settings.httpHost,
170
+ httpPort: settings.httpPort,
171
+ env: settings.env,
172
+ dataDirectory: settings.dataDirectory,
173
+ }
174
+ }
175
+
176
+ async notices(runtimeOverride) {
177
+ const runtime = runtimeOverride ?? this.#runtime ?? { errors: [] }
178
+ const notices = []
179
+ if (this.#runtimeError) notices.push({ level: 'error', code: 'runtime-missing', message: this.#runtimeError })
180
+ for (const error of runtime.errors ?? []) {
181
+ if (error.part === 'rea' && error.code === 'version-mismatch') notices.push({ level: 'warn', code: error.code, message: error.message })
182
+ }
183
+ if (this.#engine.status === 'error' && this.#engine.snapshot().lastError) {
184
+ notices.push({ level: 'error', code: 'engine-error', message: this.#engine.snapshot().lastError })
185
+ }
186
+ if (!isLoopback(this.settings.httpHost) && this.#http.snapshot().running) {
187
+ notices.push({ level: 'warn', code: 'http-public', message: 'The HTTP MCP endpoint is bound to a non-loopback address and has no authentication.' })
188
+ }
189
+ const patch = path.join(process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'), 'cordis.patch.yml')
190
+ try {
191
+ const content = fs.readFileSync(patch, 'utf8')
192
+ if (/id:\s*rea-mcp/.test(content) || /serverName:\s*rea\b/.test(content)) {
193
+ notices.push({
194
+ level: 'warn',
195
+ code: 'dsh-home-registration',
196
+ 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.',
197
+ })
198
+ }
199
+ } catch {
200
+ // No home patch is normal.
201
+ }
202
+ return notices
203
+ }
204
+
205
+ exposedToolNames() {
206
+ return exposedToolNames(this.#engine.tools, this.settings)
207
+ }
208
+
209
+ toolsPage(query = '', options = {}) {
210
+ const page = searchTools(this.#engine.tools, query, options)
211
+ return {
212
+ ...page,
213
+ families: familiesOf(this.#engine.tools),
214
+ }
215
+ }
216
+
217
+ tool(name) {
218
+ return this.#engine.tools.find(tool => tool.name === name) ?? null
219
+ }
220
+
221
+ families() {
222
+ return familiesOf(this.#engine.tools)
223
+ }
224
+
225
+ async callTool(name, args, options = {}) {
226
+ return this.#engine.callTool(name, args, options)
227
+ }
228
+
229
+ async getPrompt(name, args) {
230
+ return this.#engine.getPrompt(name, args)
231
+ }
232
+
233
+ prompts() {
234
+ return this.#engine.prompts
235
+ }
236
+
237
+ async updateSettings(patch) {
238
+ const previous = this.settings
239
+ const next = await this.#store.save(patch)
240
+ this.#engine.setSettings(next)
241
+ this.#http.setSettings(next)
242
+ const runtimeKeys = ['reaPackagePath', 'nodePath', 'env', 'startupTimeoutMs']
243
+ const runtimeChanged = runtimeKeys.some(key => JSON.stringify(previous[key]) !== JSON.stringify(next[key]))
244
+ const exposureChanged = previous.toolExposure !== next.toolExposure || JSON.stringify(previous.toolFamilies) !== JSON.stringify(next.toolFamilies)
245
+ const httpChanged = previous.httpEnabled !== next.httpEnabled || previous.httpHost !== next.httpHost || previous.httpPort !== next.httpPort || previous.connectOnStart !== next.connectOnStart
246
+
247
+ if (runtimeChanged) {
248
+ this.#runtime = await inspectRuntime(next, this.#dataDirectory)
249
+ this.#runtimeError = this.#runtime.errors[0]?.message ?? null
250
+ try {
251
+ await this.#engine.stop()
252
+ await this.#engine.start()
253
+ } catch (error) {
254
+ this.#logger.warn?.(`[dsh-reverse-engine] engine restart failed: ${shortError(error)}`)
255
+ }
256
+ }
257
+ if (exposureChanged) this.#onToolsChanged?.()
258
+ if (httpChanged) {
259
+ if (next.httpEnabled) {
260
+ this.#http.restart().catch(error => this.#logger.warn?.(`[dsh-reverse-engine] HTTP endpoint restart failed: ${shortError(error)}`))
261
+ } else {
262
+ this.#http.stop().catch(() => {})
263
+ }
264
+ }
265
+ return this.publicSettings()
266
+ }
267
+
268
+ async installRuntime() {
269
+ if (this.#install.running) throw new ReaError('busy', 'The REA runtime is already being installed.')
270
+ const pinned = '7.0.0'
271
+ this.#install = { running: true, log: [], error: null, startedAt: new Date().toISOString(), finishedAt: null }
272
+ const push = chunk => {
273
+ for (const line of String(chunk).split(/\r?\n/)) {
274
+ if (!line.trim()) continue
275
+ this.#install.log.push(line.slice(0, 500))
276
+ if (this.#install.log.length > 200) this.#install.log.shift()
277
+ }
278
+ }
279
+ this.#installRuntimeAsync(pinned, push).catch(() => {})
280
+ return this.#installSnapshot()
281
+ }
282
+
283
+ async #installRuntimeAsync(version, push) {
284
+ try {
285
+ const found = await installReaPackage(this.#dataDirectory, version, { onLog: push })
286
+ this.#install.log.push(`Installed ${found.dir} (${found.version}).`)
287
+ this.#install.running = false
288
+ this.#install.finishedAt = new Date().toISOString()
289
+ this.#runtime = await inspectRuntime(this.settings, this.#dataDirectory)
290
+ this.#runtimeError = this.#runtime.errors[0]?.message ?? null
291
+ await this.#engine.restart().catch(() => {})
292
+ } catch (error) {
293
+ this.#install.running = false
294
+ this.#install.error = shortError(error)
295
+ this.#install.finishedAt = new Date().toISOString()
296
+ this.#install.log.push(`FAILED: ${shortError(error)}`)
297
+ this.#logger.warn?.(`[dsh-reverse-engine] runtime install failed: ${shortError(error)}`)
298
+ }
299
+ }
300
+
301
+ #installSnapshot() {
302
+ return { ...this.#install, log: this.#install.log.slice(-80) }
303
+ }
304
+
305
+ async installSkill(options = {}) {
306
+ return this.#clients.installSkill(options)
307
+ }
308
+
309
+ async clients(options = {}) {
310
+ const list = await this.#clients.list(options)
311
+ this.#clientsSummary = {
312
+ total: list.total,
313
+ registered: list.clients.filter(client => client.state === 'registered').length,
314
+ detected: list.clients.filter(client => client.detected).length,
315
+ skill: list.skill,
316
+ error: list.detection.ok ? null : list.detection.message,
317
+ checkedAt: list.detection.checkedAt,
318
+ }
319
+ return list
320
+ }
321
+
322
+ async doctor(options = {}) {
323
+ const doctor = await this.#clients.doctor(options)
324
+ const registrations = doctor.identity?.registrations ?? []
325
+ return {
326
+ ok: doctor.healthy === true,
327
+ healthy: doctor.healthy === true,
328
+ environmentHealthy: doctor.environment_healthy === true,
329
+ checks: (doctor.checks ?? []).map(check => ({
330
+ name: check.name,
331
+ ok: check.ok === true,
332
+ classification: check.classification ?? null,
333
+ detail: check.detail ?? null,
334
+ remediation: check.remediation ?? null,
335
+ })),
336
+ skill: doctor.identity?.skill ?? null,
337
+ registrations,
338
+ catalog: doctor.identity?.catalog ?? null,
339
+ server: doctor.identity?.live_server ?? null,
340
+ }
341
+ }
342
+
343
+ async previewClient(clientId) {
344
+ return this.#clients.preview(clientId)
345
+ }
346
+
347
+ async registerClient(clientId, options = {}) {
348
+ const result = await this.#clients.register(clientId, options)
349
+ await this.#refreshAfterSetup()
350
+ return result
351
+ }
352
+
353
+ async registerDetected(options = {}) {
354
+ const result = await this.#clients.registerDetected(options)
355
+ await this.#refreshAfterSetup()
356
+ return result
357
+ }
358
+
359
+ async #refreshAfterSetup() {
360
+ this.#runtime = await inspectRuntime(this.settings, this.#dataDirectory)
361
+ }
362
+
363
+ async providers(options = {}) {
364
+ const now = Date.now()
365
+ if (!options.refresh && this.#capabilities && now - this.#capabilitiesAt < CAPABILITY_CACHE_MS) {
366
+ return { ...this.#capabilities, cached: true }
367
+ }
368
+ const runtime = await this.resolveRuntime()
369
+ const result = await runCommand(runtime.node.path, [runtime.rea.script, 'capabilities', '--json'], {
370
+ env: runtime.env,
371
+ timeoutMs: 180_000,
372
+ maxOutputBytes: 24 * 1024 * 1024,
373
+ })
374
+ if (result.code !== 0) {
375
+ throw new ReaError('capabilities-failed', `rea capabilities exited with code ${result.code}.`, { output: (result.stderr || result.stdout).slice(-4000) })
376
+ }
377
+ const parsed = JSON.parse(result.stdout.replace(/^\uFEFF/, '').trim())
378
+ const summary = {
379
+ ok: true,
380
+ selected: parsed.analysis_provider_binding?.provider_id ?? parsed.analysis_provider_binding ?? null,
381
+ candidates: (parsed.analysis_provider_candidates ?? []).map(candidate => ({
382
+ id: candidate.provider?.id ?? null,
383
+ name: candidate.provider?.name ?? null,
384
+ version: candidate.provider?.version ?? null,
385
+ status: candidate.availability?.status ?? null,
386
+ code: candidate.availability?.code ?? null,
387
+ reason: candidate.availability?.reason ?? null,
388
+ remediation: candidate.availability?.remediation ?? null,
389
+ selected: candidate.selected === true,
390
+ })),
391
+ providers: (parsed.capabilities ?? []).map(provider => ({
392
+ id: provider.provider?.id ?? null,
393
+ name: provider.provider?.name ?? null,
394
+ version: provider.provider?.version ?? null,
395
+ availableGroups: (provider.groups ?? []).filter(group => group.available === true).length,
396
+ totalGroups: (provider.groups ?? []).length,
397
+ })),
398
+ investigation: parsed.investigation ?? null,
399
+ server: parsed.server_identity ?? null,
400
+ guides: PROVIDER_GUIDES.providers ?? {},
401
+ guidesUpdatedAt: PROVIDER_GUIDES.updatedAt ?? null,
402
+ cached: false,
403
+ checkedAt: new Date().toISOString(),
404
+ }
405
+ this.#capabilities = summary
406
+ this.#capabilitiesAt = now
407
+ return summary
408
+ }
409
+
410
+ async cliCatalog(options = {}) {
411
+ const now = Date.now()
412
+ if (!options.refresh && this.#cli && now - this.#cliAt < CLI_CACHE_MS) return { ...this.#cli, cached: true }
413
+ const runtime = await this.resolveRuntime()
414
+ const result = await runCommand(runtime.node.path, [runtime.rea.script, '--llms'], {
415
+ env: runtime.env,
416
+ timeoutMs: 60_000,
417
+ maxOutputBytes: 8 * 1024 * 1024,
418
+ })
419
+ if (result.code !== 0) throw new ReaError('cli-failed', `rea --llms exited with code ${result.code}.`)
420
+ const commands = []
421
+ for (const line of result.stdout.split(/\r?\n/)) {
422
+ const match = /^\|\s*`rea\s+([^`]+)`\s*\|\s*(.*?)\s*\|$/.exec(line)
423
+ if (!match) continue
424
+ const usage = match[1].trim()
425
+ const name = usage.split(/\s+/)[0]
426
+ if (!name) continue
427
+ commands.push({ name, usage: `rea ${usage}`, description: match[2] })
428
+ }
429
+ this.#cli = { commands, total: commands.length, checkedAt: new Date().toISOString() }
430
+ this.#cliAt = now
431
+ return this.#cli
432
+ }
433
+
434
+ async httpEndpoint(action) {
435
+ if (action === 'start') {
436
+ if (!this.settings.httpEnabled) await this.#store.save({ httpEnabled: true })
437
+ return this.#http.start()
438
+ }
439
+ if (action === 'stop') return this.#http.stop().then(() => this.#http.snapshot())
440
+ if (action === 'restart') return this.#http.restart()
441
+ const snapshot = this.#http.snapshot()
442
+ if (this.settings.httpEnabled && !snapshot.running) {
443
+ this.#http.start().catch(error => this.#logger.warn?.(`[dsh-reverse-engine] HTTP endpoint start failed: ${shortError(error)}`))
444
+ }
445
+ return snapshot
446
+ }
447
+
448
+ async shutdown() {
449
+ await this.#http.close().catch(() => {})
450
+ await this.#engine.stop().catch(() => {})
451
+ }
452
+
453
+ installSnapshot() {
454
+ return this.#installSnapshot()
455
+ }
456
+ }
457
+
458
+ 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
+ }