@causyne/agent 1.20.17 → 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.
@@ -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);
@@ -357,17 +357,60 @@ function nativeInspectionTarget(name, parameters) {
357
357
  }
358
358
  return null;
359
359
  }
360
- function isNativeMutation(name, parameters) {
360
+ export function isNativeMutation(name, parameters = {}) {
361
+ if (!name || typeof name !== 'string')
362
+ return false;
361
363
  const action = name.toLowerCase().replace(/[_\s-]/g, '');
362
- if (/^(writefile|editfile|deletefile|applypatch|createfile|replaceinfile)$/.test(action))
364
+ if (/^(writefile|writetofile|editfile|replacefilecontent|multireplacefilecontent|deletefile|applypatch|createfile|replaceinfile|fswrite|fsedit|generatemedia|generateimage)$/.test(action)) {
363
365
  return true;
366
+ }
364
367
  if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(action))
365
368
  return false;
366
369
  const command = cleanCommandString(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '');
367
370
  if (!command)
368
371
  return false;
369
372
  return /\b(?:save_as_mainfile|save_mainfile|write_text|write_bytes|tee)\b/.test(command)
370
- || /(?:^|[;&|]\s*)(?:cp|mv|rm|install|patch)\s/.test(command);
373
+ || /(?:^|[;&|]\s*)(?:cp|mv|rm|install|patch|touch|mkdir|chmod|sed)\s/.test(command)
374
+ || /(?:>|>>)/.test(command)
375
+ || /\b(?:npm|yarn|pnpm|cargo|gradle|gradlew|mvn|dotnet|pip|pip3|pytest|vitest|jest|tsc|make|docker|git\s+(?:add|commit|checkout|merge|rebase|stash|pull|push))\b/i.test(command);
376
+ }
377
+ export function nativeToolSignature(name, parameters = {}) {
378
+ const normName = name.toLowerCase().replace(/[_\s-]/g, '');
379
+ const sortedKeys = Object.keys(parameters).sort();
380
+ const sortedObj = {};
381
+ for (const k of sortedKeys) {
382
+ const val = parameters[k];
383
+ if (val !== undefined && typeof val !== 'function') {
384
+ sortedObj[k] = val;
385
+ }
386
+ }
387
+ return `${normName}:${JSON.stringify(sortedObj)}`;
388
+ }
389
+ export function detectNativeCycle(signatures) {
390
+ for (let period = 2; period <= 4; period++) {
391
+ if (signatures.length < period * 3)
392
+ continue;
393
+ let laps = 1;
394
+ while (true) {
395
+ const base = signatures.length - period * (laps + 1);
396
+ if (base < 0)
397
+ break;
398
+ let lapEqual = true;
399
+ for (let i = 0; i < period; i++) {
400
+ if (signatures[base + i] !== signatures[signatures.length - period + i]) {
401
+ lapEqual = false;
402
+ break;
403
+ }
404
+ }
405
+ if (!lapEqual)
406
+ break;
407
+ laps++;
408
+ }
409
+ if (laps >= 3) {
410
+ return { period, laps };
411
+ }
412
+ }
413
+ return null;
371
414
  }
372
415
  export function mapNativeToolToCausyne(name, rawParams, index) {
373
416
  if (!name || typeof name !== 'string')
@@ -923,9 +966,16 @@ export class AntigravityProvider extends LLMProvider {
923
966
  }
924
967
  };
925
968
  const configuredActions = Number(options.maxNativeActions);
926
- const maxNativeActions = Number.isSafeInteger(configuredActions) && configuredActions >= 0
969
+ const isAutonomous = options.hardBudget === false || (!desktopTask && options.hardBudget !== true);
970
+ let maxNativeActions = Number.isSafeInteger(configuredActions) && configuredActions >= 0
927
971
  ? configuredActions : desktopTask ? 12 : 35;
928
972
  let nativeActionStarts = 0;
