@causyne/agent 1.20.121 → 1.20.122

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.
Files changed (256) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +6 -2
  14. package/src/agent/errorClassifier.ts +6 -2
  15. package/src/agentLoop.js +11 -5
  16. package/src/agentLoop.ts +11 -5
  17. package/src/approvalGrants.js +19 -7
  18. package/src/approvalGrants.ts +20 -7
  19. package/src/approvalPolicy.js +48 -15
  20. package/src/approvalPolicy.ts +46 -15
  21. package/src/autoUpdate.js +5 -2
  22. package/src/autoUpdate.ts +5 -2
  23. package/src/browser/causyneBrowser.js +3 -2
  24. package/src/browser/causyneBrowser.ts +3 -2
  25. package/src/browser/searchProviders.js +1 -1
  26. package/src/browser/searchProviders.ts +1 -1
  27. package/src/config.js +287 -250
  28. package/src/config.ts +342 -0
  29. package/src/configVault.js +84 -17
  30. package/src/configVault.ts +77 -17
  31. package/src/continuum/compactor.js +2 -1
  32. package/src/continuum/compactor.ts +2 -1
  33. package/src/continuum/sanitizer.js +10 -3
  34. package/src/continuum/sanitizer.ts +9 -3
  35. package/src/continuum/ui/continuumPickerView.js +3 -2
  36. package/src/continuum/ui/continuumPickerView.ts +3 -2
  37. package/src/cortex/vectorDb.js +26 -15
  38. package/src/cortex/vectorDb.ts +26 -16
  39. package/src/creative/liveBridge.js +7 -5
  40. package/src/creative/liveBridge.ts +7 -5
  41. package/src/creative/studioScripts.js +16 -5
  42. package/src/creative/studioScripts.ts +14 -5
  43. package/src/decisionPolicy.js +16 -4
  44. package/src/decisionPolicy.ts +14 -4
  45. package/src/documentEngine/antiSlopAuditor.js +10 -5
  46. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  47. package/src/documentEngine/documentForge.js +47 -15
  48. package/src/documentEngine/documentForge.ts +43 -14
  49. package/src/engines/design.js +2 -1
  50. package/src/engines/design.ts +2 -1
  51. package/src/engines/film.js +4 -4
  52. package/src/engines/film.ts +2 -2
  53. package/src/engines/light.js +2 -1
  54. package/src/engines/light.ts +2 -1
  55. package/src/engines/registry.js +1 -1
  56. package/src/engines/registry.ts +1 -1
  57. package/src/engines/reverseHarness.js +4 -3
  58. package/src/engines/reverseHarness.ts +4 -3
  59. package/src/headlessCli.js +2 -1
  60. package/src/headlessCli.ts +2 -1
  61. package/src/historyPruner.js +3 -2
  62. package/src/historyPruner.ts +3 -2
  63. package/src/hooks.js +3 -0
  64. package/src/hooks.ts +3 -0
  65. package/src/implementationPlan.js +21 -11
  66. package/src/implementationPlan.ts +21 -11
  67. package/src/infra/atomicWriter.js +4 -1
  68. package/src/infra/atomicWriter.ts +4 -1
  69. package/src/launchIntent.js +1 -1
  70. package/src/launchIntent.ts +1 -1
  71. package/src/memory/scopedFacts.js +1 -1
  72. package/src/memory/scopedFacts.ts +1 -1
  73. package/src/memory/symbolFolder.js +1 -1
  74. package/src/memory/symbolFolder.ts +1 -1
  75. package/src/modelRouter.js +1 -1
  76. package/src/modelRouter.ts +1 -1
  77. package/src/observer/evidence.js +10 -4
  78. package/src/observer/evidence.ts +10 -4
  79. package/src/osKeychain.js +62 -8
  80. package/src/osKeychain.ts +50 -8
  81. package/src/perception.js +3 -2
  82. package/src/perception.ts +3 -2
  83. package/src/planCache.js +2 -2
  84. package/src/planCache.ts +2 -2
  85. package/src/pluginsFactory/pluginsFactory.js +19 -11
  86. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  87. package/src/promptMentions.js +2 -2
  88. package/src/promptMentions.ts +2 -2
  89. package/src/providers/acp.js +1 -1
  90. package/src/providers/acp.ts +1 -1
  91. package/src/providers/anthropic.js +327 -401
  92. package/src/providers/anthropic.ts +386 -0
  93. package/src/providers/antigravity.js +10 -4
  94. package/src/providers/antigravity.ts +10 -4
  95. package/src/providers/base.js +221 -319
  96. package/src/providers/base.ts +340 -0
  97. package/src/providers/byokHttp.js +58 -15
  98. package/src/providers/byokHttp.ts +59 -16
  99. package/src/providers/byokStream.js +142 -51
  100. package/src/providers/byokStream.ts +146 -42
  101. package/src/providers/dashscope-byok.js +97 -89
  102. package/src/providers/dashscope-byok.ts +114 -0
  103. package/src/providers/deepseek.js +73 -72
  104. package/src/providers/deepseek.ts +99 -0
  105. package/src/providers/factory.js +35 -28
  106. package/src/providers/factory.ts +40 -0
  107. package/src/providers/gemini.js +227 -278
  108. package/src/providers/gemini.ts +261 -0
  109. package/src/providers/loopGuard.js +9 -5
  110. package/src/providers/loopGuard.ts +10 -5
  111. package/src/providers/moonshot.js +70 -72
  112. package/src/providers/moonshot.ts +93 -0
  113. package/src/providers/muse.js +82 -152
  114. package/src/providers/muse.ts +122 -0
  115. package/src/providers/ollama.js +114 -106
  116. package/src/providers/ollama.ts +135 -0
  117. package/src/providers/openai-compatible.js +113 -96
  118. package/src/providers/openai-compatible.ts +139 -0
  119. package/src/providers/openai.js +22 -15
  120. package/src/providers/openai.ts +30 -0
  121. package/src/providers/openrouter.js +136 -74
  122. package/src/providers/openrouter.ts +133 -72
  123. package/src/providers/pi.js +6 -0
  124. package/src/providers/pi.ts +6 -0
  125. package/src/providers/qwen-byok.js +96 -87
  126. package/src/providers/qwen-byok.ts +113 -0
  127. package/src/providers/toolContracts.js +40 -14
  128. package/src/providers/toolContracts.ts +35 -14
  129. package/src/providers/wireNormalizer.js +78 -11
  130. package/src/providers/wireNormalizer.ts +68 -12
  131. package/src/providers/xai.js +73 -72
  132. package/src/providers/xai.ts +97 -0
  133. package/src/reliability/assetEvidence.js +4 -2
  134. package/src/reliability/assetEvidence.ts +4 -2
  135. package/src/sandbox.js +489 -554
  136. package/src/sandbox.ts +552 -0
  137. package/src/sandboxPolicy.js +95 -16
  138. package/src/sandboxPolicy.ts +97 -16
  139. package/src/sessionJournal.js +8 -3
  140. package/src/sessionJournal.ts +9 -3
  141. package/src/skills/skillResourceSafety.js +19 -8
  142. package/src/skills/skillResourceSafety.ts +16 -7
  143. package/src/skillsManager.js +3 -3
  144. package/src/skillsManager.ts +3 -3
  145. package/src/smartToolsUse.js +28 -4
  146. package/src/smartToolsUse.ts +29 -7
  147. package/src/stallGuard.js +45 -22
  148. package/src/stallGuard.ts +46 -22
  149. package/src/subagentJournal.js +6 -4
  150. package/src/subagentJournal.ts +6 -4
  151. package/src/textDiff.js +6 -1
  152. package/src/textDiff.ts +6 -1
  153. package/src/timeMachine.js +7 -1
  154. package/src/timeMachine.ts +7 -1
  155. package/src/tokenTracker.js +43 -28
  156. package/src/tokenTracker.ts +44 -30
  157. package/src/toolPacks.js +3 -1
  158. package/src/toolPacks.ts +3 -1
  159. package/src/tools/archive.js +245 -35
  160. package/src/tools/archive.ts +244 -35
  161. package/src/tools/computerUse.js +7 -3
  162. package/src/tools/computerUse.ts +7 -3
  163. package/src/tools/creativeApps.js +13 -8
  164. package/src/tools/creativeApps.ts +22 -9
  165. package/src/tools/deferredMcpSearch.js +26 -14
  166. package/src/tools/deferredMcpSearch.ts +26 -14
  167. package/src/tools/desktopOpen.js +69 -10
  168. package/src/tools/desktopOpen.ts +70 -11
  169. package/src/tools/documentForge.js +167 -82
  170. package/src/tools/documentForge.ts +169 -84
  171. package/src/tools/fsEdit.js +101 -30
  172. package/src/tools/fsEdit.ts +105 -32
  173. package/src/tools/fsFind.js +8 -5
  174. package/src/tools/fsFind.ts +7 -4
  175. package/src/tools/fsRead.js +119 -13
  176. package/src/tools/fsRead.ts +124 -13
  177. package/src/tools/fsWrite.js +17 -5
  178. package/src/tools/fsWrite.ts +17 -7
  179. package/src/tools/generateMediaViaApi.js +82 -19
  180. package/src/tools/generateMediaViaApi.ts +80 -19
  181. package/src/tools/memoryRecall.js +62 -11
  182. package/src/tools/memoryRecall.ts +70 -13
  183. package/src/tools/memoryWrite.js +27 -14
  184. package/src/tools/memoryWrite.ts +30 -14
  185. package/src/tools/multiEdit.js +100 -30
  186. package/src/tools/multiEdit.ts +104 -32
  187. package/src/tools/nativeEngine.js +33 -18
  188. package/src/tools/nativeEngine.ts +31 -18
  189. package/src/tools/openSourceToolProvisioner.js +49 -14
  190. package/src/tools/openSourceToolProvisioner.ts +54 -15
  191. package/src/tools/osSandbox.js +54 -14
  192. package/src/tools/osSandbox.ts +48 -14
  193. package/src/tools/payloadSanitizer.js +40 -8
  194. package/src/tools/payloadSanitizer.ts +39 -8
  195. package/src/tools/peerAgent.js +96 -34
  196. package/src/tools/peerAgent.ts +114 -37
  197. package/src/tools/pluginsFactory.js +38 -6
  198. package/src/tools/pluginsFactory.ts +42 -6
  199. package/src/tools/readNativeSkill.js +10 -8
  200. package/src/tools/readNativeSkill.ts +10 -8
  201. package/src/tools/requestDecision.js +10 -3
  202. package/src/tools/requestDecision.ts +10 -3
  203. package/src/tools/resolveAutomator.js +91 -17
  204. package/src/tools/resolveAutomator.ts +102 -17
  205. package/src/tools/reverseEngineering.js +168 -41
  206. package/src/tools/reverseEngineering.ts +161 -41
  207. package/src/tools/sysRun.js +69 -29
  208. package/src/tools/sysRun.ts +66 -24
  209. package/src/tools/toolDispatch.js +24 -1
  210. package/src/tools/toolDispatch.ts +21 -1
  211. package/src/tools/toolOutputStore.js +62 -23
  212. package/src/tools/toolOutputStore.ts +56 -23
  213. package/src/tools/toolScanner.js +13 -10
  214. package/src/tools/toolScanner.ts +13 -10
  215. package/src/tools/toolSelfRepair.js +94 -28
  216. package/src/tools/toolSelfRepair.ts +96 -28
  217. package/src/tools/uiForge.js +71 -6
  218. package/src/tools/uiForge.ts +74 -6
  219. package/src/tools/viewImage.js +62 -17
  220. package/src/tools/viewImage.ts +57 -12
  221. package/src/tools/visionInspector.js +15 -3
  222. package/src/tools/visionInspector.ts +15 -3
  223. package/src/tools/walkerSafety.js +2 -0
  224. package/src/tools/walkerSafety.ts +1 -0
  225. package/src/tools/webFetch.js +105 -10
  226. package/src/tools/webFetch.ts +105 -11
  227. package/src/tui/banner.js +3 -2
  228. package/src/tui/banner.ts +3 -2
  229. package/src/tui/consoleGuard.js +12 -4
  230. package/src/tui/consoleGuard.ts +9 -4
  231. package/src/tui/messageInteraction.js +2 -3
  232. package/src/tui/messageInteraction.ts +2 -3
  233. package/src/tui/modelPicker.js +1 -0
  234. package/src/tui/modelPicker.ts +1 -0
  235. package/src/tui/overlay.js +3 -1
  236. package/src/tui/overlay.ts +3 -1
  237. package/src/tui/sessionPicker.js +3 -2
  238. package/src/tui/sessionPicker.ts +3 -2
  239. package/src/tui/sessionPickerView.js +7 -1
  240. package/src/tui/sessionPickerView.ts +6 -1
  241. package/src/tui/toolOutputNormalizer.js +2 -3
  242. package/src/tui/toolOutputNormalizer.ts +4 -3
  243. package/src/tui/viewport.js +4 -4
  244. package/src/tui/viewport.ts +5 -5
  245. package/src/tui/workspaceIdentity.js +2 -1
  246. package/src/tui/workspaceIdentity.ts +2 -1
  247. package/src/uncertainty.js +8 -3
  248. package/src/uncertainty.ts +8 -3
  249. package/src/utils/paths.js +8 -5
  250. package/src/utils/paths.ts +9 -7
  251. package/src/vfeTracker.js +9 -3
  252. package/src/vfeTracker.ts +9 -3
  253. package/src/config.d.ts +0 -2
  254. package/src/providers/base.d.ts +0 -94
  255. package/src/providers/factory.d.ts +0 -1
  256. package/src/sandbox.d.ts +0 -1
