@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,20 @@
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).
8
+
1
9
  import fs from 'node:fs';
2
10
  import fsp from 'node:fs/promises';
3
11
  import path from 'node:path';
4
12
  import { execFile } from 'node:child_process';
5
13
  import util from 'node:util';
6
14
  import { resolveUserPath } from '../utils/paths.js';
7
- import { ToolOutputStore } from './toolOutputStore.js';
15
+ import { ToolOutputStore, defaultToolOutputStore } from './toolOutputStore.js';
8
16
  import { isAutonomousToolContext } from '../approvalPolicy.js';
17
+ import { sovereignReverseHarness } from '../engines/reverseHarness.js';
9
18
 
10
19
  const execFileAsync = util.promisify(execFile);
11
20
 
@@ -19,7 +28,9 @@ export type ReverseEngineeringAction =
19
28
  | 'unpack'
20
29
  | 'deobfuscate'
21
30
  | 'trace'
22
- | 'status';
31
+ | 'status'
32
+ | 'engine_tool'
33
+ | 'list_tools';
23
34
 
24
35
  export interface BinaryMitigations {
25
36
  pie?: boolean | undefined;
@@ -56,6 +67,8 @@ export interface ReverseEngineeringParams {
56
67
  detail?: 'summary' | 'symbols' | 'headers' | 'mitigations' | 'full' | undefined;
57
68
  listOnly?: boolean | undefined;
58
69
  script?: string | undefined;
70
+ toolName?: string | undefined;
71
+ toolArgs?: Record<string, unknown> | undefined;
59
72
  }
60
73
 
61
74
  // ─────────────────────────────────────────────────────────────────────────────
@@ -69,88 +82,67 @@ function parseMachO(buffer: Buffer): Partial<BinaryInspectionResult> {
69
82
  const isFat = magic === 0xcafebabe || magic === 0xbebafeca;
70
83
 
71
84
  if (isFat) {
72
- const numArchs = buffer.readUInt32BE(4);
73
- if (buffer.length >= 8 + 20) {
74
- const sliceOffset = buffer.readUInt32BE(8 + 8);
75
- if (sliceOffset > 0 && sliceOffset < buffer.length) {
76
- const sliceResult = parseMachO(buffer.subarray(sliceOffset));
77
- return {
78
- ...sliceResult,
79
- format: 'Mach-O',
80
- fileType: 'Universal / FAT Binary',
81
- mitigations: sliceResult.mitigations || { pie: true, nx: true, canary: true, aslr: true, codeSigned: true },
82
- metadata: { architecturesCount: numArchs, ...sliceResult.metadata }
83
- };
85
+ let architecture = 'Universal FAT (Mach-O)';
86
+ const nfat_arch = buffer.readUInt32BE(4);
87
+ if (buffer.length >= 8 + nfat_arch * 20) {
88
+ for (let i = 0; i < nfat_arch; i++) {
89
+ const offset = 8 + i * 20;
90
+ const cputype = buffer.readInt32BE(offset);
91
+ const sliceOffset = buffer.readUInt32BE(offset + 8);
92
+ const sliceSize = buffer.readUInt32BE(offset + 12);
93
+ if (sliceOffset + 8 <= buffer.length) {
94
+ const sliceBuf = buffer.subarray(sliceOffset, Math.min(sliceOffset + sliceSize, buffer.length));
95
+ if (sliceBuf.length >= 8) {
96
+ const inner = parseMachO(sliceBuf);
97
+ return {
98
+ format: 'Mach-O',
99
+ architecture: `Universal FAT (slice: ${inner.architecture || 'unknown'}, cputype: ${cputype})`,
100
+ is64Bit: inner.is64Bit ?? true,
101
+ byteOrder: inner.byteOrder ?? 'little-endian',
102
+ fileType: inner.fileType ?? 'Mach-O Universal Binary',
103
+ mitigations: inner.mitigations ?? { pie: true, nx: true, aslr: true, codeSigned: true }
104
+ };
105
+ }
106
+ }
84
107
  }
85
108
  }
86
109
  return {
87
110
  format: 'Mach-O',
88
- fileType: 'Universal / FAT Binary',
89
- architecture: 'Universal (x86_64 + arm64)',
90
- mitigations: {
91
- pie: true,
92
- nx: true,
93
- canary: true,
94
- aslr: true,
95
- codeSigned: true
96
- },
97
- metadata: { architecturesCount: numArchs }
111
+ architecture,
112
+ is64Bit: true,
113
+ byteOrder: 'big-endian',
114
+ fileType: 'Mach-O Universal Binary',
115
+ mitigations: { pie: true, nx: true, aslr: true, codeSigned: true }
98
116
  };
99
117
  }
100
118
 
101
119
  const cputype = isLe ? buffer.readInt32LE(4) : buffer.readInt32BE(4);
102
- let arch = 'unknown';
103
- if (cputype === 0x01000007) arch = 'x86_64';
104
- else if (cputype === 0x0100000c) arch = 'arm64';
105
- else if (cputype === 7) arch = 'i386';
106
- else if (cputype === 12) arch = 'arm';
107
-
108
- const ncmds = isLe ? buffer.readUInt32LE(16) : buffer.readUInt32BE(16);
109
- const importedLibs: string[] = [];
110
- const sections: string[] = [];
111
- let codeSigned = false;
112
- let pie = false;
113
-
114
- let offset = is64 ? 32 : 28;
115
- for (let i = 0; i < ncmds && offset + 8 <= buffer.length; i++) {
116
- const cmd = isLe ? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset);
117
- const cmdsize = isLe ? buffer.readUInt32LE(offset + 4) : buffer.readUInt32BE(offset + 4);
118
- if (cmdsize <= 0 || offset + cmdsize > buffer.length) break;
119
-
120
- // LC_LOAD_DYLIB = 0xc
121
- if (cmd === 0x0c || cmd === 0x1c || cmd === 0x8000001c) {
122
- const strOffset = isLe ? buffer.readUInt32LE(offset + 8) : buffer.readUInt32BE(offset + 8);
123
- if (strOffset < cmdsize) {
124
- const rawStr = buffer.toString('utf8', offset + strOffset, offset + cmdsize).replace(/\0.*$/, '');
125
- if (rawStr) importedLibs.push(path.basename(rawStr));
126
- }
127
- }
128
- // LC_CODE_SIGNATURE = 0x1d
129
- if (cmd === 0x1d) codeSigned = true;
130
- // LC_SEGMENT_64 = 0x19
131
- if (cmd === 0x19 && offset + 72 <= buffer.length) {
132
- const segname = buffer.toString('utf8', offset + 8, offset + 24).replace(/\0.*$/, '');
133
- if (segname) sections.push(segname);
134
- }
135
- offset += cmdsize;
136
- }
120
+ let architecture = 'unknown';
121
+ if (cputype === 0x01000007) architecture = 'x86_64';
122
+ else if (cputype === 0x0100000c) architecture = 'arm64';
123
+ else if (cputype === 7) architecture = 'i386';
124
+ else if (cputype === 12) architecture = 'arm';
125
+
126
+ const filetypeInt = isLe ? buffer.readUInt32LE(12) : buffer.readUInt32BE(12);
127
+ let fileType = 'Mach-O Binary';
128
+ if (filetypeInt === 2) fileType = 'Executable (MH_EXECUTE)';
129
+ else if (filetypeInt === 6) fileType = 'Shared Library (MH_DYLIB)';
130
+ else if (filetypeInt === 8) fileType = 'Bundle (MH_BUNDLE)';
137
131
 
138
132
  const flags = isLe ? buffer.readUInt32LE(24) : buffer.readUInt32BE(24);
139
- if (flags & 0x00200000) pie = true;
133
+ const pie = (flags & 0x200000) !== 0; // MH_PIE
140
134
 
141
135
  return {
142
136
  format: 'Mach-O',
143
- architecture: arch,
137
+ architecture,
144
138
  is64Bit: is64,
145
139
  byteOrder: isLe ? 'little-endian' : 'big-endian',
146
- sections: [...new Set(sections)],
147
- importedLibraries: importedLibs,
140
+ fileType,
148
141
  mitigations: {
149
142
  pie,
150
143
  nx: true,
151
- canary: true,
152
144
  aslr: pie,
153
- codeSigned
145
+ codeSigned: true
154
146
  }
155
147
  };
156
148
  }
@@ -158,223 +150,251 @@ function parseMachO(buffer: Buffer): Partial<BinaryInspectionResult> {
158
150
  function parseElf(buffer: Buffer): Partial<BinaryInspectionResult> {
159
151
  const is64 = buffer[4] === 2;
160
152
  const isLe = buffer[5] === 1;
161
- const e_machine = isLe ? buffer.readUInt16LE(18) : buffer.readUInt16BE(18);
162
153
 
163
- let arch = 'unknown';
164
- if (e_machine === 0x3e) arch = 'x86_64';
165
- else if (e_machine === 0xb7) arch = 'aarch64 (arm64)';
166
- else if (e_machine === 0x03) arch = 'i386';
167
- else if (e_machine === 0x28) arch = 'arm';
168
- else if (e_machine === 0xf3) arch = 'riscv';
154
+ const readU16 = (off: number) => isLe ? buffer.readUInt16LE(off) : buffer.readUInt16BE(off);
155
+ const readU32 = (off: number) => isLe ? buffer.readUInt32LE(off) : buffer.readUInt32BE(off);
156
+
157
+ const eType = readU16(16);
158
+ let fileType = 'ELF Binary';
159
+ let pie = false;
160
+ if (eType === 2) {
161
+ fileType = 'Executable (ET_EXEC)';
162
+ pie = false;
163
+ } else if (eType === 3) {
164
+ fileType = 'Shared Object / Dynamic Library (ET_DYN)';
165
+ pie = true;
166
+ }
169
167
 
170
- const e_type = isLe ? buffer.readUInt16LE(16) : buffer.readUInt16BE(16);
171
- const pie = e_type === 3; // ET_DYN (shared object / PIE)
168
+ const eMachine = readU16(18);
169
+ let architecture = 'unknown';
170
+ if (eMachine === 0x3e) architecture = 'x86_64';
171
+ else if (eMachine === 0xb7) architecture = 'aarch64 (ARM64)';
172
+ else if (eMachine === 0x03) architecture = 'i386';
173
+ else if (eMachine === 0x28) architecture = 'ARM (32-bit)';
174
+ else if (eMachine === 0xf3) architecture = 'RISC-V';
172
175
 
173
176
  return {
174
177
  format: 'ELF',
175
- architecture: arch,
178
+ architecture,
176
179
  is64Bit: is64,
177
180
  byteOrder: isLe ? 'little-endian' : 'big-endian',
178
- fileType: e_type === 2 ? 'Executable' : e_type === 3 ? 'Shared Object / PIE' : 'Relocatable',
181
+ fileType,
179
182
  mitigations: {
180
183
  pie,
181
184
  nx: true,
182
- canary: true,
183
- relro: 'partial'
185
+ relro: pie ? 'full' : 'partial'
184
186
  }
185
187
  };
186
188
  }
187
189
 
188
190
  function parsePE(buffer: Buffer): Partial<BinaryInspectionResult> {
189
- if (buffer.length < 0x40) return { format: 'PE/COFF' };
191
+ if (buffer.length < 64) return { format: 'PE/COFF' };
190
192
  const peOffset = buffer.readUInt32LE(0x3c);
191
193
  if (peOffset + 24 > buffer.length) return { format: 'PE/COFF' };
192
- const magic = buffer.toString('utf8', peOffset, peOffset + 4);
193
- if (magic !== 'PE\0\0') return { format: 'PE/COFF' };
194
+
195
+ const peSig = buffer.toString('utf8', peOffset, peOffset + 4);
196
+ if (peSig !== 'PE\0\0') return { format: 'PE/COFF' };
194
197
 
195
198
  const machine = buffer.readUInt16LE(peOffset + 4);
196
- let arch = 'unknown';
197
- if (machine === 0x8664) arch = 'x86_64 (AMD64)';
198
- else if (machine === 0x014c) arch = 'i386 (x86)';
199
- else if (machine === 0xaa64) arch = 'ARM64';
199
+ let architecture = 'unknown';
200
+ if (machine === 0x8664) architecture = 'x86_64 (AMD64)';
201
+ else if (machine === 0xaa64) architecture = 'ARM64';
202
+ else if (machine === 0x14c) architecture = 'i386 (x86)';
200
203
 
204
+ const optHeaderOffset = peOffset + 24;
201
205
  let is64 = false;
202
206
  let pie = false;
203
207
  let nx = false;
204
208
 
205
- const optHeaderOffset = peOffset + 24;
206
- if (optHeaderOffset + 2 <= buffer.length) {
207
- const optMagic = buffer.readUInt16LE(optHeaderOffset);
208
- is64 = optMagic === 0x20b; // PE32+
209
- const dllCharOffset = optHeaderOffset + (is64 ? 70 : 68);
209
+ if (optHeaderOffset + 72 <= buffer.length) {
210
+ const magic = buffer.readUInt16LE(optHeaderOffset);
211
+ is64 = magic === 0x20b; // PE32+
212
+
213
+ const dllCharOffset = optHeaderOffset + 70;
210
214
  if (dllCharOffset + 2 <= buffer.length) {
211
- const dllChars = buffer.readUInt16LE(dllCharOffset);
212
- pie = (dllChars & 0x0040) !== 0; // IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
213
- nx = (dllChars & 0x0100) !== 0; // IMAGE_DLLCHARACTERISTICS_NX_COMPAT
215
+ const dllCharacteristics = buffer.readUInt16LE(dllCharOffset);
216
+ pie = (dllCharacteristics & 0x0040) !== 0; // IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE
217
+ nx = (dllCharacteristics & 0x0100) !== 0; // IMAGE_DLLCHARACTERISTICS_NX_COMPAT
214
218
  }
215
219
  }
216
220
 
217
221
  return {
218
222
  format: 'PE/COFF',
219
- architecture: arch,
223
+ architecture,
220
224
  is64Bit: is64,
221
225
  byteOrder: 'little-endian',
226
+ fileType: 'Windows Portable Executable',
222
227
  mitigations: {
223
228
  pie,
224
229
  nx,
225
- canary: true,
226
230
  aslr: pie
227
231
  }
228
232
  };
229
233
  }
230
234
 
231
235
  // ─────────────────────────────────────────────────────────────────────────────
232
- // ASAR (ELECTRON BUNDLE) UNPACKER & INSPECTOR
236
+ // ASAR BUNDLE PARSER (Electron Container Zero-Dependency Unpack)
233
237
  // ─────────────────────────────────────────────────────────────────────────────
234
238
 
235
- interface AsarDirectory {
236
- files: Record<string, AsarDirectory | AsarFileEntry>;
237
- }
238
-
239
239
  interface AsarFileEntry {
240
240
  size: number;
241
- offset?: string | number;
242
- unpacked?: boolean;
241
+ offset: number;
242
+ executable?: boolean;
243
+ }
244
+
245
+ interface AsarDirectory {
246
+ files: Record<string, AsarDirectory | AsarFileEntry>;
243
247
  }
244
248
 
245
- function parseAsarHeader(buffer: Buffer): { header: AsarDirectory; headerSize: number } | null {
249
+ function parseAsarHeader(buffer: Buffer): { headerSize: number; header: AsarDirectory } | null {
246
250
  if (buffer.length < 16) return null;
251
+ const magic = buffer.readUInt32LE(0);
252
+ if (magic !== 4) return null;
253
+
247
254
  const headerSize = buffer.readUInt32LE(12);
248
- if (headerSize <= 0 || 16 + headerSize > buffer.length) return null;
249
- const jsonStr = buffer.toString('utf8', 16, 16 + headerSize);
255
+ if (16 + headerSize > buffer.length) return null;
256
+
250
257
  try {
251
- const parsed = JSON.parse(jsonStr) as AsarDirectory;
252
- return { header: parsed, headerSize: 16 + headerSize };
258
+ const headerJson = buffer.toString('utf8', 16, 16 + headerSize);
259
+ const header = JSON.parse(headerJson) as AsarDirectory;
260
+ return { headerSize: 16 + headerSize, header };
253
261
  } catch {
254
262
  return null;
255
263
  }
256
264
  }
257
265
 
258
- function listAsarFiles(entry: AsarDirectory | AsarFileEntry, prefix = ''): { path: string; size: number }[] {
259
- const result: { path: string; size: number }[] = [];
260
- if ('files' in entry && entry.files) {
261
- for (const [name, child] of Object.entries(entry.files)) {
262
- const fullPath = prefix ? `${prefix}/${name}` : name;
263
- if ('files' in child && child.files) {
264
- result.push(...listAsarFiles(child, fullPath));
265
- } else if ('size' in child) {
266
- result.push({ path: fullPath, size: child.size ?? 0 });
267
- }
266
+ function listAsarFiles(dir: AsarDirectory, prefix = ''): { path: string; size: number }[] {
267
+ const list: { path: string; size: number }[] = [];
268
+ if (!dir || !dir.files) return list;
269
+
270
+ for (const [name, entry] of Object.entries(dir.files)) {
271
+ const fullPath = prefix ? `${prefix}/${name}` : name;
272
+ if ('files' in entry && entry.files) {
273
+ list.push(...listAsarFiles(entry, fullPath));
274
+ } else if ('size' in entry && typeof entry.size === 'number') {
275
+ list.push({ path: fullPath, size: entry.size });
268
276
  }
269
277
  }
270
- return result;
278
+ return list;
271
279
  }
272
280
 
273
281
  // ─────────────────────────────────────────────────────────────────────────────
274
- // SCRIPT DEOBFUSCATOR & SOURCEMAP HARVESTER
282
+ // JAVASCRIPT / BUNDLE SCRIPT DEOBFUSCATOR
275
283
  // ─────────────────────────────────────────────────────────────────────────────
276
284
 
277
- async function deobfuscateScript(
278
- filePath: string
279
- ): Promise<{ success: boolean; sourcemapDetected: boolean; extractedRoutes?: string[]; summary: string }> {
285
+ async function deobfuscateScript(filePath: string): Promise<{
286
+ sourcemapDetected: boolean;
287
+ extractedRoutes: string[];
288
+ summary: string;
289
+ }> {
280
290
  const code = await fsp.readFile(filePath, 'utf8');
281
291
  const sourcemapDetected = /\/\/# sourceMappingURL=/i.test(code) || /\/\*# sourceMappingURL=/i.test(code);
282
292
 
283
293
  const urlMatches = code.match(/https?:\/\/[a-zA-Z0-9./?=_%&:-]+/g) || [];
284
294
  const routeMatches = code.match(/['"`]\/(?:api|v[0-9]|auth|users|admin|graphql)[a-zA-Z0-9/_-]*['"`]/g) || [];
285
- const cleanRoutes = [...new Set([...urlMatches, ...routeMatches.map(r => r.replace(/['"`]/g, ''))])].slice(0, 50);
295
+ const cleanedRoutes = routeMatches.map(r => r.slice(1, -1));
296
+ const uniqueEndpoints = Array.from(new Set([...urlMatches, ...cleanedRoutes]));
297
+
298
+ const lines = code.split('\n').length;
299
+ const summary = `Script Analysis: ${lines} lines, ${code.length} characters. Sourcemap: ${sourcemapDetected ? 'Present' : 'None'}. Harvested ${uniqueEndpoints.length} endpoints.`;
286
300
 
287
301
  return {
288
- success: true,
289
302
  sourcemapDetected,
290
- extractedRoutes: cleanRoutes,
291
- summary: `Analyzed ${path.basename(filePath)} (${code.length} bytes). Sourcemaps detected: ${sourcemapDetected}. Discovered ${cleanRoutes.length} potential endpoints/routes.`
303
+ extractedRoutes: uniqueEndpoints.slice(0, 50),
304
+ summary
292
305
  };
293
306
  }
294
307
 
295
308
  // ─────────────────────────────────────────────────────────────────────────────
296
- // MAIN TOOL DEFINITION
309
+ // CANONICAL TOOL DEFINITION
297
310
  // ─────────────────────────────────────────────────────────────────────────────
298
311
 
299
312
  export const reverseEngineering = {
300
313
  schema: {
301
314
  name: 'reverse_engineering',
302
- 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.',
315
+ description: 'Sovereign reverse engineering, binary triage, decompilation, bundle unpacking, and runtime tracing suite backed by headless MCP engine substrate.',
303
316
  parameters: {
304
317
  type: 'object',
305
318
  properties: {
306
319
  action: {
307
320
  type: 'string',
308
- enum: ['inspect', 'decompile', 'unpack', 'deobfuscate', 'trace', 'status'],
309
- 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).'
321
+ enum: ['inspect', 'decompile', 'unpack', 'deobfuscate', 'trace', 'status', 'engine_tool', 'list_tools'],
322
+ description: 'Reverse engineering action to perform.'
310
323
  },
311
324
  filePath: {
312
325
  type: 'string',
313
- description: 'Absolute or relative path to the target binary, application bundle, or script.'
326
+ description: 'Absolute or workspace-relative path to target binary, bundle, or script.'
327
+ },
328
+ target: {
329
+ type: 'string',
330
+ description: 'Process name, function symbol, or bundle resource identifier.'
314
331
  },
315
332
  outputDir: {
316
333
  type: 'string',
317
- description: 'Destination directory for unpacked bundles or extracted assets.'
334
+ description: 'Target extraction directory for bundle unpacking.'
318
335
  },
319
336
  functionName: {
320
337
  type: 'string',
321
- description: 'Name of the function or symbol to decompile/disassemble.'
338
+ description: 'Specific function symbol to decompile or disassemble.'
322
339
  },
323
340
  address: {
324
341
  type: 'string',
325
- description: 'Hex virtual address (e.g., 0x100003f20) to inspect or decompile.'
342
+ description: 'Hexadecimal memory address (e.g. "0x100003fa0") to inspect or decompile.'
326
343
  },
327
344
  engine: {
328
345
  type: 'string',
329
346
  enum: ['auto', 'ghidra', 'rizin', 'hopper', 'native'],
330
- description: 'Decompilation engine preference. Defaults to auto.'
347
+ description: 'Decompiler engine preference (default: auto).'
331
348
  },
332
349
  detail: {
333
350
  type: 'string',
334
351
  enum: ['summary', 'symbols', 'headers', 'mitigations', 'full'],
335
- description: 'Level of detail for binary inspection.'
352
+ description: 'Level of analytical detail.'
336
353
  },
337
354
  listOnly: {
338
355
  type: 'boolean',
339
- description: 'When true, unpack lists bundle entries without extracting them to disk.'
356
+ description: 'When unpacking, list container manifest contents without extracting files to disk.'
340
357
  },
341
358
  script: {
342
359
  type: 'string',
343
- description: 'Hook script or instrumentation code for runtime tracing.'
360
+ description: 'Custom instrumentation or tracer hook script.'
361
+ },
362
+ toolName: {
363
+ type: 'string',
364
+ description: 'Specific engine tool name to execute when action is "engine_tool".'
365
+ },
366
+ toolArgs: {
367
+ type: 'object',
368
+ description: 'Arguments payload for engine_tool.'
344
369
  }
345
370
  },
346
371
  required: ['action']
347
372
  }
348
373
  },
349
374
 
350
- async execute(args: Record<string, unknown>, sandbox: Record<string, unknown> = {}): Promise<Record<string, unknown>> {
351
- const action = String(args['action'] || 'inspect') as ReverseEngineeringAction;
375
+ async execute(args: Record<string, unknown>, context: { workspaceDir?: string; sessionId?: string; signal?: AbortSignal } = {}): Promise<Record<string, unknown>> {
376
+ const action = String(args['action'] || 'status') as ReverseEngineeringAction;
352
377
  const rawPath = typeof args['filePath'] === 'string' ? args['filePath'] : undefined;
353
378
  const outputDir = typeof args['outputDir'] === 'string' ? args['outputDir'] : undefined;
354
379
  const functionName = typeof args['functionName'] === 'string' ? args['functionName'] : undefined;
355
380
  const address = typeof args['address'] === 'string' ? args['address'] : undefined;
356
- const engine = (typeof args['engine'] === 'string' ? args['engine'] : 'auto') as 'auto' | 'ghidra' | 'rizin' | 'hopper' | 'native';
357
- const detail = (typeof args['detail'] === 'string' ? args['detail'] : 'summary') as 'summary' | 'symbols' | 'headers' | 'mitigations' | 'full';
358
- const listOnly = args['listOnly'] === true;
359
-
360
- const workspaceDir = (Array.isArray(sandbox['workspacePaths']) && sandbox['workspacePaths'][0])
361
- ? String(sandbox['workspacePaths'][0])
362
- : process.cwd();
363
-
364
- const outputStore = new ToolOutputStore();
365
- const sessionId = typeof sandbox['sessionId'] === 'string' ? sandbox['sessionId'] : 're_session';
381
+ const engine = typeof args['engine'] === 'string' ? args['engine'] as 'auto' | 'ghidra' | 'rizin' | 'hopper' | 'native' : 'auto';
382
+ const detail = typeof args['detail'] === 'string' ? args['detail'] as 'summary' | 'symbols' | 'headers' | 'mitigations' | 'full' : 'summary';
383
+ const listOnly = Boolean(args['listOnly']);
384
+ const workspaceDir = context.workspaceDir || process.cwd();
385
+ const sessionId = context.sessionId || 're_session';
386
+ const outputStore = defaultToolOutputStore;
366
387
  const callId = `re_${Date.now()}`;
367
388
 
368
389
  // ── ACTION: STATUS ────────────────────────────────────────────────────
369
390
  if (action === 'status') {
370
- const engines: Record<string, { available: boolean; path?: string }> = {};
371
-
372
- const checkCmd = async (bin: string) => {
391
+ const engines: Record<string, boolean> = {};
392
+ const checkCmd = async (cmd: string): Promise<boolean> => {
373
393
  try {
374
- const res = await execFileAsync('which', [bin]);
375
- return { available: true, path: res.stdout.trim() };
394
+ await execFileAsync('which', [cmd]);
395
+ return true;
376
396
  } catch {
377
- return { available: false };
397
+ return false;
378
398
  }
379
399
  };
380
400
 
@@ -386,11 +406,16 @@ export const reverseEngineering = {
386
406
  engines['rizin'] = await checkCmd('rizin');
387
407
  engines['frida'] = await checkCmd('frida');
388
408
 
409
+ const engineAvailable = await sovereignReverseHarness.isAvailable();
410
+ const toolList = engineAvailable ? await sovereignReverseHarness.listTools() : [];
411
+
389
412
  return {
390
413
  success: true,
391
414
  action: 'status',
392
415
  platform: process.platform,
393
416
  architecture: process.arch,
417
+ engineAvailable,
418
+ specializedEngineToolsCount: toolList.length,
394
419
  installedEngines: engines,
395
420
  capabilities: [
396
421
  'Mach-O Universal / FAT & 64-bit triage',
@@ -398,11 +423,48 @@ export const reverseEngineering = {
398
423
  'PE/COFF Windows binary mitigation checks',
399
424
  'Electron ASAR pickle header inspection & extraction',
400
425
  'JavaScript sourcemap recovery and route harvesting',
401
- 'Dynamic Frida hook script synthesis'
426
+ 'Dynamic runtime tracing and API observation',
427
+ 'Headless MCP engine with 229 specialized reverse engineering tools'
402
428
  ]
403
429
  };
404
430
  }
405
431
 
432
+ // ── ACTION: LIST_TOOLS ────────────────────────────────────────────────
433
+ if (action === 'list_tools') {
434
+ const tools = await sovereignReverseHarness.listTools();
435
+ return {
436
+ success: true,
437
+ action: 'list_tools',
438
+ totalTools: tools.length,
439
+ tools
440
+ };
441
+ }
442
+
443
+ // ── ACTION: ENGINE_TOOL ───────────────────────────────────────────────
444
+ if (action === 'engine_tool') {
445
+ const toolName = typeof args['toolName'] === 'string' ? args['toolName'] : '';
446
+ if (!toolName) {
447
+ return { success: false, error: 'toolName parameter is required for action "engine_tool".' };
448
+ }
449
+ const toolArgs = (args['toolArgs'] && typeof args['toolArgs'] === 'object')
450
+ ? (args['toolArgs'] as Record<string, unknown>)
451
+ : {};
452
+
453
+ const res = await sovereignReverseHarness.callEngineTool(toolName, toolArgs, context.signal);
454
+ const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
455
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_${toolName}`, textOutput);
456
+
457
+ return {
458
+ success: res.success,
459
+ action: 'engine_tool',
460
+ toolName,
461
+ preview: stored.contentForModel,
462
+ isTruncated: stored.isTruncated,
463
+ diskPath: stored.diskPath,
464
+ error: res.error
465
+ };
466
+ }
467
+
406
468
  // Require filePath for inspect, decompile, unpack, deobfuscate
407
469
  if (!rawPath && action !== 'trace') {
408
470
  return { success: false, error: `Action "${action}" requires a valid "filePath" parameter.` };
@@ -416,6 +478,16 @@ export const reverseEngineering = {
416
478
  // ── ACTION: INSPECT ───────────────────────────────────────────────────
417
479
  if (action === 'inspect') {
418
480
  try {
481
+ let engineText = '';
482
+ try {
483
+ const engineRes = await sovereignReverseHarness.inspectBinary(resolvedFile, context.signal);
484
+ if (engineRes.success && engineRes.output) {
485
+ engineText = engineRes.output;
486
+ }
487
+ } catch {
488
+ // Fall back gracefully to native parsing
489
+ }
490
+
419
491
  const stats = await fsp.stat(resolvedFile);
420
492
  const fd = await fsp.open(resolvedFile, 'r');
421
493
  const headerBuf = Buffer.alloc(Math.min(8192, stats.size));
@@ -447,7 +519,6 @@ export const reverseEngineering = {
447
519
  result.format = 'APK/ZIP';
448
520
  result.fileType = 'Compressed Archive / Package';
449
521
  } else {
450
- // Check for ASAR
451
522
  const asar = parseAsarHeader(headerBuf);
452
523
  if (asar) {
453
524
  result.format = 'ASAR';
@@ -457,7 +528,10 @@ export const reverseEngineering = {
457
528
  }
458
529
  }
459
530
 
460
- // Gather external symbol dump if requested
531
+ if (engineText) {
532
+ result.metadata = { ...(result.metadata ?? {}), engineAnalysis: engineText };
533
+ }
534
+
461
535
  if (detail === 'symbols' || detail === 'full') {
462
536
  try {
463
537
  const nmRes = await execFileAsync('nm', ['-gU', resolvedFile], { timeout: 10000, maxBuffer: 5 * 1024 * 1024 });
@@ -491,7 +565,18 @@ export const reverseEngineering = {
491
565
  try {
492
566
  let disassemblyText = '';
493
567
 
494
- if (engine === 'rizin') {
568
+ // 1. Try sovereign engine decompilation
569
+ try {
570
+ const engineRes = await sovereignReverseHarness.decompile(resolvedFile, functionName, address, context.signal);
571
+ if (engineRes.success && engineRes.output) {
572
+ disassemblyText = engineRes.output;
573
+ }
574
+ } catch {
575
+ // Fall back gracefully
576
+ }
577
+
578
+ // 2. Fallbacks if engine output is empty
579
+ if (!disassemblyText && engine === 'rizin') {
495
580
  try {
496
581
  const args = ['-q', '-c', functionName ? `pdf @ ${functionName}` : 'pdr @ main', resolvedFile];
497
582
  const rzRes = await execFileAsync('rizin', args, { timeout: 30000 });
@@ -545,6 +630,25 @@ export const reverseEngineering = {
545
630
  if (action === 'unpack') {
546
631
  try {
547
632
  const dest = outputDir ? resolveUserPath(outputDir) : path.join(workspaceDir, `${path.basename(resolvedFile)}_unpacked`);
633
+
634
+ // Try sovereign engine bundle unpacker first
635
+ try {
636
+ const engineRes = await sovereignReverseHarness.unpackBundle(resolvedFile, dest, context.signal);
637
+ if (engineRes.success && engineRes.output) {
638
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_unpack`, engineRes.output);
639
+ return {
640
+ success: true,
641
+ action: 'unpack',
642
+ destination: dest,
643
+ preview: stored.contentForModel,
644
+ isTruncated: stored.isTruncated,
645
+ diskPath: stored.diskPath
646
+ };
647
+ }
648
+ } catch {
649
+ // Fall back gracefully
650
+ }
651
+
548
652
  const fileBuf = await fsp.readFile(resolvedFile);
549
653
  const asar = parseAsarHeader(fileBuf);
550
654
 
@@ -615,13 +719,24 @@ export const reverseEngineering = {
615
719
  if (action === 'deobfuscate') {
616
720
  try {
617
721
  const res = await deobfuscateScript(resolvedFile);
722
+ let engineText = '';
723
+ try {
724
+ const engineRes = await sovereignReverseHarness.deobfuscateScript(resolvedFile, context.signal);
725
+ if (engineRes.success && engineRes.output) {
726
+ engineText = engineRes.output;
727
+ }
728
+ } catch {
729
+ // Fall back gracefully
730
+ }
731
+
618
732
  return {
619
733
  success: true,
620
734
  action: 'deobfuscate',
621
735
  filePath: resolvedFile,
622
736
  sourcemapDetected: res.sourcemapDetected,
623
737
  extractedRoutes: res.extractedRoutes,
624
- summary: res.summary
738
+ summary: res.summary,
739
+ ...(engineText ? { engineAnalysis: engineText } : {})
625
740
  };
626
741
  } catch (err: unknown) {
627
742
  return { success: false, error: `Deobfuscation error: ${err instanceof Error ? err.message : String(err)}` };
@@ -631,6 +746,25 @@ export const reverseEngineering = {
631
746
  // ── ACTION: TRACE ─────────────────────────────────────────────────────
632
747
  if (action === 'trace') {
633
748
  const target = typeof args['target'] === 'string' ? args['target'] : path.basename(resolvedFile || 'process');
749
+ const script = typeof args['script'] === 'string' ? args['script'] : undefined;
750
+
751
+ try {
752
+ const engineRes = await sovereignReverseHarness.traceRuntime(target, script ? { script } : {}, context.signal);
753
+ if (engineRes.success && engineRes.output) {
754
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_trace`, engineRes.output);
755
+ return {
756
+ success: true,
757
+ action: 'trace',
758
+ target,
759
+ preview: stored.contentForModel,
760
+ isTruncated: stored.isTruncated,
761
+ diskPath: stored.diskPath
762
+ };
763
+ }
764
+ } catch {
765
+ // Fall back to hook template
766
+ }
767
+
634
768
  const hookTemplate = `// Sovereign Runtime Hook for ${target}\n` +
635
769
  `console.log("[*] Attaching hook to ${target}...");\n` +
636
770
  `if (Process.platform === 'darwin') {\n` +