973
+ let lastMutationActionIndex = 0;
974
+ let progressiveActionsCount = 0;
975
+ let consecutiveIdenticalCount = 0;
976
+ let consecutiveInspections = 0;
977
+ let lastToolSignature = '';
978
+ const recentSignatures = [];
929
979
  const seenNativeActionSteps = new Set();
930
980
  const mediaInspectionCounts = new Map();
931
981
  const pendingMediaMutations = new Set();
@@ -1098,13 +1148,6 @@ export class AntigravityProvider extends LLMProvider {
1098
1148
  && (!Number.isFinite(stepIndex) || !seenNativeActionSteps.has(stepIndex));
1099
1149
  if (newNativeAction && Number.isFinite(stepIndex))
1100
1150
  seenNativeActionSteps.add(stepIndex);
1101
- if (newNativeAction && ++nativeActionStarts > maxNativeActions) {
1102
- const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`);
1103
- error.code = 'AGY_NATIVE_ACTION_BUDGET';
1104
- safeReject(error);
1105
- terminateChild();
1106
- return;
1107
- }
1108
1151
  const toolInfo = stepUpdate?.tool_info || {};
1109
1152
  const name = stepUpdate?.tool_name || toolInfo?.name;
1110
1153
  const status = state === 'DONE' || state === 'ERROR'
@@ -1114,6 +1157,72 @@ export class AntigravityProvider extends LLMProvider {
1114
1157
  (stepUpdate && typeof stepUpdate === 'object' && stepUpdate.parameters) ||
1115
1158
  (toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
1116
1159
  {};
1160
+ if (name && newNativeAction) {
1161
+ const mutating = isNativeMutation(name, rawParams);
1162
+ if (mutating) {
1163
+ lastMutationActionIndex = nativeActionStarts + 1;
1164
+ progressiveActionsCount++;
1165
+ consecutiveIdenticalCount = 0;
1166
+ consecutiveInspections = 0;
1167
+ lastToolSignature = '';
1168
+ }
1169
+ else if (!desktopTask && options.taskArchetype !== 'media_3d_generation') {
1170
+ consecutiveInspections++;
1171
+ const sig = nativeToolSignature(name, rawParams);
1172
+ if (sig === lastToolSignature) {
1173
+ consecutiveIdenticalCount++;
1174
+ }
1175
+ else {
1176
+ consecutiveIdenticalCount = 1;
1177
+ lastToolSignature = sig;
1178
+ }
1179
+ recentSignatures.push(sig);
1180
+ if (recentSignatures.length > 24)
1181
+ recentSignatures.shift();
1182
+ // 1. Aimless identical streak detection: 4 identical consecutive non-mutating calls
1183
+ if (consecutiveIdenticalCount >= 4) {
1184
+ const error = Object.assign(new Error(`Antigravity repeated identical call to '${name}' ${consecutiveIdenticalCount} times without progress. Halting circular loop.`), { code: 'AGY_EXPLORATION_LOOP', toolName: name, count: consecutiveIdenticalCount });
1185
+ safeReject(error);
1186
+ terminateChild();
1187
+ return;
1188
+ }
1189
+ // 2. Aimless circular cycle detection: period 2-4 repeating 3 laps without mutation
1190
+ const cycle = detectNativeCycle(recentSignatures);
1191
+ if (cycle && (nativeActionStarts - lastMutationActionIndex) > (cycle.period * 2)) {
1192
+ const error = Object.assign(new Error(`Antigravity repeated circular cycle of ${cycle.period} tool calls without forward progress. Halting circular loop.`), { code: 'AGY_EXPLORATION_LOOP', period: cycle.period, laps: cycle.laps });
1193
+ safeReject(error);
1194
+ terminateChild();
1195
+ return;
1196
+ }
1197
+ // 3. Stagnant read-only inspection runaway without mutations on an editing task
1198
+ if (consecutiveInspections >= 30 && options.taskArchetype !== 'web_research_only') {
1199
+ const error = Object.assign(new Error(`Antigravity performed ${consecutiveInspections} consecutive read-only inspections without writing or modifying code. Halting exploration loop.`), { code: 'AGY_EXPLORATION_LOOP', inspectionCount: consecutiveInspections });
1200
+ safeReject(error);
1201
+ terminateChild();
1202
+ return;
1203
+ }
1204
+ }
1205
+ }
1206
+ if (newNativeAction && ++nativeActionStarts > maxNativeActions) {
1207
+ // In autonomous mode, if the agent has made genuine progress recently
1208
+ // (e.g. edits/mutations or productive steps within last 25 actions),
1209
+ // dynamically expand the autonomous runway so serious tasks are not interrupted!
1210
+ const hasRecentProgress = (nativeActionStarts - lastMutationActionIndex) <= 25 || progressiveActionsCount > 0;
1211
+ if (isAutonomous && hasRecentProgress && maxNativeActions < 500) {
1212
+ const extension = 50;
1213
+ maxNativeActions += extension;
1214
+ if (process.env.CAUSYNE_DEBUG === '1') {
1215
+ console.log(`[AUTONOMY] Dynamically extended native action runway (+${extension} -> ${maxNativeActions} actions) due to active progress.`);
1216
+ }
1217
+ }
1218
+ else {
1219
+ const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`);
1220
+ error.code = 'AGY_NATIVE_ACTION_BUDGET';
1221
+ safeReject(error);
1222
+ terminateChild();
1223
+ return;
1224
+ }
1225
+ }
1117
1226
  if (options.taskArchetype === 'media_3d_generation' && name) {
1118
1227
  if (newNativeAction) {
1119
1228
  const target = isReadOnlyNativeInspection(name, rawParams)
@@ -364,14 +364,56 @@ function nativeInspectionTarget(name: string, parameters: Record<string, unknown
364
364
  return null;
365
365
  }
366
366
 
367
- function isNativeMutation(name: string, parameters: Record<string, unknown>): boolean {
367
+ export function isNativeMutation(name: string, parameters: Record<string, unknown> = {}): boolean {
368
+ if (!name || typeof name !== 'string') return false;
368
369
  const action = name.toLowerCase().replace(/[_\s-]/g, '');
369
- if (/^(writefile|editfile|deletefile|applypatch|createfile|replaceinfile)$/.test(action)) return true;
370
+ if (/^(writefile|writetofile|editfile|replacefilecontent|multireplacefilecontent|deletefile|applypatch|createfile|replaceinfile|fswrite|fsedit|generatemedia|generateimage)$/.test(action)) {
371
+ return true;
372
+ }
370
373
  if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(action)) return false;
371
374
  const command = cleanCommandString(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '');
372
375
  if (!command) return false;
373
376
  return /\b(?:save_as_mainfile|save_mainfile|write_text|write_bytes|tee)\b/.test(command)
374
- || /(?:^|[;&|]\s*)(?:cp|mv|rm|install|patch)\s/.test(command);
377
+ || /(?:^|[;&|]\s*)(?:cp|mv|rm|install|patch|touch|mkdir|chmod|sed)\s/.test(command)
378
+ || /(?:>|>>)/.test(command)
379
+ || /\b(?:npm|yarn|pnpm|cargo|gradle|gradlew|mvn|dotnet|pip|pip3|pytest|vitest|jest|tsc|make|docker|git\s+(?:add|commit|checkout|merge|rebase|stash|pull|push))\b/i.test(command);
380
+ }
381
+
382
+ export function nativeToolSignature(name: string, parameters: Record<string, unknown> = {}): string {
383
+ const normName = name.toLowerCase().replace(/[_\s-]/g, '');
384
+ const sortedKeys = Object.keys(parameters).sort();
385
+ const sortedObj: Record<string, unknown> = {};
386
+ for (const k of sortedKeys) {
387
+ const val = parameters[k];
388
+ if (val !== undefined && typeof val !== 'function') {
389
+ sortedObj[k] = val;
390
+ }
391
+ }
392
+ return `${normName}:${JSON.stringify(sortedObj)}`;
393
+ }
394
+
395
+ export function detectNativeCycle(signatures: string[]): { period: number; laps: number } | null {
396
+ for (let period = 2; period <= 4; period++) {
397
+ if (signatures.length < period * 3) continue;
398
+ let laps = 1;
399
+ while (true) {
400
+ const base = signatures.length - period * (laps + 1);
401
+ if (base < 0) break;
402
+ let lapEqual = true;
403
+ for (let i = 0; i < period; i++) {
404
+ if (signatures[base + i] !== signatures[signatures.length - period + i]) {
405
+ lapEqual = false;
406
+ break;
407
+ }
408
+ }
409
+ if (!lapEqual) break;
410
+ laps++;
411
+ }
412
+ if (laps >= 3) {
413
+ return { period, laps };
414
+ }
415
+ }
416
+ return null;
375
417
  }
376
418
 
377
419
  export function mapNativeToolToCausyne(
@@ -966,9 +1008,16 @@ export class AntigravityProvider extends LLMProvider {
966
1008
  }
967
1009
  };
968
1010
  const configuredActions = Number(options.maxNativeActions);
969
- const maxNativeActions = Number.isSafeInteger(configuredActions) && configuredActions >= 0
1011
+ const isAutonomous = (options as any).hardBudget === false || (!desktopTask && (options as any).hardBudget !== true);
1012
+ let maxNativeActions = Number.isSafeInteger(configuredActions) && configuredActions >= 0
970
1013
  ? configuredActions : desktopTask ? 12 : 35;
971
1014
  let nativeActionStarts = 0;
1015
+ let lastMutationActionIndex = 0;
1016
+ let progressiveActionsCount = 0;
1017
+ let consecutiveIdenticalCount = 0;
1018
+ let consecutiveInspections = 0;
1019
+ let lastToolSignature = '';
1020
+ const recentSignatures: string[] = [];
972
1021
  const seenNativeActionSteps = new Set<number>();
973
1022
  const mediaInspectionCounts = new Map<string, number>();
974
1023
  const pendingMediaMutations = new Set<number>();
@@ -1142,13 +1191,7 @@ export class AntigravityProvider extends LLMProvider {
1142
1191
  const newNativeAction = (state === 'ACTIVE' || (state === 'DONE' && Number.isFinite(stepIndex)))
1143
1192
  && (!Number.isFinite(stepIndex) || !seenNativeActionSteps.has(stepIndex));
1144
1193
  if (newNativeAction && Number.isFinite(stepIndex)) seenNativeActionSteps.add(stepIndex);
1145
- if (newNativeAction && ++nativeActionStarts > maxNativeActions) {
1146
- const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`) as Error & { code: string };
1147
- error.code = 'AGY_NATIVE_ACTION_BUDGET';
1148
- safeReject(error);
1149
- terminateChild();
1150
- return;
1151
- }
1194
+
1152
1195
  const toolInfo = stepUpdate?.tool_info || {};
1153
1196
  const name = stepUpdate?.tool_name || toolInfo?.name;
1154
1197
  const status = state === 'DONE' || state === 'ERROR'
@@ -1159,6 +1202,82 @@ export class AntigravityProvider extends LLMProvider {
1159
1202
  (toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
1160
1203
  {};
1161
1204
 
1205
+ if (name && newNativeAction) {
1206
+ const mutating = isNativeMutation(name, rawParams);
1207
+ if (mutating) {
1208
+ lastMutationActionIndex = nativeActionStarts + 1;
1209
+ progressiveActionsCount++;
1210
+ consecutiveIdenticalCount = 0;
1211
+ consecutiveInspections = 0;
1212
+ lastToolSignature = '';
1213
+ } else if (!desktopTask && (options as any).taskArchetype !== 'media_3d_generation') {
1214
+ consecutiveInspections++;
1215
+ const sig = nativeToolSignature(name, rawParams);
1216
+ if (sig === lastToolSignature) {
1217
+ consecutiveIdenticalCount++;
1218
+ } else {
1219
+ consecutiveIdenticalCount = 1;
1220
+ lastToolSignature = sig;
1221
+ }
1222
+ recentSignatures.push(sig);
1223
+ if (recentSignatures.length > 24) recentSignatures.shift();
1224
+
1225
+ // 1. Aimless identical streak detection: 4 identical consecutive non-mutating calls
1226
+ if (consecutiveIdenticalCount >= 4) {
1227
+ const error = Object.assign(
1228
+ new Error(`Antigravity repeated identical call to '${name}' ${consecutiveIdenticalCount} times without progress. Halting circular loop.`),
1229
+ { code: 'AGY_EXPLORATION_LOOP', toolName: name, count: consecutiveIdenticalCount }
1230
+ );
1231
+ safeReject(error);
1232
+ terminateChild();
1233
+ return;
1234
+ }
1235
+
1236
+ // 2. Aimless circular cycle detection: period 2-4 repeating 3 laps without mutation
1237
+ const cycle = detectNativeCycle(recentSignatures);
1238
+ if (cycle && (nativeActionStarts - lastMutationActionIndex) > (cycle.period * 2)) {
1239
+ const error = Object.assign(
1240
+ new Error(`Antigravity repeated circular cycle of ${cycle.period} tool calls without forward progress. Halting circular loop.`),
1241
+ { code: 'AGY_EXPLORATION_LOOP', period: cycle.period, laps: cycle.laps }
1242
+ );
1243
+ safeReject(error);
1244
+ terminateChild();
1245
+ return;
1246
+ }
1247
+
1248
+ // 3. Stagnant read-only inspection runaway without mutations on an editing task
1249
+ if (consecutiveInspections >= 30 && (options as any).taskArchetype !== 'web_research_only') {
1250
+ const error = Object.assign(
1251
+ new Error(`Antigravity performed ${consecutiveInspections} consecutive read-only inspections without writing or modifying code. Halting exploration loop.`),
1252
+ { code: 'AGY_EXPLORATION_LOOP', inspectionCount: consecutiveInspections }
1253
+ );
1254
+ safeReject(error);
1255
+ terminateChild();
1256
+ return;
1257
+ }
1258
+ }
1259
+ }
1260
+
1261
+ if (newNativeAction && ++nativeActionStarts > maxNativeActions) {
1262
+ // In autonomous mode, if the agent has made genuine progress recently
1263
+ // (e.g. edits/mutations or productive steps within last 25 actions),
1264
+ // dynamically expand the autonomous runway so serious tasks are not interrupted!
1265
+ const hasRecentProgress = (nativeActionStarts - lastMutationActionIndex) <= 25 || progressiveActionsCount > 0;
1266
+ if (isAutonomous && hasRecentProgress && maxNativeActions < 500) {
1267
+ const extension = 50;
1268
+ maxNativeActions += extension;
1269
+ if (process.env.CAUSYNE_DEBUG === '1') {
1270
+ console.log(`[AUTONOMY] Dynamically extended native action runway (+${extension} -> ${maxNativeActions} actions) due to active progress.`);
1271
+ }
1272
+ } else {
1273
+ const error = new Error(`Antigravity reached the ${maxNativeActions} native-action turn checkpoint. Work remains unfinished; continue from the saved session.`) as Error & { code: string };
1274
+ error.code = 'AGY_NATIVE_ACTION_BUDGET';
1275
+ safeReject(error);
1276
+ terminateChild();
1277
+ return;
1278
+ }
1279
+ }
1280
+
1162
1281
  if ((options as any).taskArchetype === 'media_3d_generation' && name) {
1163
1282
  if (newNativeAction) {
1164
1283
  const target = isReadOnlyNativeInspection(name, rawParams)
@@ -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);