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/CHANGELOG.md +28 -0
- package/LICENSE +201 -0
- package/NOTICE +49 -0
- package/README.md +125 -2
- package/README.zh-CN.md +109 -0
- package/client.js +1658 -0
- package/cordis.patch.yml +6 -0
- package/docs/ARCHITECTURE.md +114 -0
- package/docs/CONTRACT.md +91 -0
- package/docs/VERIFICATION.md +57 -0
- package/icon.svg +23 -0
- package/index.js +218 -0
- package/lib/catalog.js +123 -0
- package/lib/clients.js +206 -0
- package/lib/engine.js +488 -0
- package/lib/http-endpoint.js +153 -0
- package/lib/provider-guides.json +502 -0
- package/lib/rea-catalog.json +671 -0
- package/lib/rea-clients.json +177 -0
- package/lib/routes.js +212 -0
- package/lib/runtime.js +299 -0
- package/lib/service.js +458 -0
- package/lib/settings.js +165 -0
- package/lib/tools.js +245 -0
- package/lib/util.js +312 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
package/lib/clients.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent-client integrations. REA already owns per-client registration for 43
|
|
3
|
+
* vendors, including backups and config formats; the console previews the exact
|
|
4
|
+
* plan and then asks REA to apply it, instead of writing those files itself.
|
|
5
|
+
*/
|
|
6
|
+
import { readJsonFileSync, ReaError, runCommand, shortError } from './util.js'
|
|
7
|
+
|
|
8
|
+
const DATA = readJsonFileSync(new URL('./rea-clients.json', import.meta.url), { clients: [] })
|
|
9
|
+
|
|
10
|
+
/** Clients that `rea setup --client <id>` knows, in documentation order. */
|
|
11
|
+
export const CLIENTS = Array.isArray(DATA.clients) ? DATA.clients : []
|
|
12
|
+
|
|
13
|
+
/** DSH itself is wired by this plugin, so its vendor registration is informational. */
|
|
14
|
+
export const BUILTIN_CLIENT_ID = 'dsh'
|
|
15
|
+
|
|
16
|
+
const REGISTERED_STATES = new Set(['registered', 'ok', 'healthy'])
|
|
17
|
+
const DETECTED_STATES = new Set(['registered', 'ok', 'healthy', 'missing', 'stale', 'invalid', 'drifted', 'outdated'])
|
|
18
|
+
|
|
19
|
+
function commandFor(runtime, args) {
|
|
20
|
+
return { file: runtime.node.path, args: [runtime.rea.script, ...args], env: undefined }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {object} options
|
|
25
|
+
* @param {() => Promise<{node: object, rea: object, env: object}>} options.resolveRuntime
|
|
26
|
+
*/
|
|
27
|
+
export class ClientManager {
|
|
28
|
+
#resolveRuntime
|
|
29
|
+
#logger
|
|
30
|
+
#doctorCache = null
|
|
31
|
+
#doctorAt = 0
|
|
32
|
+
#running = null
|
|
33
|
+
|
|
34
|
+
constructor(options) {
|
|
35
|
+
this.#resolveRuntime = options.resolveRuntime
|
|
36
|
+
this.#logger = options.logger ?? {}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Every supported client with its last known registration state. */
|
|
40
|
+
async list(options = {}) {
|
|
41
|
+
const doctor = await this.#doctor({ force: options.refresh === true }).catch(error => ({ error }))
|
|
42
|
+
const states = new Map()
|
|
43
|
+
if (doctor && !doctor.error) {
|
|
44
|
+
for (const registration of doctor.identity?.registrations ?? []) {
|
|
45
|
+
if (registration?.client) states.set(registration.client, registration)
|
|
46
|
+
}
|
|
47
|
+
for (const check of doctor.checks ?? []) {
|
|
48
|
+
if (typeof check?.name !== 'string' || !check.name.startsWith('registration:')) continue
|
|
49
|
+
const client = check.name.slice('registration:'.length)
|
|
50
|
+
if (!states.has(client) && check.ok === true) states.set(client, { client, state: 'registered' })
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
total: CLIENTS.length,
|
|
55
|
+
builtin: BUILTIN_CLIENT_ID,
|
|
56
|
+
detection: doctor?.error ? { ok: false, message: shortError(doctor.error) } : { ok: true, checkedAt: this.#doctorAt ? new Date(this.#doctorAt).toISOString() : null },
|
|
57
|
+
skill: doctor?.error ? null : (doctor.identity?.skill ?? null),
|
|
58
|
+
clients: CLIENTS.map(client => {
|
|
59
|
+
const registration = states.get(client.id)
|
|
60
|
+
const state = registration ? (REGISTERED_STATES.has(registration.state) ? 'registered' : DETECTED_STATES.has(registration.state) ? registration.state : 'unknown') : 'not-detected'
|
|
61
|
+
return {
|
|
62
|
+
id: client.id,
|
|
63
|
+
label: client.label,
|
|
64
|
+
builtin: client.id === BUILTIN_CLIENT_ID,
|
|
65
|
+
state,
|
|
66
|
+
detected: Boolean(registration),
|
|
67
|
+
configPath: registration?.config_path ?? null,
|
|
68
|
+
remediation: registration?.remediation ?? null,
|
|
69
|
+
}
|
|
70
|
+
}),
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** `rea doctor --json` with a short cache; also used by the provider panel. */
|
|
75
|
+
async #doctor(options = {}) {
|
|
76
|
+
const now = Date.now()
|
|
77
|
+
if (!options.force && this.#doctorCache && now - this.#doctorAt < 120_000) return this.#doctorCache
|
|
78
|
+
const runtime = await this.#resolveRuntime()
|
|
79
|
+
const result = await runCommand(runtime.node.path, [runtime.rea.script, 'doctor', '--json'], {
|
|
80
|
+
env: runtime.env,
|
|
81
|
+
timeoutMs: 180_000,
|
|
82
|
+
maxOutputBytes: 16 * 1024 * 1024,
|
|
83
|
+
})
|
|
84
|
+
let parsed = null
|
|
85
|
+
try {
|
|
86
|
+
parsed = parseJsonOutput(result.stdout)
|
|
87
|
+
} catch {
|
|
88
|
+
parsed = null
|
|
89
|
+
}
|
|
90
|
+
// `rea doctor` exits 1 for an unhealthy audit while still printing the
|
|
91
|
+
// complete JSON report; only a missing report is a failure here.
|
|
92
|
+
if (!parsed || typeof parsed !== 'object' || (!parsed.identity && !Array.isArray(parsed.checks))) {
|
|
93
|
+
throw new ReaError('doctor-failed', `rea doctor exited with code ${result.code} without a JSON report.`, {
|
|
94
|
+
output: (result.stderr || result.stdout).slice(-4000),
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
this.#doctorCache = parsed
|
|
98
|
+
this.#doctorAt = now
|
|
99
|
+
return parsed
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Full doctor result for the provider panel; the payload is large but complete. */
|
|
103
|
+
async doctor(options = {}) {
|
|
104
|
+
return this.#doctor(options)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Preview `rea setup` for one client without writing anything. */
|
|
108
|
+
async preview(clientId) {
|
|
109
|
+
return this.#setup(['--dry-run', '--json', '--client', assertClient(clientId)], 120_000)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Apply `rea setup` for one client. Callers must have shown the preview first. */
|
|
113
|
+
async register(clientId, options = {}) {
|
|
114
|
+
this.#assertIdle()
|
|
115
|
+
const id = assertClient(clientId)
|
|
116
|
+
this.#running = { client: id, startedAt: Date.now(), action: 'register' }
|
|
117
|
+
try {
|
|
118
|
+
const result = await this.#setup(['--yes', '--json', '--client', id], 300_000, options.signal)
|
|
119
|
+
this.#doctorCache = null
|
|
120
|
+
return result
|
|
121
|
+
} finally {
|
|
122
|
+
this.#running = null
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Apply `rea setup --all-detected`: this is what the "register detected" action runs. */
|
|
127
|
+
async registerDetected(options = {}) {
|
|
128
|
+
this.#assertIdle()
|
|
129
|
+
this.#running = { client: null, startedAt: Date.now(), action: 'register-detected' }
|
|
130
|
+
try {
|
|
131
|
+
const result = await this.#setup(['--yes', '--json', '--all-detected'], 600_000, options.signal)
|
|
132
|
+
this.#doctorCache = null
|
|
133
|
+
return result
|
|
134
|
+
} finally {
|
|
135
|
+
this.#running = null
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Install or refresh REA's bundled `reverse-engineer-anything` skill. */
|
|
140
|
+
async installSkill(options = {}) {
|
|
141
|
+
this.#assertIdle()
|
|
142
|
+
this.#running = { client: null, startedAt: Date.now(), action: 'skill' }
|
|
143
|
+
try {
|
|
144
|
+
const result = await this.#setup(['--yes', '--json', '--skill'], 300_000, options.signal)
|
|
145
|
+
this.#doctorCache = null
|
|
146
|
+
return result
|
|
147
|
+
} finally {
|
|
148
|
+
this.#running = null
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
get running() {
|
|
153
|
+
return this.#running
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
#assertIdle() {
|
|
157
|
+
if (this.#running) {
|
|
158
|
+
throw new ReaError('busy', 'Another setup or skill action is still running; wait for it to finish.')
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async #setup(args, timeoutMs, signal) {
|
|
163
|
+
const runtime = await this.#resolveRuntime()
|
|
164
|
+
const result = await runCommand(runtime.node.path, [runtime.rea.script, 'setup', ...args], {
|
|
165
|
+
env: runtime.env,
|
|
166
|
+
timeoutMs,
|
|
167
|
+
signal,
|
|
168
|
+
maxOutputBytes: 8 * 1024 * 1024,
|
|
169
|
+
})
|
|
170
|
+
const stdout = result.stdout.trim()
|
|
171
|
+
const parsed = stdout ? parseJsonOutput(stdout) : null
|
|
172
|
+
if (result.code !== 0) {
|
|
173
|
+
throw new ReaError('setup-failed', `rea setup exited with code ${result.code}.`, {
|
|
174
|
+
output: (result.stderr || stdout).slice(-6000),
|
|
175
|
+
plan: parsed,
|
|
176
|
+
})
|
|
177
|
+
}
|
|
178
|
+
return { ok: true, output: parsed ?? stdout, stderr: result.stderr.trim().slice(-4000) || null }
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function assertClient(clientId) {
|
|
183
|
+
const id = String(clientId ?? '').trim()
|
|
184
|
+
if (!CLIENTS.some(client => client.id === id)) {
|
|
185
|
+
throw new ReaError('unknown-client', `Unknown agent client: ${id || '(empty)'}.`)
|
|
186
|
+
}
|
|
187
|
+
return id
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function parseJsonOutput(stdout) {
|
|
191
|
+
const trimmed = stdout.trim()
|
|
192
|
+
try {
|
|
193
|
+
return JSON.parse(trimmed)
|
|
194
|
+
} catch {
|
|
195
|
+
const first = trimmed.indexOf('{')
|
|
196
|
+
const last = trimmed.lastIndexOf('}')
|
|
197
|
+
if (first >= 0 && last > first) {
|
|
198
|
+
try {
|
|
199
|
+
return JSON.parse(trimmed.slice(first, last + 1))
|
|
200
|
+
} catch {
|
|
201
|
+
// fall through
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return { text: trimmed.slice(0, 20_000) }
|
|
205
|
+
}
|
|
206
|
+
}
|
package/lib/engine.js
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal MCP stdio client for REA's `rea mcp` server.
|
|
3
|
+
*
|
|
4
|
+
* The plugin owns exactly one long-lived engine process. Tools registered on
|
|
5
|
+
* `ctx.tools` and the sidebar console go through the same serialized queue, so
|
|
6
|
+
* two callers cannot interleave work against REA's single stateful session.
|
|
7
|
+
*/
|
|
8
|
+
import { spawn } from 'node:child_process'
|
|
9
|
+
import { EventEmitter } from 'node:events'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
import { findReaPackage, findNodeRuntime } from './runtime.js'
|
|
12
|
+
import { engineEnvironment } from './settings.js'
|
|
13
|
+
import { ReaError, shortError } from './util.js'
|
|
14
|
+
|
|
15
|
+
const PROTOCOL_VERSION = '2025-06-18'
|
|
16
|
+
const CLIENT_INFO = { name: 'dsh-reverse-engine', version: '0.1.0' }
|
|
17
|
+
const MAX_LOG_LINES = 400
|
|
18
|
+
const MAX_ACTIVITY = 120
|
|
19
|
+
|
|
20
|
+
function extractText(content) {
|
|
21
|
+
if (!Array.isArray(content)) return ''
|
|
22
|
+
const parts = []
|
|
23
|
+
for (const block of content) {
|
|
24
|
+
if (!block || typeof block !== 'object') continue
|
|
25
|
+
if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
26
|
+
else if (block.type === 'image') parts.push(`[image ${block.mimeType ?? 'unknown'}, ${String(block.data ?? '').length} base64 chars]`)
|
|
27
|
+
else if (block.type === 'resource_link') parts.push(`[resource ${block.name ?? block.uri ?? 'unknown'}] ${block.uri ?? ''}`)
|
|
28
|
+
else if (block.type === 'resource') parts.push(`[embedded resource ${block.resource?.uri ?? 'unknown'}]`)
|
|
29
|
+
else if (block.type === 'audio') parts.push(`[audio ${block.mimeType ?? 'unknown'}]`)
|
|
30
|
+
else parts.push(JSON.stringify(block))
|
|
31
|
+
}
|
|
32
|
+
return parts.join('\n\n')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function normalizeResult(result) {
|
|
36
|
+
const content = Array.isArray(result?.content) ? result.content : []
|
|
37
|
+
return {
|
|
38
|
+
isError: result?.isError === true,
|
|
39
|
+
structuredContent: result?.structuredContent ?? null,
|
|
40
|
+
content,
|
|
41
|
+
text: extractText(content),
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class ReaEngine extends EventEmitter {
|
|
46
|
+
#settings
|
|
47
|
+
#logger
|
|
48
|
+
#dataDirectory
|
|
49
|
+
#status = 'stopped'
|
|
50
|
+
#child = null
|
|
51
|
+
#buffer = ''
|
|
52
|
+
#nextId = 0
|
|
53
|
+
#pending = new Map()
|
|
54
|
+
#queue = Promise.resolve()
|
|
55
|
+
#tools = []
|
|
56
|
+
#prompts = []
|
|
57
|
+
#stderr = []
|
|
58
|
+
#logs = []
|
|
59
|
+
#activity = []
|
|
60
|
+
#info = null
|
|
61
|
+
#runtime = null
|
|
62
|
+
#startedAt = null
|
|
63
|
+
#lastError = null
|
|
64
|
+
#starting = null
|
|
65
|
+
#stopping = false
|
|
66
|
+
|
|
67
|
+
constructor(options) {
|
|
68
|
+
super()
|
|
69
|
+
this.#settings = options.settings
|
|
70
|
+
this.#logger = options.logger ?? {}
|
|
71
|
+
this.#dataDirectory = options.dataDirectory
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Replace the settings snapshot used by the next start attempt. */
|
|
75
|
+
setSettings(settings) {
|
|
76
|
+
this.#settings = settings
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
get status() {
|
|
80
|
+
return this.#status
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
get tools() {
|
|
84
|
+
return this.#tools
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
get prompts() {
|
|
88
|
+
return this.#prompts
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
get runtime() {
|
|
92
|
+
return this.#runtime
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
get activity() {
|
|
96
|
+
return this.#activity
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
get logs() {
|
|
100
|
+
return this.#logs
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
get stderr() {
|
|
104
|
+
return this.#stderr
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
snapshot() {
|
|
108
|
+
return {
|
|
109
|
+
status: this.#status,
|
|
110
|
+
server: this.#info,
|
|
111
|
+
startedAt: this.#startedAt,
|
|
112
|
+
lastError: this.#lastError,
|
|
113
|
+
pid: this.#child?.pid ?? null,
|
|
114
|
+
toolCount: this.#tools.length,
|
|
115
|
+
promptCount: this.#prompts.length,
|
|
116
|
+
runtime: this.#runtime
|
|
117
|
+
? {
|
|
118
|
+
reaPackagePath: this.#runtime.rea.dir,
|
|
119
|
+
reaScript: this.#runtime.rea.script,
|
|
120
|
+
reaVersion: this.#runtime.rea.version,
|
|
121
|
+
reaSource: this.#runtime.rea.source,
|
|
122
|
+
nodePath: this.#runtime.node.path,
|
|
123
|
+
nodeVersion: this.#runtime.node.version,
|
|
124
|
+
nodeSource: this.#runtime.node.source,
|
|
125
|
+
}
|
|
126
|
+
: null,
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async start() {
|
|
131
|
+
if (this.#status === 'ready') return this.snapshot()
|
|
132
|
+
if (this.#starting) return this.#starting
|
|
133
|
+
this.#starting = this.#doStart().finally(() => {
|
|
134
|
+
this.#starting = null
|
|
135
|
+
})
|
|
136
|
+
return this.#starting
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async #doStart() {
|
|
140
|
+
this.#setStatus('starting')
|
|
141
|
+
this.#lastError = null
|
|
142
|
+
try {
|
|
143
|
+
const [node, rea] = await Promise.all([
|
|
144
|
+
findNodeRuntime(this.#settings),
|
|
145
|
+
findReaPackage(this.#settings, this.#dataDirectory),
|
|
146
|
+
])
|
|
147
|
+
this.#runtime = { node, rea }
|
|
148
|
+
const env = engineEnvironment(this.#settings)
|
|
149
|
+
env.ELECTRON_RUN_AS_NODE = '1'
|
|
150
|
+
if (!env.REA_MCP_TOOL_CATALOG_PROFILE) env.REA_MCP_TOOL_CATALOG_PROFILE = 'full'
|
|
151
|
+
if (!env.REA_LOG_LEVEL) env.REA_LOG_LEVEL = 'info'
|
|
152
|
+
|
|
153
|
+
const child = spawn(node.path, [rea.script, 'mcp'], {
|
|
154
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
155
|
+
env,
|
|
156
|
+
cwd: this.#dataDirectory,
|
|
157
|
+
windowsHide: true,
|
|
158
|
+
})
|
|
159
|
+
this.#child = child
|
|
160
|
+
child.stdout.setEncoding('utf8')
|
|
161
|
+
child.stderr.setEncoding('utf8')
|
|
162
|
+
child.stdout.on('data', chunk => this.#onStdout(chunk))
|
|
163
|
+
child.stderr.on('data', chunk => this.#onStderr(chunk))
|
|
164
|
+
child.once('error', error => this.#onExit(null, `Cannot start the REA engine: ${error.message}`))
|
|
165
|
+
child.once('exit', (code, signal) => this.#onExit(code, signal))
|
|
166
|
+
|
|
167
|
+
const init = await this.#request(
|
|
168
|
+
'initialize',
|
|
169
|
+
{ protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: CLIENT_INFO },
|
|
170
|
+
{ timeoutMs: this.#settings.startupTimeoutMs, skipReadyCheck: true, method: 'initialize' },
|
|
171
|
+
)
|
|
172
|
+
this.#info = {
|
|
173
|
+
name: init?.serverInfo?.name ?? 'rea',
|
|
174
|
+
version: init?.serverInfo?.version ?? rea.version,
|
|
175
|
+
title: init?.serverInfo?.title ?? null,
|
|
176
|
+
protocolVersion: init?.protocolVersion ?? null,
|
|
177
|
+
instructionsBytes: typeof init?.instructions === 'string' ? Buffer.byteLength(init.instructions, 'utf8') : 0,
|
|
178
|
+
capabilities: init?.capabilities ?? {},
|
|
179
|
+
}
|
|
180
|
+
this.#notify('notifications/initialized')
|
|
181
|
+
await this.refreshCatalog({ timeoutMs: this.#settings.startupTimeoutMs })
|
|
182
|
+
this.#startedAt = new Date().toISOString()
|
|
183
|
+
this.#setStatus('ready')
|
|
184
|
+
this.emit('ready', this.snapshot())
|
|
185
|
+
return this.snapshot()
|
|
186
|
+
} catch (error) {
|
|
187
|
+
this.#lastError = shortError(error)
|
|
188
|
+
this.#setStatus('error')
|
|
189
|
+
await this.#killChild()
|
|
190
|
+
this.emit('error', error)
|
|
191
|
+
throw error instanceof ReaError ? error : new ReaError('engine-start-failed', shortError(error))
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async stop() {
|
|
196
|
+
if (!this.#child) {
|
|
197
|
+
this.#setStatus('stopped')
|
|
198
|
+
return
|
|
199
|
+
}
|
|
200
|
+
this.#stopping = true
|
|
201
|
+
await this.#killChild()
|
|
202
|
+
this.#stopping = false
|
|
203
|
+
this.#setStatus('stopped')
|
|
204
|
+
this.#info = null
|
|
205
|
+
this.#startedAt = null
|
|
206
|
+
this.emit('stopped')
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async restart() {
|
|
210
|
+
await this.stop()
|
|
211
|
+
return this.start()
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async refreshCatalog(options = {}) {
|
|
215
|
+
const tools = await this.#listAll('tools/list', 'tools', options)
|
|
216
|
+
const prompts = await this.#listAll('prompts/list', 'prompts', options).catch(() => [])
|
|
217
|
+
this.#tools = tools
|
|
218
|
+
.filter(tool => tool && typeof tool.name === 'string')
|
|
219
|
+
.map(tool => ({
|
|
220
|
+
name: tool.name,
|
|
221
|
+
title: typeof tool.title === 'string' ? tool.title : null,
|
|
222
|
+
description: typeof tool.description === 'string' ? tool.description : '',
|
|
223
|
+
inputSchema: tool.inputSchema ?? { type: 'object', properties: {} },
|
|
224
|
+
annotations: tool.annotations ?? {},
|
|
225
|
+
}))
|
|
226
|
+
this.#prompts = prompts.map(prompt => ({
|
|
227
|
+
name: prompt.name,
|
|
228
|
+
title: prompt.title ?? null,
|
|
229
|
+
description: prompt.description ?? '',
|
|
230
|
+
arguments: Array.isArray(prompt.arguments) ? prompt.arguments : [],
|
|
231
|
+
}))
|
|
232
|
+
this.emit('catalog', { tools: this.#tools.length, prompts: this.#prompts.length })
|
|
233
|
+
return { tools: this.#tools, prompts: this.#prompts }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async #listAll(method, key, options) {
|
|
237
|
+
const items = []
|
|
238
|
+
let cursor
|
|
239
|
+
for (let page = 0; page < 100; page += 1) {
|
|
240
|
+
const result = await this.#request(method, cursor ? { cursor } : {}, { timeoutMs: options.timeoutMs ?? 60_000, method })
|
|
241
|
+
const batch = Array.isArray(result?.[key]) ? result[key] : []
|
|
242
|
+
items.push(...batch)
|
|
243
|
+
const next = result?.nextCursor
|
|
244
|
+
if (!next) break
|
|
245
|
+
cursor = next
|
|
246
|
+
}
|
|
247
|
+
return items
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Call one REA tool. Calls are serialized because `rea mcp` serves one stateful
|
|
252
|
+
* session with one active target.
|
|
253
|
+
*/
|
|
254
|
+
async callTool(name, args = {}, options = {}) {
|
|
255
|
+
if (this.#status !== 'ready') {
|
|
256
|
+
throw new ReaError('engine-not-ready', this.#lastError ? `The REA engine is not ready: ${this.#lastError}` : 'The REA engine is not ready yet.')
|
|
257
|
+
}
|
|
258
|
+
if (typeof name !== 'string' || !name.trim()) throw new ReaError('invalid-tool', 'A tool name is required.')
|
|
259
|
+
const tool = this.#tools.find(item => item.name === name)
|
|
260
|
+
if (!tool) throw new ReaError('unknown-tool', `REA does not advertise a tool named ${name}.`)
|
|
261
|
+
const timeoutMs = options.timeoutMs ?? this.#settings.toolCallTimeoutMs
|
|
262
|
+
const started = Date.now()
|
|
263
|
+
const result = this.#queue.then(() =>
|
|
264
|
+
this.#request('tools/call', { name, arguments: args && typeof args === 'object' ? args : {} }, { timeoutMs, signal: options.signal, method: `tools/call ${name}` }),
|
|
265
|
+
)
|
|
266
|
+
this.#queue = result.then(() => undefined, () => undefined)
|
|
267
|
+
try {
|
|
268
|
+
const value = normalizeResult(await result)
|
|
269
|
+
this.#recordActivity({ tool: name, ok: !value.isError, durationMs: Date.now() - started })
|
|
270
|
+
if (value.isError) {
|
|
271
|
+
throw new ReaError('tool-failed', value.text || `REA tool ${name} reported an error.`, {
|
|
272
|
+
tool: name,
|
|
273
|
+
structuredContent: value.structuredContent,
|
|
274
|
+
content: value.content,
|
|
275
|
+
})
|
|
276
|
+
}
|
|
277
|
+
return { ...value, durationMs: Date.now() - started }
|
|
278
|
+
} catch (error) {
|
|
279
|
+
if (!(error instanceof ReaError) || error.code !== 'tool-failed') {
|
|
280
|
+
this.#recordActivity({ tool: name, ok: false, durationMs: Date.now() - started, error: shortError(error) })
|
|
281
|
+
}
|
|
282
|
+
throw error
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async getPrompt(name, args = {}) {
|
|
287
|
+
if (this.#status !== 'ready') throw new ReaError('engine-not-ready', 'The REA engine is not ready yet.')
|
|
288
|
+
const result = await this.#request('prompts/get', { name, arguments: args }, { timeoutMs: 60_000, method: `prompts/get ${name}` })
|
|
289
|
+
return {
|
|
290
|
+
description: result?.description ?? '',
|
|
291
|
+
messages: Array.isArray(result?.messages) ? result.messages : [],
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
#recordActivity(entry) {
|
|
296
|
+
this.#activity.unshift({ at: new Date().toISOString(), ...entry })
|
|
297
|
+
if (this.#activity.length > MAX_ACTIVITY) this.#activity.length = MAX_ACTIVITY
|
|
298
|
+
this.emit('activity', this.#activity[0])
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
#setStatus(status) {
|
|
302
|
+
if (this.#status === status) return
|
|
303
|
+
this.#status = status
|
|
304
|
+
this.emit('status', status)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
#onStdout(chunk) {
|
|
308
|
+
this.#buffer += chunk
|
|
309
|
+
let index
|
|
310
|
+
while ((index = this.#buffer.indexOf('\n')) >= 0) {
|
|
311
|
+
const line = this.#buffer.slice(0, index).replace(/\r$/, '')
|
|
312
|
+
this.#buffer = this.#buffer.slice(index + 1)
|
|
313
|
+
if (!line.trim()) continue
|
|
314
|
+
let message
|
|
315
|
+
try {
|
|
316
|
+
message = JSON.parse(line)
|
|
317
|
+
} catch {
|
|
318
|
+
this.#pushStderr(`[stdout] ${line}`)
|
|
319
|
+
continue
|
|
320
|
+
}
|
|
321
|
+
this.#dispatch(message)
|
|
322
|
+
}
|
|
323
|
+
if (this.#buffer.length > 8 * 1024 * 1024) {
|
|
324
|
+
this.#pushStderr('[stdout] discarding an oversized unframed message')
|
|
325
|
+
this.#buffer = ''
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
#dispatch(message) {
|
|
330
|
+
if (message && typeof message === 'object' && message.id !== undefined && this.#pending.has(message.id)) {
|
|
331
|
+
const entry = this.#pending.get(message.id)
|
|
332
|
+
this.#pending.delete(message.id)
|
|
333
|
+
clearTimeout(entry.timer)
|
|
334
|
+
entry.signal?.removeEventListener?.('abort', entry.abort)
|
|
335
|
+
if (message.error) {
|
|
336
|
+
const error = new ReaError('engine-rpc-error', typeof message.error.message === 'string' ? message.error.message : 'REA returned a JSON-RPC error.', {
|
|
337
|
+
rpcCode: message.error.code,
|
|
338
|
+
data: message.error.data,
|
|
339
|
+
method: entry.method,
|
|
340
|
+
})
|
|
341
|
+
entry.reject(error)
|
|
342
|
+
} else {
|
|
343
|
+
entry.resolve(message.result)
|
|
344
|
+
}
|
|
345
|
+
return
|
|
346
|
+
}
|
|
347
|
+
if (message?.method === 'notifications/tools/list_changed') {
|
|
348
|
+
this.refreshCatalog({ timeoutMs: 60_000 }).catch(error => this.#pushStderr(`[catalog] refresh failed: ${shortError(error)}`))
|
|
349
|
+
return
|
|
350
|
+
}
|
|
351
|
+
if (message?.method && message.id !== undefined) {
|
|
352
|
+
// Server-initiated request. The console does not implement sampling or
|
|
353
|
+
// elicitation, so answer with an explicit method-not-found error.
|
|
354
|
+
this.#write({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: `Unsupported server request ${message.method}` } })
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
#write(message) {
|
|
359
|
+
if (!this.#child?.stdin?.writable) throw new ReaError('engine-stopped', 'The REA engine is not running.')
|
|
360
|
+
this.#child.stdin.write(`${JSON.stringify(message)}\n`)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
#notify(method, params) {
|
|
364
|
+
try {
|
|
365
|
+
this.#write({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) })
|
|
366
|
+
} catch {
|
|
367
|
+
// A stopped engine has no one to notify.
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
#request(method, params, options = {}) {
|
|
372
|
+
if (!this.#child?.stdin?.writable) return Promise.reject(new ReaError('engine-stopped', 'The REA engine is not running.'))
|
|
373
|
+
const id = ++this.#nextId
|
|
374
|
+
const timeoutMs = options.timeoutMs ?? 120_000
|
|
375
|
+
return new Promise((resolve, reject) => {
|
|
376
|
+
const timer = setTimeout(() => {
|
|
377
|
+
this.#pending.delete(id)
|
|
378
|
+
reject(new ReaError('engine-timeout', `REA did not answer ${method} within ${Math.round(timeoutMs / 1000)} seconds.`, { method }))
|
|
379
|
+
}, Math.max(1, timeoutMs))
|
|
380
|
+
timer.unref?.()
|
|
381
|
+
const entry = { resolve, reject, timer, method, signal: options.signal }
|
|
382
|
+
if (options.signal) {
|
|
383
|
+
if (options.signal.aborted) {
|
|
384
|
+
clearTimeout(timer)
|
|
385
|
+
reject(new ReaError('aborted', 'The request was cancelled.'))
|
|
386
|
+
return
|
|
387
|
+
}
|
|
388
|
+
entry.abort = () => {
|
|
389
|
+
this.#pending.delete(id)
|
|
390
|
+
clearTimeout(timer)
|
|
391
|
+
this.#notify('notifications/cancelled', { requestId: id, reason: 'cancelled by DeepSeek Harness' })
|
|
392
|
+
reject(new ReaError('aborted', 'The request was cancelled.'))
|
|
393
|
+
}
|
|
394
|
+
options.signal.addEventListener('abort', entry.abort, { once: true })
|
|
395
|
+
}
|
|
396
|
+
this.#pending.set(id, entry)
|
|
397
|
+
try {
|
|
398
|
+
this.#write({ jsonrpc: '2.0', id, method, params })
|
|
399
|
+
} catch (error) {
|
|
400
|
+
this.#pending.delete(id)
|
|
401
|
+
clearTimeout(timer)
|
|
402
|
+
reject(error instanceof ReaError ? error : new ReaError('engine-stopped', shortError(error)))
|
|
403
|
+
}
|
|
404
|
+
})
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
#onStderr(chunk) {
|
|
408
|
+
for (const line of chunk.split(/\r?\n/)) {
|
|
409
|
+
if (!line.trim()) continue
|
|
410
|
+
this.#pushStderr(line)
|
|
411
|
+
this.#ingestLog(line)
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
#pushStderr(line) {
|
|
416
|
+
this.#stderr.push({ at: new Date().toISOString(), line: line.slice(0, 2000) })
|
|
417
|
+
if (this.#stderr.length > MAX_LOG_LINES) this.#stderr.shift()
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
#ingestLog(line) {
|
|
421
|
+
let record
|
|
422
|
+
try {
|
|
423
|
+
record = JSON.parse(line)
|
|
424
|
+
} catch {
|
|
425
|
+
return
|
|
426
|
+
}
|
|
427
|
+
if (!record || typeof record !== 'object') return
|
|
428
|
+
const entry = {
|
|
429
|
+
at: record.time ? new Date(record.time).toISOString() : new Date().toISOString(),
|
|
430
|
+
level: typeof record.level === 'number' ? (record.level >= 50 ? 'error' : record.level >= 40 ? 'warn' : record.level >= 30 ? 'info' : 'debug') : String(record.level ?? 'info'),
|
|
431
|
+
message: typeof record.msg === 'string' ? record.msg.slice(0, 500) : '',
|
|
432
|
+
tool: typeof record.tool === 'string' ? record.tool : null,
|
|
433
|
+
durationMs: typeof record.durationMs === 'number' ? record.durationMs : null,
|
|
434
|
+
status: typeof record.status === 'string' ? record.status : null,
|
|
435
|
+
}
|
|
436
|
+
this.#logs.push(entry)
|
|
437
|
+
if (this.#logs.length > MAX_LOG_LINES) this.#logs.shift()
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
#onExit(code, detail) {
|
|
441
|
+
if (!this.#child) return
|
|
442
|
+
const child = this.#child
|
|
443
|
+
this.#child = null
|
|
444
|
+
for (const entry of this.#pending.values()) {
|
|
445
|
+
clearTimeout(entry.timer)
|
|
446
|
+
entry.signal?.removeEventListener?.('abort', entry.abort)
|
|
447
|
+
entry.reject(new ReaError('engine-stopped', 'The REA engine exited before answering.'))
|
|
448
|
+
}
|
|
449
|
+
this.#pending.clear()
|
|
450
|
+
if (this.#stopping) return
|
|
451
|
+
const reason = typeof detail === 'string' ? detail : `The REA engine exited (${detail ?? `code ${code}`}).`
|
|
452
|
+
this.#lastError = reason
|
|
453
|
+
this.#setStatus('error')
|
|
454
|
+
this.emit('crashed', { code, reason, pid: child?.pid ?? null })
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async #killChild() {
|
|
458
|
+
const child = this.#child
|
|
459
|
+
this.#child = null
|
|
460
|
+
if (!child) return
|
|
461
|
+
try {
|
|
462
|
+
child.stdin.end()
|
|
463
|
+
} catch {
|
|
464
|
+
// ignore
|
|
465
|
+
}
|
|
466
|
+
await new Promise(resolve => {
|
|
467
|
+
const timer = setTimeout(() => {
|
|
468
|
+
try {
|
|
469
|
+
child.kill('SIGKILL')
|
|
470
|
+
} catch {
|
|
471
|
+
/* ignore */
|
|
472
|
+
}
|
|
473
|
+
resolve()
|
|
474
|
+
}, 4_000)
|
|
475
|
+
timer.unref?.()
|
|
476
|
+
child.once('exit', () => {
|
|
477
|
+
clearTimeout(timer)
|
|
478
|
+
resolve()
|
|
479
|
+
})
|
|
480
|
+
try {
|
|
481
|
+
child.kill('SIGTERM')
|
|
482
|
+
} catch {
|
|
483
|
+
clearTimeout(timer)
|
|
484
|
+
resolve()
|
|
485
|
+
}
|
|
486
|
+
})
|
|
487
|
+
}
|
|
488
|
+
}
|