@@ -80,25 +80,28 @@ export interface ReverseEngineeringParams {
80
80
  // NATIVE BINARY PARSERS (Pure Node.js Zero-Dependency Fallback)
81
81
  // ─────────────────────────────────────────────────────────────────────────────
82
82
 
83
- function parseMachO(buffer: Buffer): Partial<BinaryInspectionResult> {
83
+ function parseMachO(buffer: Buffer, depth = 0): Partial<BinaryInspectionResult> {
84
+ if (buffer.length < 8) {
85
+ return { format: 'Mach-O', architecture: 'unknown' };
86
+ }
84
87
  const magic = buffer.readUInt32BE(0);
85
88
  const is64 = magic === 0xfeedfacf || magic === 0xcffaedfe;
86
- const isLe = magic === 0xfeedfacf || magic === 0xfeedface;
89
+ const isLe = magic === 0xcffaedfe || magic === 0xcefaedfe;
87
90
  const isFat = magic === 0xcafebabe || magic === 0xbebafeca;
88
91
 
89
92
  if (isFat) {
90
93
  let architecture = 'Universal FAT (Mach-O)';
91
94
  const nfat_arch = buffer.readUInt32BE(4);
92
- if (buffer.length >= 8 + nfat_arch * 20) {
95
+ if (depth < 2 && nfat_arch > 0 && nfat_arch <= 32 && buffer.length >= 8 + nfat_arch * 20) {
93
96
  for (let i = 0; i < nfat_arch; i++) {
94
97
  const offset = 8 + i * 20;
95
98
  const cputype = buffer.readInt32BE(offset);
96
99
  const sliceOffset = buffer.readUInt32BE(offset + 8);
97
100
  const sliceSize = buffer.readUInt32BE(offset + 12);
98
- if (sliceOffset + 8 <= buffer.length) {
101
+ if (sliceOffset > 0 && sliceOffset + 28 <= buffer.length) {
99
102
  const sliceBuf = buffer.subarray(sliceOffset, Math.min(sliceOffset + sliceSize, buffer.length));
100
- if (sliceBuf.length >= 8) {
101
- const inner = parseMachO(sliceBuf);
103
+ if (sliceBuf.length >= 28) {
104
+ const inner = parseMachO(sliceBuf, depth + 1);
102
105
  return {
103
106
  format: 'Mach-O',
104
107
  architecture: `Universal FAT (slice: ${inner.architecture || 'unknown'}, cputype: ${cputype})`,
@@ -121,6 +124,10 @@ function parseMachO(buffer: Buffer): Partial<BinaryInspectionResult> {
121
124
  };
122
125
  }
123
126
 
127
+ if (buffer.length < 28) {
128
+ return { format: 'Mach-O', architecture: 'unknown', is64Bit: is64, byteOrder: isLe ? 'little-endian' : 'big-endian' };
129
+ }
130
+
124
131
  const cputype = isLe ? buffer.readInt32LE(4) : buffer.readInt32BE(4);
125
132
  let architecture = 'unknown';
126
133
  if (cputype === 0x01000007) architecture = 'x86_64';
@@ -153,6 +160,9 @@ function parseMachO(buffer: Buffer): Partial<BinaryInspectionResult> {
153
160
  }
154
161
 
155
162
  function parseElf(buffer: Buffer): Partial<BinaryInspectionResult> {
163
+ if (buffer.length < 20) {
164
+ return { format: 'ELF', architecture: 'unknown' };
165
+ }
156
166
  const is64 = buffer[4] === 2;
157
167
  const isLe = buffer[5] === 1;
158
168
 
@@ -256,26 +266,29 @@ function parseAsarHeader(buffer: Buffer): { headerSize: number; header: AsarDire
256
266
  const magic = buffer.readUInt32LE(0);
257
267
  if (magic !== 4) return null;
258
268
 
269
+ const pickleSize = buffer.readUInt32LE(4);
259
270
  const headerSize = buffer.readUInt32LE(12);
260
- if (16 + headerSize > buffer.length) return null;
271
+ const dataOffset = 8 + pickleSize;
272
+ if (16 + headerSize > buffer.length || dataOffset < 16 + headerSize || dataOffset > buffer.length) return null;
261
273
 
262
274
  try {
263
275
  const headerJson = buffer.toString('utf8', 16, 16 + headerSize);
264
276
  const header = JSON.parse(headerJson) as AsarDirectory;
265
- return { headerSize: 16 + headerSize, header };
277
+ return { headerSize: dataOffset, header };
266
278
  } catch {
267
279
  return null;
268
280
  }
269
281
  }
270
282
 
271
- function listAsarFiles(dir: AsarDirectory, prefix = ''): { path: string; size: number }[] {
283
+ function listAsarFiles(dir: AsarDirectory, prefix = '', depth = 0): { path: string; size: number }[] {
272
284
  const list: { path: string; size: number }[] = [];
273
- if (!dir || !dir.files) return list;
285
+ if (depth > 64 || !dir || typeof dir !== 'object' || !dir.files || typeof dir.files !== 'object') return list;
274
286
 
275
287
  for (const [name, entry] of Object.entries(dir.files)) {
288
+ if (!entry || typeof entry !== 'object') continue;
276
289
  const fullPath = prefix ? `${prefix}/${name}` : name;
277
290
  if ('files' in entry && entry.files) {
278
- list.push(...listAsarFiles(entry, fullPath));
291
+ list.push(...listAsarFiles(entry, fullPath, depth + 1));
279
292
  } else if ('size' in entry && typeof entry.size === 'number') {
280
293
  list.push({ path: fullPath, size: entry.size });
281
294
  }
@@ -519,8 +532,12 @@ async function inspectApkZipAndManifest(apkPath: string): Promise<Partial<Binary
519
532
  return { format: 'APK/ZIP', fileType: 'Android Application Package (APK)' };
520
533
  }
521
534
 
535
+ const MAX_ZIP_SLICE_BYTES = 64 * 1024 * 1024;
522
536
  const cdSize = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 12);
523
537
  const cdOffset = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 16);
538
+ if (cdSize > MAX_ZIP_SLICE_BYTES || cdOffset + cdSize > stat.size) {
539
+ return { format: 'APK/ZIP', fileType: 'Android Application Package (APK)' };
540
+ }
524
541
  const cdBuf = Buffer.alloc(cdSize);
525
542
  await fd.read(cdBuf, 0, cdSize, cdOffset);
526
543
 
@@ -566,14 +583,20 @@ async function inspectApkZipAndManifest(apkPath: string): Promise<Partial<Binary
566
583
  let manifestStrings: string[] = [];
567
584
  if (manifestEntry) {
568
585
  const localHdr = Buffer.alloc(30);
569
- await fd.read(localHdr, 0, 30, manifestEntry.localHeaderOffset);
570
- const fnLen = localHdr.readUInt16LE(26);
571
- const extraLen = localHdr.readUInt16LE(28);
572
- const dataOffset = manifestEntry.localHeaderOffset + 30 + fnLen + extraLen;
573
- const compData = Buffer.alloc(manifestEntry.compSize);
574
- await fd.read(compData, 0, manifestEntry.compSize, dataOffset);
575
- const xmlBuf = manifestEntry.method === 8 ? zlib.inflateRawSync(compData) : compData;
576
- manifestStrings = parseAxmlStrings(xmlBuf);
586
+ const { bytesRead } = await fd.read(localHdr, 0, 30, manifestEntry.localHeaderOffset);
587
+ if (bytesRead === 30 && localHdr.readUInt32LE(0) === 0x04034b50) {
588
+ const fnLen = localHdr.readUInt16LE(26);
589
+ const extraLen = localHdr.readUInt16LE(28);
590
+ const dataOffset = manifestEntry.localHeaderOffset + 30 + fnLen + extraLen;
591
+ if (manifestEntry.compSize <= MAX_ZIP_SLICE_BYTES && dataOffset + manifestEntry.compSize <= stat.size) {
592
+ const compData = Buffer.alloc(manifestEntry.compSize);
593
+ await fd.read(compData, 0, manifestEntry.compSize, dataOffset);
594
+ const xmlBuf = manifestEntry.method === 8
595
+ ? zlib.inflateRawSync(compData, { maxOutputLength: MAX_ZIP_SLICE_BYTES })
596
+ : compData;
597
+ manifestStrings = parseAxmlStrings(xmlBuf);
598
+ }
599
+ }
577
600
  }
578
601
 
579
602
  const permissions = manifestStrings.filter(s => s.includes('permission.') || s.startsWith('android.permission'));
@@ -659,8 +682,12 @@ async function searchClassesInApk(apkPath: string, query: string): Promise<{ mat
659
682
 
660
683
  if (eocdOffset === -1) return { matchedClasses: [], totalInspected: 0 };
661
684
 
685
+ const MAX_ZIP_SLICE_BYTES = 64 * 1024 * 1024;
662
686
  const cdSize = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 12);
663
687
  const cdOffset = endBuf.readUInt32LE(eocdOffset - (stat.size - endSize) + 16);
688
+ if (cdSize > MAX_ZIP_SLICE_BYTES || cdOffset + cdSize > stat.size) {
689
+ return { matchedClasses: [], totalInspected: 0 };
690
+ }
664
691
  const cdBuf = Buffer.alloc(cdSize);
665
692
  await fd.read(cdBuf, 0, cdSize, cdOffset);
666
693
 
@@ -687,13 +714,17 @@ async function searchClassesInApk(apkPath: string, query: string): Promise<{ mat
687
714
  for (const dexEntry of dexEntries.slice(0, 5)) {
688
715
  try {
689
716
  const localHdr = Buffer.alloc(30);
690
- await fd.read(localHdr, 0, 30, dexEntry.localHeaderOffset);
717
+ const { bytesRead } = await fd.read(localHdr, 0, 30, dexEntry.localHeaderOffset);
718
+ if (bytesRead !== 30 || localHdr.readUInt32LE(0) !== 0x04034b50) continue;
691
719
  const fnLen = localHdr.readUInt16LE(26);
692
720
  const extraLen = localHdr.readUInt16LE(28);
693
721
  const dataOffset = dexEntry.localHeaderOffset + 30 + fnLen + extraLen;
722
+ if (dexEntry.compSize > MAX_ZIP_SLICE_BYTES || dataOffset + dexEntry.compSize > stat.size) continue;
694
723
  const compData = Buffer.alloc(dexEntry.compSize);
695
724
  await fd.read(compData, 0, dexEntry.compSize, dataOffset);
696
- const dexBuf = dexEntry.method === 8 ? zlib.inflateRawSync(compData) : compData;
725
+ const dexBuf = dexEntry.method === 8
726
+ ? zlib.inflateRawSync(compData, { maxOutputLength: MAX_ZIP_SLICE_BYTES })
727
+ : compData;
697
728
 
698
729
  if (dexBuf.length >= 112 && dexBuf.toString('utf8', 0, 4) === 'dex\n') {
699
730
  const stringIdsOff = dexBuf.readUInt32LE(60);
@@ -1027,10 +1058,16 @@ export const reverseEngineering = {
1027
1058
  }
1028
1059
 
1029
1060
  const stats = await fsp.stat(resolvedFile);
1030
- const fd = await fsp.open(resolvedFile, 'r');
1061
+ if (!stats.isFile()) {
1062
+ return { success: false, error: `Inspection target is not a regular file: ${resolvedFile}` };
1063
+ }
1031
1064
  const headerBuf = Buffer.alloc(Math.min(8192, stats.size));
1032
- await fd.read(headerBuf, 0, headerBuf.length, 0);
1033
- await fd.close();
1065
+ const fd = await fsp.open(resolvedFile, 'r');
1066
+ try {
1067
+ await fd.read(headerBuf, 0, headerBuf.length, 0);
1068
+ } finally {
1069
+ await fd.close();
1070
+ }
1034
1071
 
1035
1072
  let result: BinaryInspectionResult = {
1036
1073
  filePath: resolvedFile,
@@ -1109,6 +1146,9 @@ export const reverseEngineering = {
1109
1146
  // ── ACTION: DECOMPILE ─────────────────────────────────────────────────
1110
1147
  if (action === 'decompile') {
1111
1148
  try {
1149
+ if (functionName !== undefined && (typeof functionName !== 'string' || !/^[A-Za-z0-9_.$:@<>~+][A-Za-z0-9_.$:@<>~+-]{0,255}$/.test(functionName))) {
1150
+ return { success: false, error: 'Invalid functionName: contains disallowed characters for disassembler/decompiler invocation.' };
1151
+ }
1112
1152
  let disassemblyText = '';
1113
1153
 
1114
1154
  // 1. Try sovereign engine decompilation
@@ -1124,8 +1164,13 @@ export const reverseEngineering = {
1124
1164
  // 2. Fallbacks if engine output is empty
1125
1165
  if (!disassemblyText && engine === 'rizin') {
1126
1166
  try {
1127
- const args = ['-q', '-c', functionName ? `pdf @ ${functionName}` : 'pdr @ main', resolvedFile];
1128
- const rzRes = await execFileAsync('rizin', args, { timeout: 30000 });
1167
+ const rzArgs = ['-q', '-c', functionName ? `pdf @ ${functionName}` : 'pdr @ main', resolvedFile];
1168
+ const rzRes = await execFileAsync('rizin', rzArgs, {
1169
+ timeout: 30000,
1170
+ maxBuffer: 10 * 1024 * 1024,
1171
+ windowsHide: true,
1172
+ ...(context.signal ? { signal: context.signal } : {})
1173
+ });
1129
1174
  disassemblyText = rzRes.stdout;
1130
1175
  } catch (e: unknown) {
1131
1176
  disassemblyText = `[Rizin failed: ${e instanceof Error ? e.message : String(e)}]`;
@@ -1137,7 +1182,12 @@ export const reverseEngineering = {
1137
1182
  const otoolArgs = ['-tvV'];
1138
1183
  if (functionName) otoolArgs.push('-p', functionName);
1139
1184
  otoolArgs.push(resolvedFile);
1140
- const res = await execFileAsync('otool', otoolArgs, { timeout: 30000, maxBuffer: 10 * 1024 * 1024 });
1185
+ const res = await execFileAsync('otool', otoolArgs, {
1186
+ timeout: 30000,
1187
+ maxBuffer: 10 * 1024 * 1024,
1188
+ windowsHide: true,
1189
+ ...(context.signal ? { signal: context.signal } : {})
1190
+ });
1141
1191
  disassemblyText = res.stdout;
1142
1192
  } catch {
1143
1193
  // fallback to objdump
@@ -1149,7 +1199,12 @@ export const reverseEngineering = {
1149
1199
  const objdumpArgs = ['--disassemble'];
1150
1200
  if (functionName) objdumpArgs.push(`--disassemble=${functionName}`);
1151
1201
  objdumpArgs.push(resolvedFile);
1152
- const res = await execFileAsync('objdump', objdumpArgs, { timeout: 30000, maxBuffer: 10 * 1024 * 1024 });
1202
+ const res = await execFileAsync('objdump', objdumpArgs, {
1203
+ timeout: 30000,
1204
+ maxBuffer: 10 * 1024 * 1024,
1205
+ windowsHide: true,
1206
+ ...(context.signal ? { signal: context.signal } : {})
1207
+ });
1153
1208
  disassemblyText = res.stdout;
1154
1209
  } catch {
1155
1210
  disassemblyText = `Decompiler not available on system for ${path.basename(resolvedFile)}. Install Ghidra or Rizin for advanced decompilation.`;
@@ -1195,10 +1250,16 @@ export const reverseEngineering = {
1195
1250
  // Fall back gracefully
1196
1251
  }
1197
1252
 
1198
- const fileBuf = await fsp.readFile(resolvedFile);
1199
- const asar = parseAsarHeader(fileBuf);
1253
+ const unpackStat = await fsp.stat(resolvedFile);
1254
+ const MAX_ASAR_READ_BYTES = 256 * 1024 * 1024;
1255
+ let fileBuf: Buffer | null = null;
1256
+ let asar: { headerSize: number; header: AsarDirectory } | null = null;
1257
+ if (unpackStat.isFile() && unpackStat.size <= MAX_ASAR_READ_BYTES) {
1258
+ fileBuf = await fsp.readFile(resolvedFile);
1259
+ asar = parseAsarHeader(fileBuf);
1260
+ }
1200
1261
 
1201
- if (asar) {
1262
+ if (asar && fileBuf) {
1202
1263
  const files = listAsarFiles(asar.header);
1203
1264
  if (listOnly) {
1204
1265
  return {
@@ -1211,25 +1272,53 @@ export const reverseEngineering = {
1211
1272
  };
1212
1273
  }
1213
1274
 
1214
- await fsp.mkdir(dest, { recursive: true });
1275
+ const destRoot = path.resolve(dest);
1276
+ await fsp.mkdir(destRoot, { recursive: true });
1215
1277
  const baseOffset = asar.headerSize;
1216
1278
  let extractedCount = 0;
1217
1279
 
1218
- const extractEntry = async (entry: AsarDirectory | AsarFileEntry, currPath: string) => {
1219
- if ('files' in entry && entry.files) {
1220
- await fsp.mkdir(currPath, { recursive: true });
1280
+ const extractEntry = async (entry: AsarDirectory | AsarFileEntry, currPath: string, depth = 0) => {
1281
+ if (depth > 64) {
1282
+ throw new Error('Refusing overly deep ASAR archive hierarchy (> 64 levels)');
1283
+ }
1284
+ if (!entry || typeof entry !== 'object') return;
1285
+ const resolvedCurr = path.resolve(currPath);
1286
+ const rel = path.relative(destRoot, resolvedCurr);
1287
+ if (rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) {
1288
+ throw new Error(`Refusing ASAR path traversal outside destination: ${currPath}`);
1289
+ }
1290
+ try {
1291
+ const existing = await fsp.lstat(resolvedCurr);
1292
+ if (existing.isSymbolicLink()) {
1293
+ throw new Error(`Refusing to extract ASAR entry over symbolic link: ${resolvedCurr}`);
1294
+ }
1295
+ } catch (lstatErr: unknown) {
1296
+ if ((lstatErr as NodeJS.ErrnoException)?.code !== 'ENOENT') throw lstatErr;
1297
+ }
1298
+ if ('files' in entry && entry.files && typeof entry.files === 'object') {
1299
+ await fsp.mkdir(resolvedCurr, { recursive: true });
1221
1300
  for (const [name, child] of Object.entries(entry.files)) {
1222
- await extractEntry(child, path.join(currPath, name));
1301
+ if (!name || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) {
1302
+ throw new Error(`Refusing unsafe ASAR entry name: ${name}`);
1303
+ }
1304
+ await extractEntry(child, path.join(resolvedCurr, name), depth + 1);
1223
1305
  }
1224
1306
  } else if ('size' in entry && typeof entry.offset !== 'undefined') {
1225
- const fileOffset = baseOffset + parseInt(String(entry.offset), 10);
1307
+ const offsetVal = Number.parseInt(String(entry.offset), 10);
1308
+ if (!Number.isFinite(offsetVal) || offsetVal < 0 || !Number.isFinite(entry.size) || entry.size < 0) {
1309
+ throw new Error(`Invalid ASAR file entry offset/size at ${resolvedCurr}`);
1310
+ }
1311
+ const fileOffset = baseOffset + offsetVal;
1312
+ if (fileOffset + entry.size > fileBuf.length) {
1313
+ throw new Error(`ASAR entry exceeds archive bounds at ${resolvedCurr}`);
1314
+ }
1226
1315
  const fileData = fileBuf.subarray(fileOffset, fileOffset + entry.size);
1227
- await fsp.writeFile(currPath, fileData);
1316
+ await fsp.writeFile(resolvedCurr, fileData);
1228
1317
  extractedCount++;
1229
1318
  }
1230
1319
  };
1231
1320
 
1232
- await extractEntry(asar.header, dest);
1321
+ await extractEntry(asar.header, destRoot, 0);
1233
1322
  return {
1234
1323
  success: true,
1235
1324
  action: 'unpack',
@@ -1241,12 +1330,43 @@ export const reverseEngineering = {
1241
1330
  }
1242
1331
 
1243
1332
  try {
1333
+ const unzipOpts = {
1334
+ timeout: 60_000,
1335
+ maxBuffer: 10 * 1024 * 1024,
1336
+ windowsHide: true,
1337
+ ...(context.signal ? { signal: context.signal } : {})
1338
+ };
1244
1339
  if (listOnly) {
1245
- const listRes = await execFileAsync('unzip', ['-l', resolvedFile]);
1340
+ const listRes = await execFileAsync('unzip', ['-l', resolvedFile], unzipOpts);
1246
1341
  return { success: true, action: 'unpack', listOnly: true, contents: listRes.stdout.split('\n').slice(0, 50) };
1247
1342
  }
1343
+ const relDest = path.relative(path.resolve(workspaceDir), path.resolve(dest));
1344
+ if (relDest === '..' || relDest.startsWith(`..${path.sep}`) || path.isAbsolute(relDest)) {
1345
+ return { success: false, error: `Refusing to unpack archive outside workspace: ${dest}` };
1346
+ }
1347
+ const precheck = await execFileAsync('unzip', ['-Z', '-s', resolvedFile], unzipOpts);
1348
+ let totalUncompressed = 0;
1349
+ for (const line of precheck.stdout.split('\n')) {
1350
+ const trimmed = line.trim();
1351
+ if (!trimmed || trimmed.startsWith('Archive:') || trimmed.startsWith('Zip file size:') || /^\d+\s+files?,/.test(trimmed)) continue;
1352
+ if (/^l/.test(trimmed)) {
1353
+ return { success: false, error: `Refusing symlink entry inside archive: ${trimmed}` };
1354
+ }
1355
+ const parts = trimmed.split(/\s+/);
1356
+ const sizeVal = Number.parseInt(parts[3] || '0', 10);
1357
+ if (Number.isFinite(sizeVal) && sizeVal > 0) {
1358
+ totalUncompressed += sizeVal;
1359
+ if (totalUncompressed > 256 * 1024 * 1024) {
1360
+ return { success: false, error: 'Refusing archive exceeding 256 MB uncompressed safety limit.' };
1361
+ }
1362
+ }
1363
+ const entryName = parts.slice(8).join(' ').replace(/\\/g, '/');
1364
+ if (entryName && (entryName.startsWith('/') || /^[a-zA-Z]:/.test(entryName) || entryName.split('/').some(s => s === '..'))) {
1365
+ return { success: false, error: `Refusing unsafe zip path traversal entry: ${entryName}` };
1366
+ }
1367
+ }
1248
1368
  await fsp.mkdir(dest, { recursive: true });
1249
- await execFileAsync('unzip', ['-q', '-o', resolvedFile, '-d', dest]);
1369
+ await execFileAsync('unzip', ['-q', '-o', resolvedFile, '-d', dest], unzipOpts);
1250
1370
  return {
1251
1371
  success: true,
1252
1372
  action: 'unpack',
@@ -59,7 +59,7 @@ export function getEnhancedEnv(baseEnv) {
59
59
  path.join(os.homedir(), 'Library', 'Android', 'sdk'), // macOS
60
60
  path.join(os.homedir(), 'Android', 'Sdk'), // Linux
61
61
  '/usr/lib/android-sdk', // Linux package
62
- path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk') // Windows
62
+ ...(process.env.LOCALAPPDATA ? [path.join(process.env.LOCALAPPDATA, 'Android', 'Sdk')] : []) // Windows
63
63
  ];
64
64
  for (const dir of candidateDirs) {
65
65
  if (dir && fs.existsSync(dir)) {
@@ -184,8 +184,9 @@ export function isFinalCommandSearch(rawCommand) {
184
184
  lastStmt = subshellMatch[1].trim();
185
185
  }
186
186
  const pipeParts = lastStmt.split('|');
187
- const finalCmd = pipeParts.at(-1)?.trim().replace(/["'\)\s]+$/, '') || '';
188
- return /(?:^|\s)(grep|egrep|fgrep|diff|test|which|where|cmp|pidof|pgrep|find)\b/.test(finalCmd);
187
+ const rawFinalCmd = pipeParts.at(-1)?.trim().replace(/["'\)\s]+$/, '') || '';
188
+ const finalCmd = rawFinalCmd.replace(/^(?:adb\s+(?:-s\s+\S+\s+)?shell|ssh\s+\S+)\s+/i, '');
189
+ return /^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*(?:(?:\/(?:usr\/)?bin\/)?(?:grep|egrep|fgrep|diff|test|which|where|cmp|pidof|pgrep|find))(?:\s|$)/.test(finalCmd);
189
190
  }
190
191
  /**
191
192
  * Commands that are strictly read-only and idempotent.
@@ -218,10 +219,37 @@ export function isPersistentServerCommand(cmd) {
218
219
  }
219
220
  export const SERVER_READY_PATTERN = /(?:https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0):[0-9]+|serving\s+http\s+on|server\s+(?:running|started)|ready\s+in\s+[0-9]+|terra_server_running)/i;
220
221
  const COMMAND_CACHE_TTL_MS = 60_000;
222
+ const MAX_CACHE_ENTRIES = 64;
221
223
  const commandCache = new Map();
224
+ function setCachedResult(key, entry) {
225
+ if (commandCache.size >= MAX_CACHE_ENTRIES && !commandCache.has(key)) {
226
+ const oldest = commandCache.keys().next().value;
227
+ if (oldest !== undefined)
228
+ commandCache.delete(oldest);
229
+ }
230
+ commandCache.set(key, entry);
231
+ }
222
232
  export function clearSysRunCache() {
223
233
  commandCache.clear();
224
234
  }
235
+ function resolveSysCwd(rawCwd, context) {
236
+ const expand = (p) => {
237
+ const trimmed = p.trim();
238
+ if (trimmed === '~')
239
+ return os.homedir();
240
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
241
+ return path.join(os.homedir(), trimmed.slice(2));
242
+ }
243
+ return trimmed;
244
+ };
245
+ const fallbackBase = context?.parentLoop?.workspaceRoot?.trim()
246
+ ? path.resolve(expand(context.parentLoop.workspaceRoot))
247
+ : process.cwd();
248
+ if (!rawCwd || !rawCwd.trim())
249
+ return fallbackBase;
250
+ const expanded = expand(rawCwd);
251
+ return path.isAbsolute(expanded) ? path.resolve(expanded) : path.resolve(fallbackBase, expanded);
252
+ }
225
253
  export const sysRun = {
226
254
  schema: {
227
255
  name: 'sysRun',
@@ -238,7 +266,7 @@ export const sysRun = {
238
266
  },
239
267
  async execute(args, context = {}) {
240
268
  const rawCommand = (args?.command || '').trim();
241
- const cwd = args?.cwd ? args.cwd.replace(/^~\//, os.homedir() + '/') : process.cwd();
269
+ const cwd = resolveSysCwd(args?.cwd, context);
242
270
  let timeoutMs = 60000;
243
271
  const rawTimeout = args?.timeout;
244
272
  if (typeof rawTimeout === 'number' && Number.isFinite(rawTimeout) && rawTimeout > 0) {
@@ -259,9 +287,12 @@ export const sysRun = {
259
287
  timeoutMs = val <= 600 ? Math.round(val * 1000) : Math.round(val);
260
288
  }
261
289
  }
262
- if (timeoutMs < 1000) {
290
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1000) {
263
291
  timeoutMs = 1000;
264
292
  }
293
+ else if (timeoutMs > 2_147_483_647) {
294
+ timeoutMs = 2_147_483_647;
295
+ }
265
296
  const signal = context.signal;
266
297
  // A foreground server waits forever for requests. Keep launch-only turns
267
298
  // responsive and make it explicit that starting is not a readiness check.
@@ -343,6 +374,14 @@ export const sysRun = {
343
374
  const MAX_LENGTH = 50000;
344
375
  let outputBuffer = '';
345
376
  let isDetached = false;
377
+ const detachChild = () => {
378
+ child.stdout?.removeAllListeners('data');
379
+ child.stderr?.removeAllListeners('data');
380
+ child.stdout?.destroy();
381
+ child.stderr?.destroy();
382
+ child.stdin?.destroy();
383
+ child.unref();
384
+ };
346
385
  const checkServerDetach = () => {
347
386
  if (isDetached)
348
387
  return;
@@ -353,7 +392,7 @@ export const sysRun = {
353
392
  clearTimeout(timeoutId);
354
393
  if (serverGraceTimer)
355
394
  clearTimeout(serverGraceTimer);
356
- child.unref();
395
+ detachChild();
357
396
  resolve({
358
397
  success: true,
359
398
  output: cleanSubprocessOutput(outputBuffer),
@@ -393,7 +432,7 @@ export const sysRun = {
393
432
  isDetached = true;
394
433
  if (timeoutId)
395
434
  clearTimeout(timeoutId);
396
- child.unref();
435
+ detachChild();
397
436
  resolve({
398
437
  success: true,
399
438
  output: cleanSubprocessOutput(outputBuffer) || 'Server process started and running in background.',
@@ -403,15 +442,24 @@ export const sysRun = {
403
442
  }
404
443
  }, 2500);
405
444
  }
445
+ let settled = false;
446
+ const finish = (result) => {
447
+ if (settled)
448
+ return;
449
+ settled = true;
450
+ if (timeoutId)
451
+ clearTimeout(timeoutId);
452
+ if (serverGraceTimer)
453
+ clearTimeout(serverGraceTimer);
454
+ resolve(result);
455
+ };
406
456
  let timeoutId;
407
457
  if (timeoutMs > 0) {
408
458
  timeoutId = setTimeout(() => {
409
- if (isDetached)
459
+ if (isDetached || settled)
410
460
  return;
411
- if (serverGraceTimer)
412
- clearTimeout(serverGraceTimer);
413
461
  child.kill('SIGKILL');
414
- resolve({
462
+ finish({
415
463
  success: false,
416
464
  output: cleanSubprocessOutput(outputBuffer),
417
465
  error: `Process timed out after ${timeoutMs}ms`,
@@ -420,13 +468,9 @@ export const sysRun = {
420
468
  }, timeoutMs);
421
469
  }
422
470
  child.on('error', (err) => {
423
- if (isDetached)
471
+ if (isDetached || settled)
424
472
  return;
425
- if (timeoutId)
426
- clearTimeout(timeoutId);
427
- if (serverGraceTimer)
428
- clearTimeout(serverGraceTimer);
429
- resolve({
473
+ finish({
430
474
  success: false,
431
475
  output: cleanSubprocessOutput(outputBuffer),
432
476
  error: err.message,
@@ -434,25 +478,21 @@ export const sysRun = {
434
478
  });
435
479
  });
436
480
  child.on('close', (code) => {
437
- if (isDetached)
481
+ if (isDetached || settled)
438
482
  return;
439
- if (timeoutId)
440
- clearTimeout(timeoutId);
441
- if (serverGraceTimer)
442
- clearTimeout(serverGraceTimer);
443
483
  const cleanOutput = cleanSubprocessOutput(outputBuffer);
444
484
  const exitCode = typeof code === 'number' ? code : 1;
445
485
  if (exitCode === 0) {
446
486
  const res = { success: true, output: cleanOutput, exitCode: 0 };
447
487
  if (isIdempotent) {
448
- commandCache.set(cacheKey, {
488
+ setCachedResult(cacheKey, {
449
489
  output: cleanOutput,
450
490
  exitCode: 0,
451
491
  success: true,
452
492
  timestamp: Date.now()
453
493
  });
454
494
  }
455
- resolve(res);
495
+ finish(res);
456
496
  }
457
497
  else if (exitCode === 1 && isFinalCommandSearch(rawCommand)) {
458
498
  // Semantic Exit Code Normalization: Search tool found 0 matching lines.
@@ -463,7 +503,7 @@ export const sysRun = {
463
503
  note: 'Command executed successfully with 0 search matches.'
464
504
  };
465
505
  if (isIdempotent) {
466
- commandCache.set(cacheKey, {
506
+ setCachedResult(cacheKey, {
467
507
  output: res.output,
468
508
  exitCode: 1,
469
509
  success: true,
@@ -471,7 +511,7 @@ export const sysRun = {
471
511
  timestamp: Date.now()
472
512
  });
473
513
  }
474
- resolve(res);
514
+ finish(res);
475
515
  }
476
516
  else {
477
517
  let errorMsg = `Command exited with code ${exitCode}`;
@@ -479,10 +519,10 @@ export const sysRun = {
479
519
  errorMsg = 'adb failed: multiple devices/emulators connected. Pass `-s <serial>` (e.g. `adb -s emulator-5554 ...`) or set `export ANDROID_SERIAL=<serial>`.';
480
520
  }
481
521
  if (signal && signal.aborted) {
482
- resolve({ success: false, output: cleanOutput, error: 'Process killed by user.', exitCode: 1 });
522
+ finish({ success: false, output: cleanOutput, error: 'Process killed by user.', exitCode: 1 });
483
523
  }
484
524
  else {
485
- resolve({ success: false, output: cleanOutput, error: errorMsg, exitCode });
525
+ finish({ success: false, output: cleanOutput, error: errorMsg, exitCode });
486
526
  }
487
527
  }
488
528
  });
@@ -506,7 +546,7 @@ export const sysRunBg = {
506
546
  },
507
547
  async execute(args, context = {}) {
508
548
  try {
509
- const cwd = args.cwd ? args.cwd.replace(/^~\//, os.homedir() + '/') : process.cwd();
549
+ const cwd = resolveSysCwd(args?.cwd, context);
510
550
  const shell = os.platform() === 'win32' ? 'cmd.exe' : '/bin/bash';
511
551
  const shellArgs = os.platform() === 'win32' ? ['/c', args.command] : ['-c', args.command];
512
552
  const resolvedMode = resolveOsSandboxMode(process.env, context.parentLoop?.config?.osSandbox);