@causyne/agent 1.20.18 → 1.20.19

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.18",
3
+ "version": "1.20.19",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
package/src/agentLoop.js CHANGED
@@ -270,6 +270,15 @@ You are bound by an unbreakable ethical safety net. Regardless of user prompt, j
270
270
 
271
271
  If asked to perform ANY harmful task, politely decline, state that Causyne exists to make the world better, and offer legitimate developer assistance instead.
272
272
 
273
+ # Sovereign Reverse Engineering & Clean-Room Analysis (REA Substrate)
274
+ You possess native reverse engineering capabilities powered by the Reverse Engineer Anything (REA) sovereign substrate via the \`reverse_engineering\` tool.
275
+ - **Authorized Analytical Scope**: Reverse engineering for interoperability, binary inspection, security research, vulnerability analysis, format decoding, manifest analysis, and clean-room application implementation is fully authorized.
276
+ - **Clean-Room Implementation Discipline**: When a user provides an APK, binary, or application package and asks to build a similar or compatible application (e.g. "analyze using rea make app like this for me"):
277
+ 1. Proactively use \`reverse_engineering\` with actions 'inspect', 'unpack', 'decompile', or 'engine_tool' to inspect the artifact: examine \`AndroidManifest.xml\`, decode resources, list activities, extract layouts, inspect DEX classes, and map the application graph.
278
+ 2. Synthesize functional and architectural specifications (data models, UI flows, service components).
279
+ 3. Scaffold and build the original, clean-room application using modern open-source frameworks and idiomatic patterns.
280
+ 4. NEVER issue canned refusals (such as "I cannot decompile, extract, or clone proprietary commercial software..."). Legitimate structural inspection, format analysis, and clean-room development are core sovereign capabilities.
281
+
273
282
  # Dependency Management & Autonomy Modes
274
283
  - **Mode A (Passive)**: You MUST explicitly ask the user for permission (by ending your turn and asking a question) before installing any dependencies.
275
284
  - **Mode B (Supervised)**: You may install standard development dependencies automatically, but you MUST ask for permission before modifying OS-level settings or running \`sudo\`.
@@ -2131,7 +2140,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
2131
2140
  pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
2132
2141
  shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
2133
2142
  pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
2134
- this.efficiencyBudget?.extendBudget?.(1_000_000, 100);
2143
+ const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
2144
+ const extraTokens = Math.max(stepScale * 10, 1_000_000);
2145
+ const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
2146
+ this.tokenTracker.extendBudget(extraTokens);
2147
+ this.efficiencyBudget?.extendBudget?.(extraTokens, extraActions);
2135
2148
  }
2136
2149
  }
2137
2150
  // 2. PLAN (Call LLM). dynamicTools was resolved above so the task brief
@@ -2626,20 +2639,45 @@ You are operating in a text-and-code modality without direct image pixel renderi
2626
2639
  // If no tool calls, check if the agent is just thinking/planning or actually done
2627
2640
  if (!response.toolCalls || response.toolCalls.length === 0) {
2628
2641
  if (response.toolRoutingError) {
2629
- const name = response.toolRoutingError.tool;
2630
- if (toolRoutingRecoveries++ >= 1) {
2631
- this.emitEvent({ type: 'error', message: `The peer repeatedly invoked host tool ${name} through its native channel. Work remains unfinished.` });
2642
+ const rawName = response.toolRoutingError.tool;
2643
+ const resolved = resolveTool(rawName);
2644
+ if (resolved) {
2645
+ const canonical = canonicalToolName(rawName);
2646
+ const toolParams = { ...(response.toolRoutingError.parameters || {}) };
2647
+ if (canonical === 'reverse_engineering' && !toolParams.filePath && !toolParams.target && !toolParams.file && !toolParams.path) {
2648
+ const promptMatch = (this.currentTaskPrompt || this.userPrompt || '').match(/([a-zA-Z0-9_\-./]+\.(apk|aab|dex|dylib|so|dll|exe|asar))\b/i);
2649
+ if (promptMatch && promptMatch[1]) {
2650
+ toolParams.filePath = promptMatch[1];
2651
+ if (!toolParams.action)
2652
+ toolParams.action = 'inspect';
2653
+ }
2654
+ }
2655
+ // Direct auto-bridge: peer explicitly targeted a registered host tool
2656
+ response.toolCalls = [{
2657
+ id: `host_auto_${Date.now()}`,
2658
+ type: 'function',
2659
+ function: {
2660
+ name: canonical,
2661
+ arguments: JSON.stringify(toolParams)
2662
+ }
2663
+ }];
2664
+ delete response.toolRoutingError;
2665
+ }
2666
+ else if (toolRoutingRecoveries++ >= 3) {
2667
+ this.emitEvent({ type: 'error', message: `The peer repeatedly invoked unknown host tool ${rawName}. Work remains unfinished.` });
2632
2668
  this.memoryManager.saveHistory(this.messages);
2633
2669
  break;
2634
2670
  }
2635
- this.messages.push({ role: 'system', content: `[TOOL ROUTING REPAIR] ${name} is a Causyne host tool, not a peer-native function. `
2636
- + `Return a complete <tool_call>{"name":${JSON.stringify(name)},"arguments":{...}}</tool_call> as assistant text with the real arguments from its advertised schema. `
2637
- + 'End your response after the envelope. Causyne will execute it through the normal policy gates and supply its actual result. '
2638
- + 'Do not retry the same native function, use dummy shell calls, or assume the host tool already executed. Your other native tools remain available.' });
2639
- this.emitEvent({ type: 'status', message: `Correcting the host-tool route for ${name}…` });
2640
- auditLog.log({ event: 'peer_tool_route_repaired', taskId: this.taskId, tool: name });
2641
- this.memoryManager.saveHistory(this.messages);
2642
- continue;
2671
+ else {
2672
+ this.messages.push({ role: 'system', content: `[TOOL ROUTING REPAIR] ${rawName} is a Causyne host tool, not a peer-native function. `
2673
+ + `Return a complete <tool_call>{"name":${JSON.stringify(rawName)},"arguments":{...}}</tool_call> as assistant text with the real arguments from its advertised schema. `
2674
+ + 'End your response after the envelope. Causyne will execute it through the normal policy gates and supply its actual result. '
2675
+ + 'Do not retry the same native function, use dummy shell calls, or assume the host tool already executed. Your other native tools remain available.' });
2676
+ this.emitEvent({ type: 'status', message: `Correcting the host-tool route for ${rawName}…` });
2677
+ auditLog.log({ event: 'peer_tool_route_repaired', taskId: this.taskId, tool: rawName });
2678
+ this.memoryManager.saveHistory(this.messages);
2679
+ continue;
2680
+ }
2643
2681
  }
2644
2682
  const contentText = response.content || '';
2645
2683
  const lower = contentText.toLowerCase();
@@ -3985,7 +4023,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
3985
4023
  this.memoryManager.saveHistory(this.messages);
3986
4024
  continue;
3987
4025
  }
3988
- if (e instanceof EfficiencyCheckpoint && e.scope === 'turn' && e.reason === 'tokens' && incompleteTurnContinuations < 5) {
4026
+ const isTokenCheckpoint = e instanceof EfficiencyCheckpoint && e.scope === 'turn' && e.reason === 'tokens';
4027
+ const isHardBudget = (Number.isInteger(this.taskTokenLimit) && this.taskTokenLimit > 0)
4028
+ || (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
4029
+ const isDesktopLimit = e?.code === 'AGY_DESKTOP_TASK_LIMIT';
4030
+ if (isTokenCheckpoint && !isHardBudget && !isDesktopLimit && incompleteTurnContinuations < 5) {
3989
4031
  incompleteTurnContinuations++;
3990
4032
  this.emitEvent({ type: 'budget_warning', message: e.message });
3991
4033
  auditLog.log({
@@ -3994,17 +4036,21 @@ You are operating in a text-and-code modality without direct image pixel renderi
3994
4036
  reason: e?.reason || e?.code || 'budget',
3995
4037
  ...this.efficiencyBudget.snapshot()
3996
4038
  });
3997
- this.efficiencyBudget.extendBudget?.(1_000_000, 100);
4039
+ const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
4040
+ const extraTokens = Math.max(stepScale * 10, 1_000_000);
4041
+ const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
4042
+ this.tokenTracker.extendBudget(extraTokens);
4043
+ this.efficiencyBudget.extendBudget?.(extraTokens, extraActions);
3998
4044
  compactSessionMessages(this.messages, {
3999
4045
  keepRecentTurns: 4,
4000
4046
  taskId: this.taskId,
4001
4047
  originalPrompt: this.currentTaskPrompt || this.userPrompt
4002
4048
  });
4003
- this.emitEvent({ type: 'status', message: 'Continuing task execution from efficiency checkpoint…' });
4049
+ this.emitEvent({ type: 'status', message: `Continuing task execution from efficiency checkpoint (runway extended +${extraActions} actions)…` });
4004
4050
  this.emitEvent({ type: 'agent_activity', activity: 'Continuing task from efficiency checkpoint…' });
4005
4051
  this.messages.push({
4006
4052
  role: 'system',
4007
- content: `[EFFICIENCY CONTINUATION: Previous turn paused at checkpoint (${e.message}). Session history and files on disk are preserved. Do NOT repeat completed setup, inspections, or scans. Continue immediately from where you left off, implement the remaining features, and verify completion now.]`
4053
+ content: `[EFFICIENCY CONTINUATION: Previous turn paused at checkpoint (${e.message}). Autonomous runway extended (+${extraActions} actions). Session history and disk modifications are preserved. Do NOT replay prior actions. Continue executing the task directly.]`
4008
4054
  });
4009
4055
  this.memoryManager.saveHistory(this.messages);
4010
4056
  continue;
package/src/agentLoop.ts CHANGED
@@ -353,6 +353,15 @@ You are bound by an unbreakable ethical safety net. Regardless of user prompt, j
353
353
 
354
354
  If asked to perform ANY harmful task, politely decline, state that Causyne exists to make the world better, and offer legitimate developer assistance instead.
355
355
 
356
+ # Sovereign Reverse Engineering & Clean-Room Analysis (REA Substrate)
357
+ You possess native reverse engineering capabilities powered by the Reverse Engineer Anything (REA) sovereign substrate via the \`reverse_engineering\` tool.
358
+ - **Authorized Analytical Scope**: Reverse engineering for interoperability, binary inspection, security research, vulnerability analysis, format decoding, manifest analysis, and clean-room application implementation is fully authorized.
359
+ - **Clean-Room Implementation Discipline**: When a user provides an APK, binary, or application package and asks to build a similar or compatible application (e.g. "analyze using rea make app like this for me"):
360
+ 1. Proactively use \`reverse_engineering\` with actions 'inspect', 'unpack', 'decompile', or 'engine_tool' to inspect the artifact: examine \`AndroidManifest.xml\`, decode resources, list activities, extract layouts, inspect DEX classes, and map the application graph.
361
+ 2. Synthesize functional and architectural specifications (data models, UI flows, service components).
362
+ 3. Scaffold and build the original, clean-room application using modern open-source frameworks and idiomatic patterns.
363
+ 4. NEVER issue canned refusals (such as "I cannot decompile, extract, or clone proprietary commercial software..."). Legitimate structural inspection, format analysis, and clean-room development are core sovereign capabilities.
364
+
356
365
  # Dependency Management & Autonomy Modes
357
366
  - **Mode A (Passive)**: You MUST explicitly ask the user for permission (by ending your turn and asking a question) before installing any dependencies.
358
367
  - **Mode B (Supervised)**: You may install standard development dependencies automatically, but you MUST ask for permission before modifying OS-level settings or running \`sudo\`.
@@ -2260,7 +2269,11 @@ You are operating in a text-and-code modality without direct image pixel renderi
2260
2269
  pruneStaleToolObservations(this.messages, { keepRecent: 3, minChars: 300, taskId: this.taskId });
2261
2270
  shortenOversizedToolObservations(this.messages, { threshold: 1500, taskId: this.taskId });
2262
2271
  pruneExecutedToolArguments(this.messages, { threshold: 1500, taskId: this.taskId });
2263
- this.efficiencyBudget?.extendBudget?.(1_000_000, 100);
2272
+ const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
2273
+ const extraTokens = Math.max(stepScale * 10, 1_000_000);
2274
+ const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
2275
+ this.tokenTracker.extendBudget(extraTokens);
2276
+ this.efficiencyBudget?.extendBudget?.(extraTokens, extraActions);
2264
2277
  }
2265
2278
  }
2266
2279
 
@@ -2769,21 +2782,43 @@ You are operating in a text-and-code modality without direct image pixel renderi
2769
2782
  // If no tool calls, check if the agent is just thinking/planning or actually done
2770
2783
  if (!response.toolCalls || response.toolCalls.length === 0) {
2771
2784
  if (response.toolRoutingError) {
2772
- const name = response.toolRoutingError.tool;
2773
- if (toolRoutingRecoveries++ >= 1) {
2774
- this.emitEvent({ type: 'error', message: `The peer repeatedly invoked host tool ${name} through its native channel. Work remains unfinished.` });
2785
+ const rawName = response.toolRoutingError.tool;
2786
+ const resolved = resolveTool(rawName);
2787
+ if (resolved) {
2788
+ const canonical = canonicalToolName(rawName);
2789
+ const toolParams: Record<string, unknown> = { ...(response.toolRoutingError.parameters || {}) };
2790
+ if (canonical === 'reverse_engineering' && !toolParams.filePath && !toolParams.target && !toolParams.file && !toolParams.path) {
2791
+ const promptMatch = (this.currentTaskPrompt || this.userPrompt || '').match(/([a-zA-Z0-9_\-./]+\.(apk|aab|dex|dylib|so|dll|exe|asar))\b/i);
2792
+ if (promptMatch && promptMatch[1]) {
2793
+ toolParams.filePath = promptMatch[1];
2794
+ if (!toolParams.action) toolParams.action = 'inspect';
2795
+ }
2796
+ }
2797
+ // Direct auto-bridge: peer explicitly targeted a registered host tool
2798
+ response.toolCalls = [{
2799
+ id: `host_auto_${Date.now()}`,
2800
+ type: 'function',
2801
+ function: {
2802
+ name: canonical,
2803
+ arguments: JSON.stringify(toolParams)
2804
+ }
2805
+ }];
2806
+ delete response.toolRoutingError;
2807
+ } else if (toolRoutingRecoveries++ >= 3) {
2808
+ this.emitEvent({ type: 'error', message: `The peer repeatedly invoked unknown host tool ${rawName}. Work remains unfinished.` });
2775
2809
  this.memoryManager.saveHistory(this.messages);
2776
2810
  break;
2811
+ } else {
2812
+ this.messages.push({ role: 'system', content:
2813
+ `[TOOL ROUTING REPAIR] ${rawName} is a Causyne host tool, not a peer-native function. `
2814
+ + `Return a complete <tool_call>{"name":${JSON.stringify(rawName)},"arguments":{...}}</tool_call> as assistant text with the real arguments from its advertised schema. `
2815
+ + 'End your response after the envelope. Causyne will execute it through the normal policy gates and supply its actual result. '
2816
+ + 'Do not retry the same native function, use dummy shell calls, or assume the host tool already executed. Your other native tools remain available.' });
2817
+ this.emitEvent({ type: 'status', message: `Correcting the host-tool route for ${rawName}…` });
2818
+ auditLog.log({ event: 'peer_tool_route_repaired', taskId: this.taskId, tool: rawName });
2819
+ this.memoryManager.saveHistory(this.messages);
2820
+ continue;
2777
2821
  }
2778
- this.messages.push({ role: 'system', content:
2779
- `[TOOL ROUTING REPAIR] ${name} is a Causyne host tool, not a peer-native function. `
2780
- + `Return a complete <tool_call>{"name":${JSON.stringify(name)},"arguments":{...}}</tool_call> as assistant text with the real arguments from its advertised schema. `
2781
- + 'End your response after the envelope. Causyne will execute it through the normal policy gates and supply its actual result. '
2782
- + 'Do not retry the same native function, use dummy shell calls, or assume the host tool already executed. Your other native tools remain available.' });
2783
- this.emitEvent({ type: 'status', message: `Correcting the host-tool route for ${name}…` });
2784
- auditLog.log({ event: 'peer_tool_route_repaired', taskId: this.taskId, tool: name });
2785
- this.memoryManager.saveHistory(this.messages);
2786
- continue;
2787
2822
  }
2788
2823
  const contentText = response.content || '';
2789
2824
  const lower = contentText.toLowerCase();
@@ -4235,7 +4270,12 @@ You are operating in a text-and-code modality without direct image pixel renderi
4235
4270
  this.memoryManager.saveHistory(this.messages);
4236
4271
  continue;
4237
4272
  }
4238
- if (e instanceof EfficiencyCheckpoint && e.scope === 'turn' && e.reason === 'tokens' && incompleteTurnContinuations < 5) {
4273
+ const isTokenCheckpoint = e instanceof EfficiencyCheckpoint && e.scope === 'turn' && e.reason === 'tokens';
4274
+ const isHardBudget = (Number.isInteger(this.taskTokenLimit) && (this.taskTokenLimit as number) > 0)
4275
+ || (this.tokenTracker.budget?.enabled === true && this.tokenTracker.budget?.hardStop === true);
4276
+ const isDesktopLimit = e?.code === 'AGY_DESKTOP_TASK_LIMIT';
4277
+
4278
+ if (isTokenCheckpoint && !isHardBudget && !isDesktopLimit && incompleteTurnContinuations < 5) {
4239
4279
  incompleteTurnContinuations++;
4240
4280
  this.emitEvent({ type: 'budget_warning', message: e.message });
4241
4281
  auditLog.log({
@@ -4244,17 +4284,21 @@ You are operating in a text-and-code modality without direct image pixel renderi
4244
4284
  reason: (e as any)?.reason || (e as any)?.code || 'budget',
4245
4285
  ...this.efficiencyBudget.snapshot()
4246
4286
  });
4247
- this.efficiencyBudget.extendBudget?.(1_000_000, 100);
4287
+ const stepScale = Math.max(this.tokenTracker.largestStepTokens || 50_000, 100_000);
4288
+ const extraTokens = Math.max(stepScale * 10, 1_000_000);
4289
+ const extraActions = Math.max(Math.ceil((this.efficiencyBudget?.getRemainingActions() ?? 50) + 100), 100);
4290
+ this.tokenTracker.extendBudget(extraTokens);
4291
+ this.efficiencyBudget.extendBudget?.(extraTokens, extraActions);
4248
4292
  compactSessionMessages(this.messages, {
4249
4293
  keepRecentTurns: 4,
4250
4294
  taskId: this.taskId,
4251
4295
  originalPrompt: this.currentTaskPrompt || this.userPrompt
4252
4296
  });
4253
- this.emitEvent({ type: 'status', message: 'Continuing task execution from efficiency checkpoint…' });
4297
+ this.emitEvent({ type: 'status', message: `Continuing task execution from efficiency checkpoint (runway extended +${extraActions} actions)…` });
4254
4298
  this.emitEvent({ type: 'agent_activity', activity: 'Continuing task from efficiency checkpoint…' });
4255
4299
  this.messages.push({
4256
4300
  role: 'system',
4257
- content: `[EFFICIENCY CONTINUATION: Previous turn paused at checkpoint (${e.message}). Session history and files on disk are preserved. Do NOT repeat completed setup, inspections, or scans. Continue immediately from where you left off, implement the remaining features, and verify completion now.]`
4301
+ content: `[EFFICIENCY CONTINUATION: Previous turn paused at checkpoint (${e.message}). Autonomous runway extended (+${extraActions} actions). Session history and disk modifications are preserved. Do NOT replay prior actions. Continue executing the task directly.]`
4258
4302
  });
4259
4303
  this.memoryManager.saveHistory(this.messages);
4260
4304
  continue;
@@ -48,10 +48,25 @@ export class SovereignReverseHarness {
48
48
  }
49
49
  this.connectPromise = (async () => {
50
50
  try {
51
+ // 1. Locate local rea binary if installed (sub-second launch, zero network lag)
52
+ let command = 'npx';
53
+ let args = ['--yes', 'rea-agents@6.8.0', '--mcp'];
54
+ const candidatePaths = [
55
+ path.join(process.env.HOME || '', '.local', 'bin', 'rea'),
56
+ '/usr/local/bin/rea',
57
+ '/opt/homebrew/bin/rea'
58
+ ];
59
+ for (const candidate of candidatePaths) {
60
+ if (fs.existsSync(candidate)) {
61
+ command = candidate;
62
+ args = ['--mcp'];
63
+ break;
64
+ }
65
+ }
51
66
  const mcpClient = new McpClient({
52
67
  name: 'causyne_reverse_engineering',
53
- command: 'npx',
54
- args: ['--yes', 'rea-agents@6.8.0', 'mcp'],
68
+ command,
69
+ args,
55
70
  timeoutMs: 60_000
56
71
  });
57
72
  await mcpClient.connect();
@@ -145,10 +160,19 @@ export class SovereignReverseHarness {
145
160
  if (!fs.existsSync(resolved)) {
146
161
  return { success: false, toolName: 'inspect_binary', error: `File not found: ${resolved}`, source: 'engine' };
147
162
  }
163
+ const ext = path.extname(resolved).toLowerCase();
164
+ if (ext === '.apk' || ext === '.aab') {
165
+ const pkg = await this.callEngineTool('inspect_android_package', { path: resolved }, signal);
166
+ if (pkg.success)
167
+ return pkg;
168
+ const dec = await this.callEngineTool('decode_android_resources', { path: resolved }, signal);
169
+ if (dec.success)
170
+ return dec;
171
+ }
148
172
  // Try primary session / overview tools
149
- const overview = await this.callEngineTool('binary_overview', { path: resolved }, signal);
150
- if (overview.success)
151
- return overview;
173
+ const open = await this.callEngineTool('open_binary', { path: resolved }, signal);
174
+ if (open.success)
175
+ return open;
152
176
  const layout = await this.callEngineTool('inspect_binary_layout', { path: resolved }, signal);
153
177
  if (layout.success)
154
178
  return layout;
@@ -224,5 +248,41 @@ export class SovereignReverseHarness {
224
248
  ...(options.script ? { script: options.script } : {})
225
249
  }, signal);
226
250
  }
251
+ /**
252
+ * Decode Android resources (AndroidManifest.xml, resources.arsc, layouts).
253
+ */
254
+ async decodeAndroidResources(apkPath, outputDirectory, signal) {
255
+ const resolved = resolveUserPath(apkPath);
256
+ if (!fs.existsSync(resolved)) {
257
+ return { success: false, toolName: 'decode_android_resources', error: `APK not found: ${resolved}`, source: 'engine' };
258
+ }
259
+ return this.callEngineTool('decode_android_resources', {
260
+ path: resolved,
261
+ ...(outputDirectory ? { output_directory: resolveUserPath(outputDirectory) } : {})
262
+ }, signal);
263
+ }
264
+ /**
265
+ * Search classes or list class hierarchy inside an Android APK.
266
+ */
267
+ async searchAndroidClasses(apkPath, query = '', signal) {
268
+ const resolved = resolveUserPath(apkPath);
269
+ if (!fs.existsSync(resolved)) {
270
+ return { success: false, toolName: 'search_android_classes', error: `APK not found: ${resolved}`, source: 'engine' };
271
+ }
272
+ return this.callEngineTool('search_android_classes', {
273
+ path: resolved,
274
+ query: query || ''
275
+ }, signal);
276
+ }
277
+ /**
278
+ * Project authenticated Android application graph (components, intents, activities).
279
+ */
280
+ async projectAndroidGraph(apkPath, signal) {
281
+ const resolved = resolveUserPath(apkPath);
282
+ if (!fs.existsSync(resolved)) {
283
+ return { success: false, toolName: 'project_android_application_graph', error: `APK not found: ${resolved}`, source: 'engine' };
284
+ }
285
+ return this.callEngineTool('project_android_application_graph', { path: resolved }, signal);
286
+ }
227
287
  }
228
288
  export const sovereignReverseHarness = SovereignReverseHarness.getInstance();
@@ -62,10 +62,28 @@ export class SovereignReverseHarness {
62
62
 
63
63
  this.connectPromise = (async () => {
64
64
  try {
65
+ // 1. Locate local rea binary if installed (sub-second launch, zero network lag)
66
+ let command = 'npx';
67
+ let args = ['--yes', 'rea-agents@6.8.0', '--mcp'];
68
+
69
+ const candidatePaths = [
70
+ path.join(process.env.HOME || '', '.local', 'bin', 'rea'),
71
+ '/usr/local/bin/rea',
72
+ '/opt/homebrew/bin/rea'
73
+ ];
74
+
75
+ for (const candidate of candidatePaths) {
76
+ if (fs.existsSync(candidate)) {
77
+ command = candidate;
78
+ args = ['--mcp'];
79
+ break;
80
+ }
81
+ }
82
+
65
83
  const mcpClient = new McpClient({
66
84
  name: 'causyne_reverse_engineering',
67
- command: 'npx',
68
- args: ['--yes', 'rea-agents@6.8.0', 'mcp'],
85
+ command,
86
+ args,
69
87
  timeoutMs: 60_000
70
88
  });
71
89
 
@@ -165,9 +183,18 @@ export class SovereignReverseHarness {
165
183
  return { success: false, toolName: 'inspect_binary', error: `File not found: ${resolved}`, source: 'engine' };
166
184
  }
167
185
 
186
+ const ext = path.extname(resolved).toLowerCase();
187
+ if (ext === '.apk' || ext === '.aab') {
188
+ const pkg = await this.callEngineTool('inspect_android_package', { path: resolved }, signal);
189
+ if (pkg.success) return pkg;
190
+
191
+ const dec = await this.callEngineTool('decode_android_resources', { path: resolved }, signal);
192
+ if (dec.success) return dec;
193
+ }
194
+
168
195
  // Try primary session / overview tools
169
- const overview = await this.callEngineTool('binary_overview', { path: resolved }, signal);
170
- if (overview.success) return overview;
196
+ const open = await this.callEngineTool('open_binary', { path: resolved }, signal);
197
+ if (open.success) return open;
171
198
 
172
199
  const layout = await this.callEngineTool('inspect_binary_layout', { path: resolved }, signal);
173
200
  if (layout.success) return layout;
@@ -267,6 +294,59 @@ export class SovereignReverseHarness {
267
294
  ...(options.script ? { script: options.script } : {})
268
295
  }, signal);
269
296
  }
297
+
298
+ /**
299
+ * Decode Android resources (AndroidManifest.xml, resources.arsc, layouts).
300
+ */
301
+ public async decodeAndroidResources(
302
+ apkPath: string,
303
+ outputDirectory?: string,
304
+ signal?: AbortSignal
305
+ ): Promise<EngineToolExecutionResult> {
306
+ const resolved = resolveUserPath(apkPath);
307
+ if (!fs.existsSync(resolved)) {
308
+ return { success: false, toolName: 'decode_android_resources', error: `APK not found: ${resolved}`, source: 'engine' };
309
+ }
310
+
311
+ return this.callEngineTool('decode_android_resources', {
312
+ path: resolved,
313
+ ...(outputDirectory ? { output_directory: resolveUserPath(outputDirectory) } : {})
314
+ }, signal);
315
+ }
316
+
317
+ /**
318
+ * Search classes or list class hierarchy inside an Android APK.
319
+ */
320
+ public async searchAndroidClasses(
321
+ apkPath: string,
322
+ query: string = '',
323
+ signal?: AbortSignal
324
+ ): Promise<EngineToolExecutionResult> {
325
+ const resolved = resolveUserPath(apkPath);
326
+ if (!fs.existsSync(resolved)) {
327
+ return { success: false, toolName: 'search_android_classes', error: `APK not found: ${resolved}`, source: 'engine' };
328
+ }
329
+
330
+ return this.callEngineTool('search_android_classes', {
331
+ path: resolved,
332
+ query: query || ''
333
+ }, signal);
334
+ }
335
+
336
+ /**
337
+ * Project authenticated Android application graph (components, intents, activities).
338
+ */
339
+ public async projectAndroidGraph(
340
+ apkPath: string,
341
+ signal?: AbortSignal
342
+ ): Promise<EngineToolExecutionResult> {
343
+ const resolved = resolveUserPath(apkPath);
344
+ if (!fs.existsSync(resolved)) {
345
+ return { success: false, toolName: 'project_android_application_graph', error: `APK not found: ${resolved}`, source: 'engine' };
346
+ }
347
+
348
+ return this.callEngineTool('project_android_application_graph', { path: resolved }, signal);
349
+ }
270
350
  }
271
351
 
272
352
  export const sovereignReverseHarness = SovereignReverseHarness.getInstance();
@@ -44,7 +44,7 @@ export function extractMentions(text) {
44
44
  if (!cleanPath || seen.has(cleanPath))
45
45
  continue;
46
46
  // Do not capture npm scope prefixes on their own or common non-file @ words
47
- if (cleanPath === 'here' || cleanPath === 'all' || cleanPath === 'workspace') {
47
+ if (cleanPath === 'here' || cleanPath === 'all' || cleanPath === 'workspace' || cleanPath === 'rea' || cleanPath === 'rea-agents') {
48
48
  seen.add(cleanPath);
49
49
  mentions.push({ raw, path: cleanPath, isQuoted: false, isMeta: true });
50
50
  continue;
@@ -76,6 +76,10 @@ export async function resolveMentionedContext(prompt, options = {}) {
76
76
  if (m.path === 'workspace' || m.path === 'here') {
77
77
  sections.push(`📁 REFERENCED SCOPE: Whole workspace (${cwd})`);
78
78
  }
79
+ else if (m.path === 'rea' || m.path === 'rea-agents') {
80
+ sections.push(`🔬 REFERENCED CAPABILITY: Reverse Engineer Anything (REA) Substrate active.\n` +
81
+ `Use the 'reverse_engineering' tool with action 'inspect', 'unpack', 'decompile', or 'engine_tool' to analyze APKs, binaries, and assemblies.`);
82
+ }
79
83
  continue;
80
84
  }
81
85
  let targetPath = path.resolve(cwd, m.path);
@@ -136,20 +140,29 @@ export async function resolveMentionedContext(prompt, options = {}) {
136
140
  more);
137
141
  }
138
142
  else if (stats.isFile()) {
139
- const content = fs.readFileSync(targetPath, 'utf8');
140
- const lines = content.split('\n');
141
- let body;
142
- if (lines.length > MAX_MENTION_FILE_LINES) {
143
- body = lines.slice(0, MAX_MENTION_FILE_LINES).join('\n') +
144
- `\n\n... [Truncated: showing first ${MAX_MENTION_FILE_LINES} of ${lines.length} lines. Use fs.read for remaining lines.]`;
143
+ const ext = path.extname(targetPath).toLowerCase();
144
+ const isBinary = /\.(apk|aab|dex|dylib|so|dll|exe|bin|asar|zip|tar|gz|tgz)$/i.test(ext);
145
+ if (isBinary) {
146
+ const sizeMb = (stats.size / (1024 * 1024)).toFixed(2);
147
+ sections.push(`📦 REFERENCED BINARY PACKAGE: ${relPath} (${stats.size.toLocaleString()} bytes, ~${sizeMb} MB, format: ${ext.toUpperCase().replace('.', '')})\n` +
148
+ `Note: This is a binary/compiled package. Do not read raw bytes. Use the 'reverse_engineering' tool with action 'inspect', 'unpack', or 'decompile' to analyze manifest, classes, resources, and architecture.`);
145
149
  }
146
150
  else {
147
- body = content;
151
+ const content = fs.readFileSync(targetPath, 'utf8');
152
+ const lines = content.split('\n');
153
+ let body;
154
+ if (lines.length > MAX_MENTION_FILE_LINES) {
155
+ body = lines.slice(0, MAX_MENTION_FILE_LINES).join('\n') +
156
+ `\n\n... [Truncated: showing first ${MAX_MENTION_FILE_LINES} of ${lines.length} lines. Use fs.read for remaining lines.]`;
157
+ }
158
+ else {
159
+ body = content;
160
+ }
161
+ sections.push(`📄 REFERENCED FILE: ${relPath} (${lines.length} lines):\n` +
162
+ '```\n' +
163
+ body + '\n' +
164
+ '```');
148
165
  }
