@causyne/agent 1.20.18 → 1.20.20

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.
@@ -0,0 +1,360 @@
1
+ // Causyne package updates.
2
+ //
3
+ // Updates are intentionally limited to installations managed by npm or by the
4
+ // causyne.com installer. A source checkout is never rewritten. Commands are
5
+ // passed as argv arrays with shell disabled, and the only accepted package is
6
+ // the public @causyne/agent package from the npm registry.
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { spawnSync, type SpawnSyncReturns } from 'node:child_process';
12
+
13
+ import { UI } from './utils/cli_ui.js';
14
+ import { causyneHome } from './utils/paths.js';
15
+ import { getPackageVersion } from './version.js';
16
+
17
+ const PACKAGE_NAME = '@causyne/agent';
18
+ const REGISTRY_LATEST = 'https://registry.npmjs.org/@causyne%2fagent/latest';
19
+ const DEFAULT_CHECK_INTERVAL_MS = 60 * 60 * 1000; // 1 hour for active developer agility
20
+ const ERROR_RETRY_INTERVAL_MS = 2 * 60 * 1000; // 2 minutes retry on network error
21
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
22
+
23
+ export interface VersionParts {
24
+ numbers: [number, number, number];
25
+ prerelease: string;
26
+ }
27
+
28
+ export interface InstallationInfo {
29
+ managed: boolean;
30
+ type: 'causyne.com installer' | 'global npm' | 'source checkout';
31
+ prefix: string | null;
32
+ packageRoot: string;
33
+ npmCommand: string;
34
+ }
35
+
36
+ export interface UpdateState {
37
+ checkedAt?: number;
38
+ latest?: string;
39
+ installedAt?: number;
40
+ error?: string;
41
+ }
42
+
43
+ export interface CheckUpdateOptions {
44
+ currentVersion?: string;
45
+ fetchImpl?: typeof fetch;
46
+ timeoutMs?: number;
47
+ signal?: AbortSignal;
48
+ env?: NodeJS.ProcessEnv;
49
+ }
50
+
51
+ export interface SelfUpdateOptions extends CheckUpdateOptions {
52
+ force?: boolean;
53
+ stateFile?: string;
54
+ packageRoot?: string;
55
+ spawnSyncImpl?: (command: string, args: readonly string[], options: Record<string, unknown>) => SpawnSyncReturns<string | Buffer>;
56
+ verbose?: boolean;
57
+ version?: string;
58
+ }
59
+
60
+ export interface CheckResult {
61
+ current: string;
62
+ latest: string;
63
+ available: boolean;
64
+ }
65
+
66
+ export interface UpdateResult extends InstallationInfo {
67
+ current?: string | undefined;
68
+ latest?: string | undefined;
69
+ available?: boolean | undefined;
70
+ updated: boolean;
71
+ reason?: 'disabled' | 'source-checkout' | 'recently-checked' | 'current' | 'failed' | undefined;
72
+ error?: string | undefined;
73
+ }
74
+
75
+ export interface DiagnosisResult extends InstallationInfo {
76
+ current?: string | undefined;
77
+ latest?: string | null | undefined;
78
+ available?: boolean | undefined;
79
+ autoUpdates: boolean;
80
+ error?: string | undefined;
81
+ }
82
+
83
+ function updateStateFile(options: { stateFile?: string; env?: NodeJS.ProcessEnv } = {}): string {
84
+ if (options.stateFile) return path.resolve(options.stateFile);
85
+ const env = options.env || process.env;
86
+ const root = env.CAUSYNE_HOME && String(env.CAUSYNE_HOME).trim()
87
+ ? path.resolve(String(env.CAUSYNE_HOME).trim())
88
+ : causyneHome();
89
+ return path.join(root, 'update-state.json');
90
+ }
91
+
92
+ export function versionParts(version: string | undefined): VersionParts | null {
93
+ const match = String(version || '').trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);
94
+ if (!match) return null;
95
+ const num1 = Number(match[1]);
96
+ const num2 = Number(match[2]);
97
+ const num3 = Number(match[3]);
98
+ return { numbers: [num1, num2, num3], prerelease: match[4] || '' };
99
+ }
100
+
101
+ export function compareVersions(left: string | undefined, right: string | undefined): number {
102
+ const a = versionParts(left);
103
+ const b = versionParts(right);
104
+ if (!a || !b) return 0;
105
+ for (let index = 0; index < 3; index++) {
106
+ const aNum = a.numbers[index] ?? 0;
107
+ const bNum = b.numbers[index] ?? 0;
108
+ if (aNum !== bNum) return aNum > bNum ? 1 : -1;
109
+ }
110
+ if (a.prerelease === b.prerelease) return 0;
111
+ if (!a.prerelease) return 1;
112
+ if (!b.prerelease) return -1;
113
+ const aParts = a.prerelease.split('.');
114
+ const bParts = b.prerelease.split('.');
115
+ const length = Math.max(aParts.length, bParts.length);
116
+ for (let index = 0; index < length; index++) {
117
+ const aPart = aParts[index];
118
+ const bPart = bParts[index];
119
+ if (aPart === undefined) return -1;
120
+ if (bPart === undefined) return 1;
121
+ if (aPart === bPart) continue;
122
+ const aNumeric = /^\d+$/.test(aPart);
123
+ const bNumeric = /^\d+$/.test(bPart);
124
+ if (aNumeric && bNumeric) return Number(aPart) > Number(bPart) ? 1 : -1;
125
+ if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
126
+ return aPart.localeCompare(bPart);
127
+ }
128
+ return 0;
129
+ }
130
+
131
+ function managedPrefix(packageRoot: string = PACKAGE_ROOT, env: NodeJS.ProcessEnv = process.env): string | null {
132
+ if (env.CAUSYNE_INSTALL_ROOT) return path.resolve(env.CAUSYNE_INSTALL_ROOT);
133
+
134
+ const markers = [
135
+ path.join('lib', 'node_modules', '@causyne', 'agent'),
136
+ path.join('node_modules', '@causyne', 'agent')
137
+ ];
138
+ for (const marker of markers) {
139
+ const index = packageRoot.lastIndexOf(marker);
140
+ if (index >= 0 && index + marker.length === packageRoot.length) {
141
+ return packageRoot.slice(0, index).replace(/[\\/]$/, '');
142
+ }
143
+ }
144
+ return null;
145
+ }
146
+
147
+ export function resolveNpmExecutable(env: NodeJS.ProcessEnv = process.env): string {
148
+ if (env.CAUSYNE_NPM_COMMAND && String(env.CAUSYNE_NPM_COMMAND).trim()) {
149
+ return String(env.CAUSYNE_NPM_COMMAND).trim();
150
+ }
151
+
152
+ const isWin = process.platform === 'win32';
153
+ const npmName = isWin ? 'npm.cmd' : 'npm';
154
+
155
+ // 1. Sibling of running node binary (most reliable across all Node version managers: nvm, fnm, volta, mise)
156
+ if (process.execPath) {
157
+ const sibling = path.join(path.dirname(process.execPath), npmName);
158
+ if (fs.existsSync(sibling)) {
159
+ return sibling;
160
+ }
161
+ }
162
+
163
+ // 2. Private Causyne runtime if provisioned
164
+ const privateNpm = path.join(causyneHome(), 'runtime', 'node', isWin ? '' : 'bin', npmName);
165
+ if (fs.existsSync(privateNpm)) {
166
+ return privateNpm;
167
+ }
168
+
169
+ // 3. Default fallback to system PATH
170
+ return npmName;
171
+ }
172
+
173
+ export function installationInfo(options: { env?: NodeJS.ProcessEnv; packageRoot?: string } = {}): InstallationInfo {
174
+ const env = options.env || process.env;
175
+ const packageRoot = options.packageRoot || PACKAGE_ROOT;
176
+ const prefix = managedPrefix(packageRoot, env);
177
+ const npmCommand = resolveNpmExecutable(env);
178
+ return {
179
+ managed: Boolean(prefix),
180
+ type: env.CAUSYNE_INSTALL_ROOT ? 'causyne.com installer' : (prefix ? 'global npm' : 'source checkout'),
181
+ prefix,
182
+ packageRoot,
183
+ npmCommand
184
+ };
185
+ }
186
+
187
+ function readState(options: { stateFile?: string; env?: NodeJS.ProcessEnv } = {}): UpdateState {
188
+ try {
189
+ return JSON.parse(fs.readFileSync(updateStateFile(options), 'utf8')) as UpdateState;
190
+ } catch {
191
+ return {};
192
+ }
193
+ }
194
+
195
+ function writeState(state: UpdateState, options: { stateFile?: string; env?: NodeJS.ProcessEnv } = {}): void {
196
+ try {
197
+ const stateFile = updateStateFile(options);
198
+ fs.mkdirSync(path.dirname(stateFile), { recursive: true, mode: 0o700 });
199
+ fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), { mode: 0o600 });
200
+ } catch {
201
+ // Update state is an optimisation. Failure must never stop the CLI.
202
+ }
203
+ }
204
+
205
+ export async function latestPackageVersion(options: CheckUpdateOptions = {}): Promise<string> {
206
+ const fetchImpl = options.fetchImpl || globalThis.fetch;
207
+ if (typeof fetchImpl !== 'function') throw new Error('This Node.js runtime has no fetch implementation.');
208
+ const timeoutMs = options.timeoutMs || 3500;
209
+ const signal = options.signal || AbortSignal.timeout(timeoutMs);
210
+ const response = await fetchImpl(REGISTRY_LATEST, {
211
+ headers: { accept: 'application/json', 'user-agent': `causyne/${getPackageVersion()}` },
212
+ signal
213
+ });
214
+ if (!response.ok) throw new Error(`npm registry returned HTTP ${response.status}`);
215
+ const metadata = (await response.json()) as { name?: string; version?: string };
216
+ if (metadata.name !== PACKAGE_NAME || !versionParts(metadata.version)) {
217
+ throw new Error('npm registry returned invalid package metadata');
218
+ }
219
+ return metadata.version as string;
220
+ }
221
+
222
+ function installLatest(info: InstallationInfo, options: SelfUpdateOptions = {}): void {
223
+ if (!info.prefix) {
224
+ throw new Error('Cannot install package: prefix is not defined for this installation.');
225
+ }
226
+ const runner = options.spawnSyncImpl || spawnSync;
227
+ const targetVersion = options.version;
228
+ if (!targetVersion) {
229
+ throw new Error('Target version must be specified for installation.');
230
+ }
231
+
232
+ const args = [
233
+ 'install', '--global', '--prefix', info.prefix,
234
+ `${PACKAGE_NAME}@${targetVersion}`, '--ignore-scripts', '--no-audit', '--no-fund'
235
+ ];
236
+
237
+ // Prepend the directory containing node and npm to PATH so child npm executes smoothly
238
+ const env = { ...(options.env || process.env) };
239
+ const extraPaths = [path.dirname(process.execPath)];
240
+ if (info.npmCommand.includes('/') || info.npmCommand.includes('\\')) {
241
+ extraPaths.push(path.dirname(info.npmCommand));
242
+ }
243
+ const delimiter = process.platform === 'win32' ? ';' : ':';
244
+ const currentPath = env.PATH || env.Path || '';
245
+ env.PATH = [...extraPaths, currentPath].filter(Boolean).join(delimiter);
246
+
247
+ const result = runner(info.npmCommand, args, {
248
+ shell: false,
249
+ stdio: options.verbose ? 'inherit' : 'pipe',
250
+ encoding: 'utf8',
251
+ env
252
+ });
253
+
254
+ if (result.error) throw result.error;
255
+ if (result.status !== 0) {
256
+ const detail = String(result.stderr || result.stdout || '').trim();
257
+ throw new Error(detail || `npm exited with status ${result.status}`);
258
+ }
259
+ }
260
+
261
+ export async function checkForUpdate(options: CheckUpdateOptions = {}): Promise<CheckResult> {
262
+ const current = options.currentVersion || getPackageVersion();
263
+ const latest = await latestPackageVersion(options);
264
+ return { current, latest, available: compareVersions(latest, current) > 0 };
265
+ }
266
+
267
+ export async function runSelfUpdate(verbose: boolean = false, options: SelfUpdateOptions = {}): Promise<UpdateResult> {
268
+ const info = installationInfo(options);
269
+ if (!info.managed) {
270
+ if (verbose) UI.printInfo('This is a source checkout. Update it with Git; Causyne will not rewrite developer source.');
271
+ return { updated: false, reason: 'source-checkout', ...info };
272
+ }
273
+
274
+ try {
275
+ const status = await checkForUpdate(options);
276
+ if (!status.available) {
277
+ writeState({ checkedAt: Date.now(), latest: status.latest }, options);
278
+ if (verbose) UI.printSuccess(`Causyne ${status.current} is up to date.`);
279
+ return { updated: false, reason: 'current', ...status, ...info };
280
+ }
281
+
282
+ if (verbose) UI.printInfo(`Updating Causyne ${status.current} → ${status.latest}...`);
283
+ installLatest(info, { ...options, version: status.latest, verbose });
284
+ writeState({ checkedAt: Date.now(), latest: status.latest, installedAt: Date.now() }, options);
285
+ if (verbose) UI.printSuccess(`Updated to Causyne ${status.latest}.`);
286
+ return { updated: true, ...status, ...info };
287
+ } catch (error) {
288
+ const message = error instanceof Error ? error.message : String(error);
289
+ writeState({ checkedAt: Date.now(), error: message }, options);
290
+ if (verbose) UI.printError(`Update failed: ${message}`);
291
+ return { updated: false, reason: 'failed', error: message, ...info };
292
+ }
293
+ }
294
+
295
+ /** Check on launch, defaulting to at most once per hour with fast retry on error. */
296
+ export async function startUpdateChecker(options: SelfUpdateOptions = {}): Promise<UpdateResult> {
297
+ const env = options.env || process.env;
298
+ if (env.CAUSYNE_DISABLE_AUTOUPDATE === '1' || env.CAUSYNE_DISABLE_AUTOUPDATE === 'true') {
299
+ return {
300
+ updated: false,
301
+ reason: 'disabled',
302
+ managed: false,
303
+ type: 'source checkout',
304
+ prefix: null,
305
+ packageRoot: PACKAGE_ROOT,
306
+ npmCommand: resolveNpmExecutable(env)
307
+ };
308
+ }
309
+
310
+ const info = installationInfo(options);
311
+ if (!info.managed) return { updated: false, reason: 'source-checkout', ...info };
312
+
313
+ const customInterval = Number(env.CAUSYNE_UPDATE_INTERVAL_MS);
314
+ const checkInterval = Number.isFinite(customInterval) && customInterval > 0
315
+ ? customInterval
316
+ : DEFAULT_CHECK_INTERVAL_MS;
317
+
318
+ const state = readState(options);
319
+ if (!options.force && Number.isFinite(state.checkedAt)) {
320
+ const elapsed = Date.now() - (state.checkedAt as number);
321
+ const intervalToUse = state.error ? ERROR_RETRY_INTERVAL_MS : checkInterval;
322
+ if (elapsed < intervalToUse) {
323
+ return { updated: false, reason: 'recently-checked', latest: state.latest, ...info };
324
+ }
325
+ }
326
+
327
+ return runSelfUpdate(false, options);
328
+ }
329
+
330
+ export async function diagnoseInstallation(options: CheckUpdateOptions = {}): Promise<DiagnosisResult> {
331
+ const info = installationInfo(options);
332
+ let update: CheckResult | { current: string; latest: null; available: false; error: string };
333
+ try {
334
+ update = await checkForUpdate(options);
335
+ } catch (error) {
336
+ const message = error instanceof Error ? error.message : String(error);
337
+ update = { current: getPackageVersion(), latest: null, available: false, error: message };
338
+ }
339
+ return {
340
+ ...info,
341
+ ...update,
342
+ autoUpdates: !['1', 'true'].includes(String((options.env || process.env).CAUSYNE_DISABLE_AUTOUPDATE || '').toLowerCase())
343
+ };
344
+ }
345
+
346
+ export function formatDoctorReport(status: DiagnosisResult, runtime: typeof process = process): string {
347
+ const rows = [
348
+ `Version : ${status.current || 'unknown'}`,
349
+ `Latest : ${status.latest || `unavailable (${status.error || 'unknown error'})`}`,
350
+ `Installation : ${status.type}`,
351
+ `Package root : ${status.packageRoot}`,
352
+ `NPM command : ${status.npmCommand}`,
353
+ `Node.js : ${runtime.version}`,
354
+ `Platform : ${runtime.platform} ${runtime.arch}`,
355
+ `Auto updates : ${status.autoUpdates ? 'enabled' : 'disabled'}`,
356
+ `Workspace : ${runtime.cwd()}`
357
+ ];
358
+ if (status.available) rows.push('Update : available — run `causyne update`');
359
+ return rows.join('\n');
360
+ }
@@ -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) {