@causyne/agent 1.20.16 → 1.20.18

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.
@@ -1,11 +1,19 @@
1
+ // Sovereign Reverse Engineering & Binary Inspection Capability.
2
+ //
3
+ // Native Causyne Agent reverse engineering suite backed by the headless sovereign
4
+ // engine substrate with zero-dependency static analysis fallbacks.
5
+ //
6
+ // Compliant with Causyne progressive disclosure (toolPacks.ts) and DTOC
7
+ // token-guarding offload (toolOutputStore.ts).
1
8
  import fs from 'node:fs';
2
9
  import fsp from 'node:fs/promises';
3
10
  import path from 'node:path';
4
11
  import { execFile } from 'node:child_process';
5
12
  import util from 'node:util';
6
13
  import { resolveUserPath } from '../utils/paths.js';
7
- import { ToolOutputStore } from './toolOutputStore.js';
14
+ import { ToolOutputStore, defaultToolOutputStore } from './toolOutputStore.js';
8
15
  import { isAutonomousToolContext } from '../approvalPolicy.js';
16
+ import { sovereignReverseHarness } from '../engines/reverseHarness.js';
9
17
  const execFileAsync = util.promisify(execFile);
10
18
  // ─────────────────────────────────────────────────────────────────────────────
11
19
  // NATIVE BINARY PARSERS (Pure Node.js Zero-Dependency Fallback)