149
- sections.push(`📄 REFERENCED FILE: ${relPath} (${lines.length} lines):\n` +
150
- '```\n' +
151
- body + '\n' +
152
- '```');
153
166
  }
154
167
  }
155
168
  catch (err) {
@@ -67,7 +67,7 @@ export function extractMentions(text: string): Mention[] {
67
67
  if (!cleanPath || seen.has(cleanPath)) continue;
68
68
 
69
69
  // Do not capture npm scope prefixes on their own or common non-file @ words
70
- if (cleanPath === 'here' || cleanPath === 'all' || cleanPath === 'workspace') {
70
+ if (cleanPath === 'here' || cleanPath === 'all' || cleanPath === 'workspace' || cleanPath === 'rea' || cleanPath === 'rea-agents') {
71
71
  seen.add(cleanPath);
72
72
  mentions.push({ raw, path: cleanPath, isQuoted: false, isMeta: true });
73
73
  continue;
@@ -106,6 +106,11 @@ export async function resolveMentionedContext(
106
106
  if (m.isMeta) {
107
107
  if (m.path === 'workspace' || m.path === 'here') {
108
108
  sections.push(`📁 REFERENCED SCOPE: Whole workspace (${cwd})`);
109
+ } else if (m.path === 'rea' || m.path === 'rea-agents') {
110
+ sections.push(
111
+ `🔬 REFERENCED CAPABILITY: Reverse Engineer Anything (REA) Substrate active.\n` +
112
+ `Use the 'reverse_engineering' tool with action 'inspect', 'unpack', 'decompile', or 'engine_tool' to analyze APKs, binaries, and assemblies.`
113
+ );
109
114
  }
110
115
  continue;
111
116
  }
@@ -175,22 +180,32 @@ export async function resolveMentionedContext(
175
180
  more
176
181
  );
177
182
  } else if (stats.isFile()) {
178
- const content = fs.readFileSync(targetPath, 'utf8');
179
- const lines = content.split('\n');
180
- let body: string;
181
- if (lines.length > MAX_MENTION_FILE_LINES) {
182
- body = lines.slice(0, MAX_MENTION_FILE_LINES).join('\n') +
183
- `\n\n... [Truncated: showing first ${MAX_MENTION_FILE_LINES} of ${lines.length} lines. Use fs.read for remaining lines.]`;
183
+ const ext = path.extname(targetPath).toLowerCase();
184
+ const isBinary = /\.(apk|aab|dex|dylib|so|dll|exe|bin|asar|zip|tar|gz|tgz)$/i.test(ext);
185
+ if (isBinary) {
186
+ const sizeMb = (stats.size / (1024 * 1024)).toFixed(2);
187
+ sections.push(
188
+ `📦 REFERENCED BINARY PACKAGE: ${relPath} (${stats.size.toLocaleString()} bytes, ~${sizeMb} MB, format: ${ext.toUpperCase().replace('.', '')})\n` +
189
+ `Note: This is a binary/compiled package. Do not read raw bytes. Use the 'reverse_engineering' tool with action 'inspect', 'unpack', or 'decompile' to analyze manifest, classes, resources, and architecture.`
190
+ );
184
191
  } else {
185
- body = content;
186
- }
192
+ const content = fs.readFileSync(targetPath, 'utf8');
193
+ const lines = content.split('\n');
194
+ let body: string;
195
+ if (lines.length > MAX_MENTION_FILE_LINES) {
196
+ body = lines.slice(0, MAX_MENTION_FILE_LINES).join('\n') +
197
+ `\n\n... [Truncated: showing first ${MAX_MENTION_FILE_LINES} of ${lines.length} lines. Use fs.read for remaining lines.]`;
198
+ } else {
199
+ body = content;
200
+ }
187
201
 
188
- sections.push(
189
- `📄 REFERENCED FILE: ${relPath} (${lines.length} lines):\n` +
190
- '```\n' +
191
- body + '\n' +
192
- '```'
193
- );
202
+ sections.push(
203
+ `📄 REFERENCED FILE: ${relPath} (${lines.length} lines):\n` +
204
+ '```\n' +
205
+ body + '\n' +
206
+ '```'
207
+ );
208
+ }
194
209
  }
195
210
  } catch (err: unknown) {
196
211
  const msg = err instanceof Error ? err.message : String(err);
@@ -486,7 +486,15 @@ export class AcpProvider extends LLMProvider {
486
486
  if (isInvalidPseudoTool) {
487
487
  const requested = typeof input.tool === 'string' ? input.tool : '';
488
488
  if (!this.toolRoutingError && requested && normalizeToolContracts(this.peerServices?.tools || []).some(tool => tool.name === requested)) {
489
- this.toolRoutingError = { tool: requested, message: 'Host tool requested through the peer-native channel' };
489
+ const rawArgs = (input.args && typeof input.args === 'object') ? input.args
490
+ : (input.parameters && typeof input.parameters === 'object') ? input.parameters
491
+ : (earlier?.parameters && typeof earlier.parameters === 'object') ? earlier.parameters
492
+ : undefined;
493
+ this.toolRoutingError = {
494
+ tool: requested,
495
+ message: typeof input.error === 'string' ? input.error : 'Host tool requested through the peer-native channel',
496
+ parameters: rawArgs
497
+ };
490
498
  client.notifyCancel(sessionId);
491
499
  }
492
500
  this.liveFileActions.delete(id);
@@ -487,7 +487,15 @@ export class AcpProvider extends LLMProvider {
487
487
  if (isInvalidPseudoTool) {
488
488
  const requested = typeof input.tool === 'string' ? input.tool : '';
489
489
  if (!this.toolRoutingError && requested && normalizeToolContracts(this.peerServices?.tools || []).some(tool => tool.name === requested)) {
490
- this.toolRoutingError = { tool: requested, message: 'Host tool requested through the peer-native channel' };
490
+ const rawArgs = (input.args && typeof input.args === 'object') ? input.args
491
+ : (input.parameters && typeof input.parameters === 'object') ? input.parameters
492
+ : (earlier?.parameters && typeof earlier.parameters === 'object') ? earlier.parameters
493
+ : undefined;
494
+ this.toolRoutingError = {
495
+ tool: requested,
496
+ message: typeof input.error === 'string' ? input.error : 'Host tool requested through the peer-native channel',
497
+ parameters: rawArgs
498
+ };
491
499
  client.notifyCancel(sessionId);
492
500
  }
493
501
  this.liveFileActions.delete(id);
@@ -48,7 +48,7 @@ export interface ChatResponse {
48
48
  reasoningContent?: string | undefined;
49
49
  thinkingBlocks?: any[] | undefined;
50
50
  externalActions?: ChatResponseAction[] | undefined;
51
- toolRoutingError?: { tool: string; message: string } | undefined;
51
+ toolRoutingError?: { tool: string; message: string; parameters?: Record<string, unknown> | undefined } | undefined;
52
52
  incompleteTurn?: boolean | undefined;
53
53
  }
54
54
 
@@ -90,6 +90,11 @@ export class UnifiedBudgetEnforcer {
90
90
  this.maxTurnTokens = Math.max(this.maxTurnTokens, extraTokens);
91
91
  this.maxTurnActions = Math.max(this.maxTurnActions, this.actions + extraActions);
92
92
  }
93
+ extendForAutonomousMomentum(actionCount = 50, tokenCount = 500_000) {
94
+ this.maxTurnActions = Math.max(this.maxTurnActions, this.actions + actionCount);
95
+ this.maxTurnTokens = Math.max(this.maxTurnTokens, tokenCount);
96
+ this.maxTaskTokens = Math.max(this.maxTaskTokens, this.tokens + tokenCount);
97
+ }
93
98
  recordUsage(usage) {
94
99
  const fresh = noncachedTokens(usage);
95
100
  this.tokens += fresh;
@@ -93,6 +93,12 @@ export class UnifiedBudgetEnforcer {
93
93
  this.maxTurnActions = Math.max(this.maxTurnActions, this.actions + extraActions);
94
94
  }
95
95
 
96
+ extendForAutonomousMomentum(actionCount = 50, tokenCount = 500_000): void {
97
+ this.maxTurnActions = Math.max(this.maxTurnActions, this.actions + actionCount);
98
+ this.maxTurnTokens = Math.max(this.maxTurnTokens, tokenCount);
99
+ this.maxTaskTokens = Math.max(this.maxTaskTokens, this.tokens + tokenCount);
100
+ }
101
+
96
102
  recordUsage(usage: BudgetUsage): void {
97
103
  const fresh = noncachedTokens(usage);
98
104
  this.tokens += fresh;
@@ -338,6 +338,14 @@ export class TokenTracker {
338
338
  }
339
339
  return { allowed: true, used: this.taskTokens, limit, projected };
340
340
  }
341
+ extendBudget(extraTokens) {
342
+ if (this.budget && typeof this.budget === 'object') {
343
+ const current = Number(this.budget.maxTokensPerTask || 0);
344
+ if (current > 0) {
345
+ this.budget.maxTokensPerTask = Math.max(current + extraTokens, this.taskTokens + extraTokens);
346
+ }
347
+ }
348
+ }
341
349
  resetTask() {
342
350
  this.taskTokens = 0;
343
351
  this.taskCostUsd = 0;
@@ -447,6 +447,15 @@ export class TokenTracker {
447
447
  return { allowed: true, used: this.taskTokens, limit, projected };
448
448
  }
449
449
 
450
+ extendBudget(extraTokens: number): void {
451
+ if (this.budget && typeof this.budget === 'object') {
452
+ const current = Number(this.budget.maxTokensPerTask || 0);
453
+ if (current > 0) {
454
+ this.budget.maxTokensPerTask = Math.max(current + extraTokens, this.taskTokens + extraTokens);
455
+ }
456
+ }
457
+ }
458
+
450
459
  resetTask(): void {
451
460
  this.taskTokens = 0;
452
461
  this.taskCostUsd = 0;
package/src/toolPacks.js CHANGED
@@ -331,7 +331,7 @@ const WEB_INTENT = /\b(web|webpage|website|frontend|front-end|landing page|homep
331
331
  const MEDIA_INTENT = /\b(image|images|picture|photo|render|3d model|blender|animation|animate|video|movie|film|audio|sound|sfx|music|song|voice|tts|text.to.speech|narration|podcast|thumbnail|poster|illustration|logo)\b/i;
332
332
  const SYSTEM_INTENT = /\b(process|processes|pid|kill|port|zip|unzip|tar|archive|compress|extract|clipboard|copy to clipboard|print|printer|open in browser|launch app|computer use|vision grounding|desktop vision|gui agent|coordinate click|desktop control)\b/i;
333
333
  const ADVANCED_INTENT = /\b(pdf|document|proposal|screenplay|shotlist|shot list|voiceover|dubbing|forge a tool|custom tool|new tool|plugin|plugins|custom plugin|subagent|sub-agent|parallel agent|swarm|ast|symbols|refactor across)\b/i;
334
- const REVERSE_ENGINEERING_INTENT = /\b(decompile|disassemble|binary|binaries|apk|dex|elf|mach-o|pe|coff|reverse engineer|reverse-engineering|reverse_engineering|sourcemap|deobfuscate|asar|symbols|ghidra|rizin|radare|hopper|frida|hook script|mitigations|pie|canary)\b/i;
334
+ const REVERSE_ENGINEERING_INTENT = /\b(rea|rea-agents|decompile|decompiling|decompilation|disassemble|disassembly|disassembling|binary|binaries|apk|aab|dex|elf|mach-o|pe|coff|reverse[\s_-]?engineer(ing)?|sourcemap|deobfuscate|asar|symbols|ghidra|rizin|radare|hopper|frida|hook script|mitigations|pie|canary|clean[- ]?room)\b|\.(apk|aab|dex|dylib|so|dll|exe|asar)\b/i;
335
335
  const INTENT_MATCHERS = {
336
336
  game: GAME_INTENT,
337
337
  web: WEB_INTENT,
package/src/toolPacks.ts CHANGED
@@ -376,7 +376,7 @@ const SYSTEM_INTENT = /\b(process|processes|pid|kill|port|zip|unzip|tar|archive|
376
376
 
377
377
  const ADVANCED_INTENT = /\b(pdf|document|proposal|screenplay|shotlist|shot list|voiceover|dubbing|forge a tool|custom tool|new tool|plugin|plugins|custom plugin|subagent|sub-agent|parallel agent|swarm|ast|symbols|refactor across)\b/i;
378
378
 
379
- const REVERSE_ENGINEERING_INTENT = /\b(decompile|disassemble|binary|binaries|apk|dex|elf|mach-o|pe|coff|reverse engineer|reverse-engineering|reverse_engineering|sourcemap|deobfuscate|asar|symbols|ghidra|rizin|radare|hopper|frida|hook script|mitigations|pie|canary)\b/i;
379
+ const REVERSE_ENGINEERING_INTENT = /\b(rea|rea-agents|decompile|decompiling|decompilation|disassemble|disassembly|disassembling|binary|binaries|apk|aab|dex|elf|mach-o|pe|coff|reverse[\s_-]?engineer(ing)?|sourcemap|deobfuscate|asar|symbols|ghidra|rizin|radare|hopper|frida|hook script|mitigations|pie|canary|clean[- ]?room)\b|\.(apk|aab|dex|dylib|so|dll|exe|asar)\b/i;
380
380
 
381
381
  const INTENT_MATCHERS: Record<PackName, RegExp> = {
382
382
  game: GAME_INTENT,
@@ -239,7 +239,7 @@ export const reverseEngineering = {
239
239
  properties: {
240
240
  action: {
241
241
  type: 'string',
242
- enum: ['inspect', 'decompile', 'unpack', 'deobfuscate', 'trace', 'status', 'engine_tool', 'list_tools'],
242
+ enum: ['inspect', 'decompile', 'unpack', 'deobfuscate', 'trace', 'status', 'engine_tool', 'list_tools', 'decode_resources', 'search_classes', 'graph'],
243
243
  description: 'Reverse engineering action to perform.'
244
244
  },
245
245
  filePath: {
@@ -287,14 +287,40 @@ export const reverseEngineering = {
287
287
  toolArgs: {
288
288
  type: 'object',
289
289
  description: 'Arguments payload for engine_tool.'
290
+ },
291
+ query: {
292
+ type: 'string',
293
+ description: 'Class, method, or string search query for reverse engineering.'
290
294
  }
291
295
  },
292
296
  required: ['action']
293
297
  }
294
298
  },
295
299
  async execute(args, context = {}) {
296
- const action = String(args['action'] || 'status');
297
- const rawPath = typeof args['filePath'] === 'string' ? args['filePath'] : undefined;
300
+ const rawPath = typeof args['filePath'] === 'string' ? args['filePath']
301
+ : typeof args['file'] === 'string' ? args['file']
302
+ : typeof args['path'] === 'string' ? args['path']
303
+ : typeof args['apk'] === 'string' ? args['apk']
304
+ : typeof args['binary'] === 'string' ? args['binary']
305
+ : (typeof args['target'] === 'string' && args['action'] !== 'trace' ? args['target'] : undefined);
306
+ let rawAction = typeof args['action'] === 'string' ? args['action']
307
+ : typeof args['operation'] === 'string' ? args['operation']
308
+ : typeof args['mode'] === 'string' ? args['mode']
309
+ : '';
310
+ if (!rawAction && (typeof args['toolName'] === 'string' || typeof args['engineTool'] === 'string')) {
311
+ rawAction = 'engine_tool';
312
+ }
313
+ if (['analyze', 'info', 'check', 'probe', 'inspect_package'].includes(rawAction))
314
+ rawAction = 'inspect';
315
+ if (['disassemble', 'disasm'].includes(rawAction))
316
+ rawAction = 'decompile';
317
+ if (['decode_resources', 'resources', 'decode'].includes(rawAction))
318
+ rawAction = 'decode_resources';
319
+ if (['search_classes', 'classes'].includes(rawAction))
320
+ rawAction = 'search_classes';
321
+ if (['graph', 'application_graph'].includes(rawAction))
322
+ rawAction = 'graph';
323
+ const action = (rawAction || (rawPath ? 'inspect' : 'status'));
298
324
  const outputDir = typeof args['outputDir'] === 'string' ? args['outputDir'] : undefined;
299
325
  const functionName = typeof args['functionName'] === 'string' ? args['functionName'] : undefined;
300
326
  const address = typeof args['address'] === 'string' ? args['address'] : undefined;
@@ -341,7 +367,8 @@ export const reverseEngineering = {
341
367
  'Electron ASAR pickle header inspection & extraction',
342
368
  'JavaScript sourcemap recovery and route harvesting',
343
369
  'Dynamic runtime tracing and API observation',
344
- 'Headless MCP engine with 229 specialized reverse engineering tools'
370
+ 'Headless MCP engine with 170+ specialized reverse engineering tools',
371
+ 'Android APK resource decoding, class hierarchy & graph projection'
345
372
  ]
346
373
  };
347
374
  }
@@ -357,7 +384,7 @@ export const reverseEngineering = {
357
384
  }
358
385
  // ── ACTION: ENGINE_TOOL ───────────────────────────────────────────────
359
386
  if (action === 'engine_tool') {
360
- const toolName = typeof args['toolName'] === 'string' ? args['toolName'] : '';
387
+ const toolName = typeof args['toolName'] === 'string' ? args['toolName'] : typeof args['engineTool'] === 'string' ? args['engineTool'] : '';
361
388
  if (!toolName) {
362
389
  return { success: false, error: 'toolName parameter is required for action "engine_tool".' };
363
390
  }
@@ -377,7 +404,7 @@ export const reverseEngineering = {
377
404
  error: res.error
378
405
  };
379
406
  }
380
- // Require filePath for inspect, decompile, unpack, deobfuscate
407
+ // Require filePath for inspect, decompile, unpack, deobfuscate, decode_resources, search_classes, graph
381
408
  if (!rawPath && action !== 'trace') {
382
409
  return { success: false, error: `Action "${action}" requires a valid "filePath" parameter.` };
383
410
  }
@@ -385,6 +412,53 @@ export const reverseEngineering = {
385
412
  if (resolvedFile && !fs.existsSync(resolvedFile)) {
386
413
  return { success: false, error: `File not found: ${resolvedFile}` };
387
414
  }
415
+ // ── ACTION: DECODE_RESOURCES ──────────────────────────────────────────
416
+ if (action === 'decode_resources') {
417
+ const res = await sovereignReverseHarness.decodeAndroidResources(resolvedFile, outputDir, context.signal);
418
+ const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
419
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_decode_resources`, textOutput);
420
+ return {
421
+ success: res.success,
422
+ action: 'decode_resources',
423
+ filePath: resolvedFile,
424
+ preview: stored.contentForModel,
425
+ isTruncated: stored.isTruncated,
426
+ diskPath: stored.diskPath,
427
+ error: res.error
428
+ };
429
+ }
430
+ // ── ACTION: SEARCH_CLASSES ───────────────────────────────────────────
431
+ if (action === 'search_classes') {
432
+ const query = String(args['query'] || '');
433
+ const res = await sovereignReverseHarness.searchAndroidClasses(resolvedFile, query, context.signal);
434
+ const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
435
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_search_classes`, textOutput);
436
+ return {
437
+ success: res.success,
438
+ action: 'search_classes',
439
+ filePath: resolvedFile,
440
+ query,
441
+ preview: stored.contentForModel,
442
+ isTruncated: stored.isTruncated,
443
+ diskPath: stored.diskPath,
444
+ error: res.error
445
+ };
446
+ }
447
+ // ── ACTION: GRAPH ─────────────────────────────────────────────────────
448
+ if (action === 'graph') {
449
+ const res = await sovereignReverseHarness.projectAndroidGraph(resolvedFile, context.signal);
450
+ const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
451
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_graph`, textOutput);
452
+ return {
453
+ success: res.success,
454
+ action: 'graph',
455
+ filePath: resolvedFile,
456
+ preview: stored.contentForModel,
457
+ isTruncated: stored.isTruncated,
458
+ diskPath: stored.diskPath,
459
+ error: res.error
460
+ };
461
+ }
388
462
  // ── ACTION: INSPECT ───────────────────────────────────────────────────
389
463
  if (action === 'inspect') {
390
464
  try {
@@ -424,9 +498,26 @@ export const reverseEngineering = {
424
498
  result.format = 'WebAssembly';
425
499
  result.architecture = 'wasm32 / wasm64';
426
500
  }
427
- else if (headerBuf[0] === 0x50 && headerBuf[1] === 0x4b && headerBuf[2] === 0x03 && headerBuf[3] === 0x04) {
501
+ else if ((headerBuf[0] === 0x50 && headerBuf[1] === 0x4b && headerBuf[2] === 0x03 && headerBuf[3] === 0x04) ||
502
+ resolvedFile.toLowerCase().endsWith('.apk')) {
428
503
  result.format = 'APK/ZIP';
429
- result.fileType = 'Compressed Archive / Package';
504
+ result.fileType = 'Android Application Package (APK)';
505
+ try {
506
+ const unzipList = await execFileAsync('unzip', ['-l', resolvedFile], { timeout: 15000 });
507
+ const lines = unzipList.stdout.split('\n');
508
+ const dexFiles = lines.filter(l => l.includes('.dex')).map(l => l.trim().split(/\s+/).pop());
509
+ const hasManifest = lines.some(l => l.includes('AndroidManifest.xml'));
510
+ const nativeLibs = lines.filter(l => l.includes('lib/')).slice(0, 15).map(l => l.trim().split(/\s+/).pop());
511
+ result.metadata = {
512
+ dexFiles,
513
+ hasManifest,
514
+ totalEntries: lines.length,
515
+ sampleNativeLibraries: nativeLibs
516
+ };
517
+ }
518
+ catch {
519
+ // unzip fallback
520
+ }
430
521
  }
431
522
  else {
432
523
  const asar = parseAsarHeader(headerBuf);
@@ -30,7 +30,10 @@ export type ReverseEngineeringAction =
30
30
  | 'trace'
31
31
  | 'status'
32
32
  | 'engine_tool'
33
- | 'list_tools';
33
+ | 'list_tools'
34
+ | 'decode_resources'
35
+ | 'search_classes'
36
+ | 'graph';
34
37
 
35
38
  export interface BinaryMitigations {
36
39
  pie?: boolean | undefined;
@@ -69,6 +72,7 @@ export interface ReverseEngineeringParams {
69
72
  script?: string | undefined;
70
73
  toolName?: string | undefined;
71
74
  toolArgs?: Record<string, unknown> | undefined;
75
+ query?: string | undefined;
72
76
  }
73
77
 
74
78
  // ─────────────────────────────────────────────────────────────────────────────
@@ -318,7 +322,7 @@ export const reverseEngineering = {
318
322
  properties: {
319
323
  action: {
320
324
  type: 'string',
321
- enum: ['inspect', 'decompile', 'unpack', 'deobfuscate', 'trace', 'status', 'engine_tool', 'list_tools'],
325
+ enum: ['inspect', 'decompile', 'unpack', 'deobfuscate', 'trace', 'status', 'engine_tool', 'list_tools', 'decode_resources', 'search_classes', 'graph'],
322
326
  description: 'Reverse engineering action to perform.'
323
327
  },
324
328
  filePath: {
@@ -366,6 +370,10 @@ export const reverseEngineering = {
366
370
  toolArgs: {
367
371
  type: 'object',
368
372
  description: 'Arguments payload for engine_tool.'
373
+ },
374
+ query: {
375
+ type: 'string',
376
+ description: 'Class, method, or string search query for reverse engineering.'
369
377
  }
370
378
  },
371
379
  required: ['action']
@@ -373,8 +381,29 @@ export const reverseEngineering = {
373
381
  },
374
382
 
375
383
  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;
377
- const rawPath = typeof args['filePath'] === 'string' ? args['filePath'] : undefined;
384
+ const rawPath = typeof args['filePath'] === 'string' ? args['filePath']
385
+ : typeof args['file'] === 'string' ? args['file']
386
+ : typeof args['path'] === 'string' ? args['path']
387
+ : typeof args['apk'] === 'string' ? args['apk']
388
+ : typeof args['binary'] === 'string' ? args['binary']
389
+ : (typeof args['target'] === 'string' && args['action'] !== 'trace' ? args['target'] : undefined);
390
+
391
+ let rawAction = typeof args['action'] === 'string' ? args['action']
392
+ : typeof args['operation'] === 'string' ? args['operation']
393
+ : typeof args['mode'] === 'string' ? args['mode']
394
+ : '';
395
+
396
+ if (!rawAction && (typeof args['toolName'] === 'string' || typeof args['engineTool'] === 'string')) {
397
+ rawAction = 'engine_tool';
398
+ }
399
+
400
+ if (['analyze', 'info', 'check', 'probe', 'inspect_package'].includes(rawAction)) rawAction = 'inspect';
401
+ if (['disassemble', 'disasm'].includes(rawAction)) rawAction = 'decompile';
402
+ if (['decode_resources', 'resources', 'decode'].includes(rawAction)) rawAction = 'decode_resources';
403
+ if (['search_classes', 'classes'].includes(rawAction)) rawAction = 'search_classes';
404
+ if (['graph', 'application_graph'].includes(rawAction)) rawAction = 'graph';
405
+
406
+ const action = (rawAction || (rawPath ? 'inspect' : 'status')) as ReverseEngineeringAction;
378
407
  const outputDir = typeof args['outputDir'] === 'string' ? args['outputDir'] : undefined;
379
408
  const functionName = typeof args['functionName'] === 'string' ? args['functionName'] : undefined;
380
409
  const address = typeof args['address'] === 'string' ? args['address'] : undefined;
@@ -424,7 +453,8 @@ export const reverseEngineering = {
424
453
  'Electron ASAR pickle header inspection & extraction',
425
454
  'JavaScript sourcemap recovery and route harvesting',
426
455
  'Dynamic runtime tracing and API observation',
427
- 'Headless MCP engine with 229 specialized reverse engineering tools'
456
+ 'Headless MCP engine with 170+ specialized reverse engineering tools',
457
+ 'Android APK resource decoding, class hierarchy & graph projection'
428
458
  ]
429
459
  };
430
460
  }
@@ -442,7 +472,7 @@ export const reverseEngineering = {
442
472
 
443
473
  // ── ACTION: ENGINE_TOOL ───────────────────────────────────────────────
444
474
  if (action === 'engine_tool') {
445
- const toolName = typeof args['toolName'] === 'string' ? args['toolName'] : '';
475
+ const toolName = typeof args['toolName'] === 'string' ? args['toolName'] : typeof args['engineTool'] === 'string' ? args['engineTool'] : '';
446
476
  if (!toolName) {
447
477
  return { success: false, error: 'toolName parameter is required for action "engine_tool".' };
448
478
  }
@@ -465,7 +495,7 @@ export const reverseEngineering = {
465
495
  };
466
496
  }
467
497
 
468
- // Require filePath for inspect, decompile, unpack, deobfuscate
498
+ // Require filePath for inspect, decompile, unpack, deobfuscate, decode_resources, search_classes, graph
469
499
  if (!rawPath && action !== 'trace') {
470
500
  return { success: false, error: `Action "${action}" requires a valid "filePath" parameter.` };
471
501
  }
@@ -475,6 +505,56 @@ export const reverseEngineering = {
475
505
  return { success: false, error: `File not found: ${resolvedFile}` };
476
506
  }
477
507
 
508
+ // ── ACTION: DECODE_RESOURCES ──────────────────────────────────────────
509
+ if (action === 'decode_resources') {
510
+ const res = await sovereignReverseHarness.decodeAndroidResources(resolvedFile, outputDir, context.signal);
511
+ const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
512
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_decode_resources`, textOutput);
513
+ return {
514
+ success: res.success,
515
+ action: 'decode_resources',
516
+ filePath: resolvedFile,
517
+ preview: stored.contentForModel,
518
+ isTruncated: stored.isTruncated,
519
+ diskPath: stored.diskPath,
520
+ error: res.error
521
+ };
522
+ }
523
+
524
+ // ── ACTION: SEARCH_CLASSES ───────────────────────────────────────────
525
+ if (action === 'search_classes') {
526
+ const query = String(args['query'] || '');
527
+ const res = await sovereignReverseHarness.searchAndroidClasses(resolvedFile, query, context.signal);
528
+ const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
529
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_search_classes`, textOutput);
530
+ return {
531
+ success: res.success,
532
+ action: 'search_classes',
533
+ filePath: resolvedFile,
534
+ query,
535
+ preview: stored.contentForModel,
536
+ isTruncated: stored.isTruncated,
537
+ diskPath: stored.diskPath,
538
+ error: res.error
539
+ };
540
+ }
541
+
542
+ // ── ACTION: GRAPH ─────────────────────────────────────────────────────
543
+ if (action === 'graph') {
544
+ const res = await sovereignReverseHarness.projectAndroidGraph(resolvedFile, context.signal);
545
+ const textOutput = res.output || (res.structuredContent ? JSON.stringify(res.structuredContent, null, 2) : res.error || '');
546
+ const stored = outputStore.processToolOutput(sessionId, `${callId}_graph`, textOutput);
547
+ return {
548
+ success: res.success,
549
+ action: 'graph',
550
+ filePath: resolvedFile,
551
+ preview: stored.contentForModel,
552
+ isTruncated: stored.isTruncated,
553
+ diskPath: stored.diskPath,
554
+ error: res.error
555
+ };
556
+ }
557
+
478
558
  // ── ACTION: INSPECT ───────────────────────────────────────────────────
479
559
  if (action === 'inspect') {
480
560
  try {
@@ -515,9 +595,27 @@ export const reverseEngineering = {
515
595
  } else if (headerBuf[0] === 0x00 && headerBuf[1] === 0x61 && headerBuf[2] === 0x73 && headerBuf[3] === 0x6d) {
516
596
  result.format = 'WebAssembly';
517
597
  result.architecture = 'wasm32 / wasm64';
518
- } else if (headerBuf[0] === 0x50 && headerBuf[1] === 0x4b && headerBuf[2] === 0x03 && headerBuf[3] === 0x04) {
598
+ } else if (
599
+ (headerBuf[0] === 0x50 && headerBuf[1] === 0x4b && headerBuf[2] === 0x03 && headerBuf[3] === 0x04) ||
600
+ resolvedFile.toLowerCase().endsWith('.apk')
601
+ ) {
519
602
  result.format = 'APK/ZIP';
520
- result.fileType = 'Compressed Archive / Package';
603
+ result.fileType = 'Android Application Package (APK)';
604
+ try {
605
+ const unzipList = await execFileAsync('unzip', ['-l', resolvedFile], { timeout: 15000 });
606
+ const lines = unzipList.stdout.split('\n');
607
+ const dexFiles = lines.filter(l => l.includes('.dex')).map(l => l.trim().split(/\s+/).pop());
608
+ const hasManifest = lines.some(l => l.includes('AndroidManifest.xml'));
609
+ const nativeLibs = lines.filter(l => l.includes('lib/')).slice(0, 15).map(l => l.trim().split(/\s+/).pop());
610
+ result.metadata = {
611
+ dexFiles,
612
+ hasManifest,
613
+ totalEntries: lines.length,
614
+ sampleNativeLibraries: nativeLibs
615
+ };
616
+ } catch {
617
+ // unzip fallback
618
+ }
521
619
  } else {
522
620
  const asar = parseAsarHeader(headerBuf);
523
621
  if (asar) {