@@ -16,165 +24,154 @@ function parseMachO(buffer) {
16
24
  const isLe = magic === 0xfeedfacf || magic === 0xfeedface;
17
25
  const isFat = magic === 0xcafebabe || magic === 0xbebafeca;
18
26
  if (isFat) {
19
- const numArchs = buffer.readUInt32BE(4);
20
- if (buffer.length >= 8 + 20) {
21
- const sliceOffset = buffer.readUInt32BE(8 + 8);
22
- if (sliceOffset > 0 && sliceOffset < buffer.length) {
23
- const sliceResult = parseMachO(buffer.subarray(sliceOffset));
24
- return {
25
- ...sliceResult,
26
- format: 'Mach-O',
27
- fileType: 'Universal / FAT Binary',
28
- mitigations: sliceResult.mitigations || { pie: true, nx: true, canary: true, aslr: true, codeSigned: true },
29
- metadata: { architecturesCount: numArchs, ...sliceResult.metadata }
30
- };
27
+ let architecture = 'Universal FAT (Mach-O)';
28
+ const nfat_arch = buffer.readUInt32BE(4);
29
+ if (buffer.length >= 8 + nfat_arch * 20) {
30
+ for (let i = 0; i < nfat_arch; i++) {
31
+ const offset = 8 + i * 20;
32
+ const cputype = buffer.readInt32BE(offset);
33
+ const sliceOffset = buffer.readUInt32BE(offset + 8);
34
+ const sliceSize = buffer.readUInt32BE(offset + 12);
35
+ if (sliceOffset + 8 <= buffer.length) {
36
+ const sliceBuf = buffer.subarray(sliceOffset, Math.min(sliceOffset + sliceSize, buffer.length));
37
+ if (sliceBuf.length >= 8) {
38
+ const inner = parseMachO(sliceBuf);
39
+ return {
40
+ format: 'Mach-O',
41
+ architecture: `Universal FAT (slice: ${inner.architecture || 'unknown'}, cputype: ${cputype})`,
42
+ is64Bit: inner.is64Bit ?? true,
43
+ byteOrder: inner.byteOrder ?? 'little-endian',
44
+ fileType: inner.fileType ?? 'Mach-O Universal Binary',
45
+ mitigations: inner.mitigations ?? { pie: true, nx: true, aslr: true, codeSigned: true }
46
+ };
47
+ }
48
+ }
31
49
  }
32
50
  }
33
51
  return {
34
52
  format: 'Mach-O',
35
- fileType: 'Universal / FAT Binary',
36
- architecture: 'Universal (x86_64 + arm64)',
37
- mitigations: {
38
- pie: true,
39
- nx: true,
40
- canary: true,
41
- aslr: true,
42
- codeSigned: true
43
- },
44
- metadata: { architecturesCount: numArchs }
53
+ architecture,
54
+ is64Bit: true,
55
+ byteOrder: 'big-endian',
56
+ fileType: 'Mach-O Universal Binary',
57
+ mitigations: { pie: true, nx: true, aslr: true, codeSigned: true }
45
58
  };
46
59
  }
47
60
  const cputype = isLe ? buffer.readInt32LE(4) : buffer.readInt32BE(4);
48
- let arch = 'unknown';
61
+ let architecture = 'unknown';
49
62
  if (cputype === 0x01000007)
50
- arch = 'x86_64';
63
+ architecture = 'x86_64';
51
64
  else if (cputype === 0x0100000c)
52
- arch = 'arm64';
65
+ architecture = 'arm64';
53
66
  else if (cputype === 7)
54
- arch = 'i386';
67
+ architecture = 'i386';
55
68
  else if (cputype === 12)
56
- arch = 'arm';
57
- const ncmds = isLe ? buffer.readUInt32LE(16) : buffer.readUInt32BE(16);
58
- const importedLibs = [];
59
- const sections = [];
60
- let codeSigned = false;
61
- let pie = false;
62
- let offset = is64 ? 32 : 28;
63
- for (let i = 0; i < ncmds && offset + 8 <= buffer.length; i++) {
64
- const cmd = isLe ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset);
65
- const cmdsize = isLe ? buffer.readUInt32LE(offset + 4) : buffer.readUInt32BE(offset + 4);
66
- if (cmdsize <= 0 || offset + cmdsize > buffer.length)
67
- break;
68
- // LC_LOAD_DYLIB = 0xc
69
- if (cmd === 0x0c || cmd === 0x1c || cmd === 0x8000001c) {
70
- const strOffset = isLe ? buffer.readUInt32LE(offset + 8) : buffer.readUInt32BE(offset + 8);
71
- if (strOffset < cmdsize) {
72
- const rawStr = buffer.toString('utf8', offset + strOffset, offset + cmdsize).replace(/\0.*$/, '');
73
- if (rawStr)
74
- importedLibs.push(path.basename(rawStr));
75
- }
76
- }
77
- // LC_CODE_SIGNATURE = 0x1d
78
- if (cmd === 0x1d)
79
- codeSigned = true;
80
- // LC_SEGMENT_64 = 0x19
81
- if (cmd === 0x19 && offset + 72 <= buffer.length) {
82
- const segname = buffer.toString('utf8', offset + 8, offset + 24).replace(/\0.*$/, '');
83
- if (segname)
84
- sections.push(segname);
85
- }
86
- offset += cmdsize;
87
- }
69
+ architecture = 'arm';
70
+ const filetypeInt = isLe ? buffer.readUInt32LE(12) : buffer.readUInt32BE(12);
71
+ let fileType = 'Mach-O Binary';
72
+ if (filetypeInt === 2)
73
+ fileType = 'Executable (MH_EXECUTE)';
74
+ else if (filetypeInt === 6)
75
+ fileType = 'Shared Library (MH_DYLIB)';
76
+ else if (filetypeInt === 8)
77
+ fileType = 'Bundle (MH_BUNDLE)';
88
78
  const flags = isLe ? buffer.readUInt32LE(24) : buffer.readUInt32BE(24);
89
- if (flags & 0x00200000)
90
- pie = true;
79
+ const pie = (flags & 0x200000) !== 0; // MH_PIE
91
80
  return {
92
81
  format: 'Mach-O',
93
- architecture: arch,
82
+ architecture,
94
83
  is64Bit: is64,
95
84
  byteOrder: isLe ? 'little-endian' : 'big-endian',
96
- sections: [...new Set(sections)],
97
- importedLibraries: importedLibs,
85
+ fileType,
98
86
  mitigations: {
99
87
  pie,
100
88
  nx: true,
101
- canary: true,
102
89
  aslr: pie,
103
- codeSigned
90
+ codeSigned: true
104
91
  }
105
92
  };
106
93
  }
107
94
  function parseElf(buffer) {
108
95
  const is64 = buffer[4] === 2;
109
96
  const isLe = buffer[5] === 1;
110
- const e_machine = isLe ? buffer.readUInt16LE(18) : buffer.readUInt16BE(18);
111
- let arch = 'unknown';
112
- if (e_machine === 0x3e)
113
- arch = 'x86_64';
114
- else if (e_machine === 0xb7)
115
- arch = 'aarch64 (arm64)';
116
- else if (e_machine === 0x03)
117
- arch = 'i386';
118
- else if (e_machine === 0x28)
119
- arch = 'arm';
120
- else if (e_machine === 0xf3)
121
- arch = 'riscv';
122
- const e_type = isLe ? buffer.readUInt16LE(16) : buffer.readUInt16BE(16);
123
- const pie = e_type === 3; // ET_DYN (shared object / PIE)
97
+ const readU16 = (off) => isLe ? buffer.readUInt16LE(off) : buffer.readUInt16BE(off);
98
+ const readU32 = (off) => isLe ? buffer.readUInt32LE(off) : buffer.readUInt32BE(off);
99
+ const eType = readU16(16);
100
+ let fileType = 'ELF Binary';
101
+ let pie = false;
102
+ if (eType === 2) {
103
+ fileType = 'Executable (ET_EXEC)';
104
+ pie = false;
105
+ }
106
+ else if (eType === 3) {
107
+ fileType = 'Shared Object / Dynamic Library (ET_DYN)';
108
+ pie = true;
109
+ }
110
+ const eMachine = readU16(18);
111
+ let architecture = 'unknown';
112
+ if (eMachine === 0x3e)
113
+ architecture = 'x86_64';
114
+ else if (eMachine === 0xb7)
115
+ architecture = 'aarch64 (ARM64)';
116
+ else if (eMachine === 0x03)
117
+ architecture = 'i386';
118
+ else if (eMachine === 0x28)
119
+ architecture = 'ARM (32-bit)';
120
+ else if (eMachine === 0xf3)
121
+ architecture = 'RISC-V';
124
122
  return {
125
123
  format: 'ELF',
126
- architecture: arch,
124
+ architecture,
127
125
  is64Bit: is64,
128
126
  byteOrder: isLe ? 'little-endian' : 'big-endian',
129
- fileType: e_type === 2 ? 'Executable' : e_type === 3 ? 'Shared Object / PIE' : 'Relocatable',
127
+ fileType,
130
128
  mitigations: {
131
129
  pie,
132
130
  nx: true,
133
- canary: true,
134
- relro: 'partial'
131
+ relro: pie ? 'full' : 'partial'
135
132
  }
136
133
  };
137
134
  }
138
135
  function parsePE(buffer) {
139
- if (buffer.length < 0x40)
136
+ if (buffer.length < 64)
140
137
  return { format: 'PE/COFF' };
141
138
  const peOffset = buffer.readUInt32LE(0x3c);
142
139
  if (peOffset + 24 > buffer.length)
143
140
  return { format: 'PE/COFF' };
144
- const magic = buffer.toString('utf8', peOffset, peOffset + 4);
145
- if (magic !== 'PE\0\0')
141
+ const peSig = buffer.toString('utf8', peOffset, peOffset + 4);
142
+ if (peSig !== 'PE\0\0')
146
143
  return { format: 'PE/COFF' };
147
144
  const machine = buffer.readUInt16LE(peOffset + 4);
148
- let arch = 'unknown';
145
+ let architecture = 'unknown';
149
146
  if (machine === 0x8664)
150
- arch = 'x86_64 (AMD64)';
151
- else if (machine === 0x014c)
152
- arch = 'i386 (x86)';
147
+ architecture = 'x86_64 (AMD64)';
153
148
  else if (machine === 0xaa64)
154
- arch = 'ARM64';
149
+ architecture = 'ARM64';
150
+ else if (machine === 0x14c)
151
+ architecture = 'i386 (x86)';
152
+ const optHeaderOffset = peOffset + 24;
155
153
  let is64 = false;
156
154
  let pie = false;
157
155
  let nx = false;
158
- const optHeaderOffset = peOffset + 24;
159
- if (optHeaderOffset + 2 <= buffer.length) {
160
- const optMagic = buffer.readUInt16LE(optHeaderOffset);
161
- is64 = optMagic === 0x20b; // PE32+
162
- const dllCharOffset = optHeaderOffset + (is64 ? 70 : 68);
156
+ if (optHeaderOffset + 72 <= buffer.length) {
157
+ const magic = buffer.readUInt16LE(optHeaderOffset);
158
+ is64 = magic === 0x20b; // PE32+
159
+ const dllCharOffset = optHeaderOffset + 70;
163
160
  if (dllCharOffset + 2 <= buffer.length) {
164
- const dllChars = buffer.readUInt16LE(dllCharOffset);
165
- pie = (dllChars & 0x0040) !== 0; // IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
166
- nx = (dllChars & 0x0100) !== 0; // IMAGE_DLLCHARACTERISTICS_NX_COMPAT
161
+ const dllCharacteristics = buffer.readUInt16LE(dllCharOffset);
162
+ pie = (dllCharacteristics & 0x0040) !== 0; // IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
163
+ nx = (dllCharacteristics & 0x0100) !== 0; // IMAGE_DLLCHARACTERISTICS_NX_COMPAT
167
164
  }
168
165
  }
169
166
  return {
170
167
  format: 'PE/COFF',
171
- architecture: arch,
168
+ architecture,
172
169
  is64Bit: is64,
173
170
  byteOrder: 'little-endian',
171
+ fileType: 'Windows Portable Executable',
174
172
  mitigations: {
175
173
  pie,
176
174
  nx,
177
- canary: true,
178
175
  aslr: pie
179
176
  }
180
177
  };
@@ -182,127 +179,142 @@ function parsePE(buffer) {
182
179
  function parseAsarHeader(buffer) {
183
180
  if (buffer.length < 16)
184
181
  return null;
182
+ const magic = buffer.readUInt32LE(0);
183
+ if (magic !== 4)
184
+ return null;
185
185
  const headerSize = buffer.readUInt32LE(12);
186
- if (headerSize <= 0 || 16 + headerSize > buffer.length)
186
+ if (16 + headerSize > buffer.length)
187
187
  return null;
188
- const jsonStr = buffer.toString('utf8', 16, 16 + headerSize);
189
188
  try {
190
- const parsed = JSON.parse(jsonStr);
191
- return { header: parsed, headerSize: 16 + headerSize };
189
+ const headerJson = buffer.toString('utf8', 16, 16 + headerSize);
190
+ const header = JSON.parse(headerJson);
191
+ return { headerSize: 16 + headerSize, header };
192
192
  }
193
193
  catch {
194
194
  return null;
195
195
  }
196
196
  }
197
- function listAsarFiles(entry, prefix = '') {
198
- const result = [];
199
- if ('files' in entry && entry.files) {
200
- for (const [name, child] of Object.entries(entry.files)) {
201
- const fullPath = prefix ? `${prefix}/${name}` : name;
202
- if ('files' in child && child.files) {
203
- result.push(...listAsarFiles(child, fullPath));
204
- }
205
- else if ('size' in child) {
206
- result.push({ path: fullPath, size: child.size ?? 0 });
207
- }
197
+ function listAsarFiles(dir, prefix = '') {
198
+ const list = [];
199
+ if (!dir || !dir.files)
200
+ return list;
201
+ for (const [name, entry] of Object.entries(dir.files)) {
202
+ const fullPath = prefix ? `${prefix}/${name}` : name;
203
+ if ('files' in entry && entry.files) {
204
+ list.push(...listAsarFiles(entry, fullPath));
205
+ }
206
+ else if ('size' in entry && typeof entry.size === 'number') {
207
+ list.push({ path: fullPath, size: entry.size });
208
208
  }
209
209
  }
210
- return result;
210
+ return list;
211
211
  }
212
212
  // ─────────────────────────────────────────────────────────────────────────────
213
- // SCRIPT DEOBFUSCATOR & SOURCEMAP HARVESTER
213
+ // JAVASCRIPT / BUNDLE SCRIPT DEOBFUSCATOR
214
214
  // ─────────────────────────────────────────────────────────────────────────────
215
215
  async function deobfuscateScript(filePath) {
216
216
  const code = await fsp.readFile(filePath, 'utf8');
217
217
  const sourcemapDetected = /\/\/# sourceMappingURL=/i.test(code) || /\/\*# sourceMappingURL=/i.test(code);
218
218
  const urlMatches = code.match(/https?:\/\/[a-zA-Z0-9./?=_%&:-]+/g) || [];
219
219
  const routeMatches = code.match(/['"`]\/(?:api|v[0-9]|auth|users|admin|graphql)[a-zA-Z0-9/_-]*['"`]/g) || [];
220
- const cleanRoutes = [...new Set([...urlMatches, ...routeMatches.map(r => r.replace(/['"`]/g, ''))])].slice(0, 50);
220
+ const cleanedRoutes = routeMatches.map(r => r.slice(1, -1));
221
+ const uniqueEndpoints = Array.from(new Set([...urlMatches, ...cleanedRoutes]));
222
+ const lines = code.split('\n').length;
223
+ const summary = `Script Analysis: ${lines} lines, ${code.length} characters. Sourcemap: ${sourcemapDetected ? 'Present' : 'None'}. Harvested ${uniqueEndpoints.length} endpoints.`;
221
224
  return {
222
- success: true,
223
225
  sourcemapDetected,
224
- extractedRoutes: cleanRoutes,
225
- summary: `Analyzed ${path.basename(filePath)} (${code.length} bytes). Sourcemaps detected: ${sourcemapDetected}. Discovered ${cleanRoutes.length} potential endpoints/routes.`
226
+ extractedRoutes: uniqueEndpoints.slice(0, 50),
227
+ summary
226
228
  };
227
229
  }
228
230
  // ─────────────────────────────────────────────────────────────────────────────
229
- // MAIN TOOL DEFINITION
231
+ // CANONICAL TOOL DEFINITION
230
232
  // ─────────────────────────────────────────────────────────────────────────────
231
233
  export const reverseEngineering = {
232
234
  schema: {
233
235
  name: 'reverse_engineering',
234
- description: 'Sovereign binary inspection, decompilation, bundle unpacking, and script deobfuscation engine. Inspects Mach-O, ELF, PE, WebAssembly, and Electron ASAR bundles with automated security mitigation analysis and token-safe DTOC disk offloading.',
236
+ description: 'Sovereign reverse engineering, binary triage, decompilation, bundle unpacking, and runtime tracing suite backed by headless MCP engine substrate.',
235
237
  parameters: {
236
238
  type: 'object',
237
239
  properties: {
238
240
  action: {
239
241
  type: 'string',
240
- enum: ['inspect', 'decompile', 'unpack', 'deobfuscate', 'trace', 'status'],
241
- description: 'The reverse engineering action to execute: inspect (binary/bundle structure & mitigations), decompile (function disassembly or decompilation), unpack (extract ASAR/APK/ZIP bundles), deobfuscate (extract routes and reconstruct sourcemaps), trace (dynamic hook generation), status (check local engine readiness).'
242
+ enum: ['inspect', 'decompile', 'unpack', 'deobfuscate', 'trace', 'status', 'engine_tool', 'list_tools'],
243
+ description: 'Reverse engineering action to perform.'
242
244
  },
243
245
  filePath: {
244
246
  type: 'string',
245
- description: 'Absolute or relative path to the target binary, application bundle, or script.'
247
+ description: 'Absolute or workspace-relative path to target binary, bundle, or script.'
248
+ },
249
+ target: {
250
+ type: 'string',
251
+ description: 'Process name, function symbol, or bundle resource identifier.'
246
252
  },
247
253
  outputDir: {
248
254
  type: 'string',
249
- description: 'Destination directory for unpacked bundles or extracted assets.'
255
+ description: 'Target extraction directory for bundle unpacking.'
250
256
  },
251
257
  functionName: {
252
258
  type: 'string',
253
- description: 'Name of the function or symbol to decompile/disassemble.'
259
+ description: 'Specific function symbol to decompile or disassemble.'
254
260
  },
255
261
  address: {
256
262
  type: 'string',
257
- description: 'Hex virtual address (e.g., 0x100003f20) to inspect or decompile.'
263
+ description: 'Hexadecimal memory address (e.g. "0x100003fa0") to inspect or decompile.'
258
264
  },
259
265
  engine: {
260
266
  type: 'string',
261
267
  enum: ['auto', 'ghidra', 'rizin', 'hopper', 'native'],
262
- description: 'Decompilation engine preference. Defaults to auto.'
268
+ description: 'Decompiler engine preference (default: auto).'
263
269
  },
264
270
  detail: {
265
271
  type: 'string',
266
272
  enum: ['summary', 'symbols', 'headers', 'mitigations', 'full'],
267
- description: 'Level of detail for binary inspection.'
273
+ description: 'Level of analytical detail.'
268
274
  },
269
275
  listOnly: {
270
276
  type: 'boolean',
271
- description: 'When true, unpack lists bundle entries without extracting them to disk.'
277
+ description: 'When unpacking, list container manifest contents without extracting files to disk.'
272
278
  },
273
279
  script: {
274
280
  type: 'string',
275
- description: 'Hook script or instrumentation code for runtime tracing.'
281
+ description: 'Custom instrumentation or tracer hook script.'
282
+ },
283
+ toolName: {
284
+ type: 'string',
285
+ description: 'Specific engine tool name to execute when action is "engine_tool".'
286
+ },
287
+ toolArgs: {
288
+ type: 'object',
289
+ description: 'Arguments payload for engine_tool.'
276
290
  }
277
291
  },
278
292
  required: ['action']
279
293
  }
280
294
  },
281
- async execute(args, sandbox = {}) {
282
- const action = String(args['action'] || 'inspect');
295
+ async execute(args, context = {}) {
296
+ const action = String(args['action'] || 'status');
283
297
  const rawPath = typeof args['filePath'] === 'string' ? args['filePath'] : undefined;
284
298
  const outputDir = typeof args['outputDir'] === 'string' ? args['outputDir'] : undefined;
285
299
  const functionName = typeof args['functionName'] === 'string' ? args['functionName'] : undefined;
286
300
  const address = typeof args['address'] === 'string' ? args['address'] : undefined;
287
- const engine = (typeof args['engine'] === 'string' ? args['engine'] : 'auto');
288
- const detail = (typeof args['detail'] === 'string' ? args['detail'] : 'summary');
289
- const listOnly = args['listOnly'] === true;
290
- const workspaceDir = (Array.isArray(sandbox['workspacePaths']) && sandbox['workspacePaths'][0])
291
- ? String(sandbox['workspacePaths'][0])
292
- : process.cwd();
293
- const outputStore = new ToolOutputStore();
294
- const sessionId = typeof sandbox['sessionId'] === 'string' ? sandbox['sessionId'] : 're_session';
301
+ const engine = typeof args['engine'] === 'string' ? args['engine'] : 'auto';
302
+ const detail = typeof args['detail'] === 'string' ? args['detail'] : 'summary';
303
+ const listOnly = Boolean(args['listOnly']);
304
+ const workspaceDir = context.workspaceDir || process.cwd();
305
+ const sessionId = context.sessionId || 're_session';
306
+ const outputStore = defaultToolOutputStore;
295
307
  const callId = `re_${Date.now()}`;
296
308
  // ── ACTION: STATUS ────────────────────────────────────────────────────
297
309
  if (action === 'status') {
298
310
  const engines = {};
299
- const checkCmd = async (bin) => {
311
+ const checkCmd = async (cmd) => {
300
312
  try {
301
- const res = await execFileAsync('which', [bin]);
302
- return { available: true, path: res.stdout.trim() };
313
+ await execFileAsync('which', [cmd]);
314
+ return true;
303
315
  }
304
316
  catch {
305
- return { available: false };
317
+ return false;
306
318
  }
307
319
  };
308
320
  engines['otool'] = await checkCmd('otool');
@@ -312,11 +324,15 @@ export const reverseEngineering = {
312
324
  engines['ghidra'] = await checkCmd('analyzeHeadless');
313
325
  engines['rizin'] = await checkCmd('rizin');
314
326
  engines['frida'] = await checkCmd('frida');
327
+ const engineAvailable = await sovereignReverseHarness.isAvailable();
328
+ const toolList = engineAvailable ? await sovereignReverseHarness.listTools() : [];
315
329
  return {
316
330
  success: true,
317
331
  action: 'status',
318
332
  platform: process.platform,
319
333
  architecture: process.arch,
334
+ engineAvailable,
335
+ specializedEngineToolsCount: toolList.length,
320
336
  installedEngines: engines,
321
337
  capabilities: [
322
338
  'Mach-O Universal / FAT & 64-bit triage',
@@ -324,10 +340,43 @@ export const reverseEngineering = {
324
340
  'PE/COFF Windows binary mitigation checks',
325
341
  'Electron ASAR pickle header inspection & extraction',
326
342
  'JavaScript sourcemap recovery and route harvesting',
327
- 'Dynamic Frida hook script synthesis'
343
+ 'Dynamic runtime tracing and API observation',
344
+ 'Headless MCP engine with 229 specialized reverse engineering tools'
328
345
  ]
329
346
  };
330
347
  }
348
+ // ── ACTION: LIST_TOOLS ────────────────────────────────────────────────
349
+ if (action === 'list_tools') {
350
+ const tools = await sovereignReverseHarness.listTools();
351
+ return {
352
+ success: true,
353
+ action: 'list_tools',
354
+ totalTools: tools.length,
355
+ tools
356
+ };
357
+ }
358
+ // ── ACTION: ENGINE_TOOL ───────────────────────────────────────────────
359
+ if (action === 'engine_tool') {
360
+ const toolName = typeof args['toolName'] === 'string' ? args['toolName'] : '';
361
+ if (!toolName) {
362
+ return { success: false, error: 'toolName parameter is required for action "engine_tool".' };
363
+ }
364
+ const toolArgs = (args['toolArgs'] && typeof args['toolArgs'] === 'object')
365
+ ? args['toolArgs']
366
+ : {};
367
+ const res = await sovereignReverseHarness.callEngineTool(toolName, toolArgs, context.signal);
368
+ const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
369
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_${toolName}`, textOutput);
370
+ return {
371
+ success: res.success,
372
+ action: 'engine_tool',
373
+ toolName,
374
+ preview: stored.contentForModel,
375
+ isTruncated: stored.isTruncated,
376
+ diskPath: stored.diskPath,
377
+ error: res.error
378
+ };
379
+ }
331
380
  // Require filePath for inspect, decompile, unpack, deobfuscate
332
381
  if (!rawPath && action !== 'trace') {
333
382
  return { success: false, error: `Action "${action}" requires a valid "filePath" parameter.` };
@@ -339,6 +388,16 @@ export const reverseEngineering = {
339
388
  // ── ACTION: INSPECT ───────────────────────────────────────────────────
340
389
  if (action === 'inspect') {
341
390
  try {
391
+ let engineText = '';
392
+ try {
393
+ const engineRes = await sovereignReverseHarness.inspectBinary(resolvedFile, context.signal);
394
+ if (engineRes.success && engineRes.output) {
395
+ engineText = engineRes.output;
396
+ }
397
+ }
398
+ catch {
399
+ // Fall back gracefully to native parsing
400
+ }
342
401
  const stats = await fsp.stat(resolvedFile);
343
402
  const fd = await fsp.open(resolvedFile, 'r');
344
403
  const headerBuf = Buffer.alloc(Math.min(8192, stats.size));
@@ -370,7 +429,6 @@ export const reverseEngineering = {
370
429
  result.fileType = 'Compressed Archive / Package';
371
430
  }
372
431
  else {
373
- // Check for ASAR
374
432
  const asar = parseAsarHeader(headerBuf);
375
433
  if (asar) {
376
434
  result.format = 'ASAR';
@@ -379,7 +437,9 @@ export const reverseEngineering = {
379
437
  result.metadata = { totalFiles: files.length, sampleFiles: files.slice(0, 10).map(f => f.path) };
380
438
  }
381
439
  }
382
- // Gather external symbol dump if requested
440
+ if (engineText) {
441
+ result.metadata = { ...(result.metadata ?? {}), engineAnalysis: engineText };
442
+ }
383
443
  if (detail === 'symbols' || detail === 'full') {
384
444
  try {
385
445
  const nmRes = await execFileAsync('nm', ['-gU', resolvedFile], { timeout: 10000, maxBuffer: 5 * 1024 * 1024 });
@@ -411,7 +471,18 @@ export const reverseEngineering = {
411
471
  if (action === 'decompile') {
412
472
  try {
413
473
  let disassemblyText = '';
414
- if (engine === 'rizin') {
474
+ // 1. Try sovereign engine decompilation
475
+ try {
476
+ const engineRes = await sovereignReverseHarness.decompile(resolvedFile, functionName, address, context.signal);
477
+ if (engineRes.success && engineRes.output) {
478
+ disassemblyText = engineRes.output;
479
+ }
480
+ }
481
+ catch {
482
+ // Fall back gracefully
483
+ }
484
+ // 2. Fallbacks if engine output is empty
485
+ if (!disassemblyText && engine === 'rizin') {
415
486
  try {
416
487
  const args = ['-q', '-c', functionName ? `pdf @ ${functionName}` : 'pdr @ main', resolvedFile];
417
488
  const rzRes = await execFileAsync('rizin', args, { timeout: 30000 });
@@ -466,6 +537,24 @@ export const reverseEngineering = {
466
537
  if (action === 'unpack') {
467
538
  try {
468
539
  const dest = outputDir ? resolveUserPath(outputDir) : path.join(workspaceDir, `${path.basename(resolvedFile)}_unpacked`);
540
+ // Try sovereign engine bundle unpacker first
541
+ try {
542
+ const engineRes = await sovereignReverseHarness.unpackBundle(resolvedFile, dest, context.signal);
543
+ if (engineRes.success && engineRes.output) {
544
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_unpack`, engineRes.output);
545
+ return {
546
+ success: true,
547
+ action: 'unpack',
548
+ destination: dest,
549
+ preview: stored.contentForModel,
550
+ isTruncated: stored.isTruncated,
551
+ diskPath: stored.diskPath
552
+ };
553
+ }
554
+ }
555
+ catch {
556
+ // Fall back gracefully
557
+ }
469
558
  const fileBuf = await fsp.readFile(resolvedFile);
470
559
  const asar = parseAsarHeader(fileBuf);
471
560
  if (asar) {
@@ -533,13 +622,24 @@ export const reverseEngineering = {
533
622
  if (action === 'deobfuscate') {
534
623
  try {
535
624
  const res = await deobfuscateScript(resolvedFile);
625
+ let engineText = '';
626
+ try {
627
+ const engineRes = await sovereignReverseHarness.deobfuscateScript(resolvedFile, context.signal);
628
+ if (engineRes.success && engineRes.output) {
629
+ engineText = engineRes.output;
630
+ }
631
+ }
632
+ catch {
633
+ // Fall back gracefully
634
+ }
536
635
  return {
537
636
  success: true,
538
637
  action: 'deobfuscate',
539
638
  filePath: resolvedFile,
540
639
  sourcemapDetected: res.sourcemapDetected,
541
640
  extractedRoutes: res.extractedRoutes,
542
- summary: res.summary
641
+ summary: res.summary,
642
+ ...(engineText ? { engineAnalysis: engineText } : {})
543
643
  };
544
644
  }
545
645
  catch (err) {
@@ -549,6 +649,24 @@ export const reverseEngineering = {
549
649
  // ── ACTION: TRACE ─────────────────────────────────────────────────────
550
650
  if (action === 'trace') {
551
651
  const target = typeof args['target'] === 'string' ? args['target'] : path.basename(resolvedFile || 'process');
652
+ const script = typeof args['script'] === 'string' ? args['script'] : undefined;
653
+ try {
654
+ const engineRes = await sovereignReverseHarness.traceRuntime(target, script ? { script } : {}, context.signal);
655
+ if (engineRes.success && engineRes.output) {
656
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_trace`, engineRes.output);
657
+ return {
658
+ success: true,
659
+ action: 'trace',
660
+ target,
661
+ preview: stored.contentForModel,
662
+ isTruncated: stored.isTruncated,
663
+ diskPath: stored.diskPath
664
+ };
665
+ }
666
+ }
667
+ catch {
668
+ // Fall back to hook template
669
+ }
552
670
  const hookTemplate = `// Sovereign Runtime Hook for ${target}\n` +
553
671
  `console.log("[*] Attaching hook to ${target}...");\n` +
554
672
  `if (Process.platform === 'darwin') {\n` +