@causyne/agent 1.20.120 → 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 (276) 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 +117 -0
  14. package/src/agent/errorClassifier.ts +165 -0
  15. package/src/agent/promptIntent.js +200 -0
  16. package/src/agent/promptIntent.ts +203 -0
  17. package/src/agent/toolArgValidator.js +97 -0
  18. package/src/agent/toolArgValidator.ts +112 -0
  19. package/src/agentLoop.js +33 -344
  20. package/src/agentLoop.ts +51 -352
  21. package/src/approvalGrants.js +19 -7
  22. package/src/approvalGrants.ts +20 -7
  23. package/src/approvalPolicy.js +48 -15
  24. package/src/approvalPolicy.ts +46 -15
  25. package/src/autoUpdate.js +116 -10
  26. package/src/autoUpdate.ts +149 -10
  27. package/src/browser/causyneBrowser.js +3 -2
  28. package/src/browser/causyneBrowser.ts +3 -2
  29. package/src/browser/searchProviders.js +1 -1
  30. package/src/browser/searchProviders.ts +1 -1
  31. package/src/cliMode.js +16 -2
  32. package/src/commands.js +10 -9
  33. package/src/config.js +288 -272
  34. package/src/config.ts +342 -0
  35. package/src/configVault.js +271 -0
  36. package/src/configVault.ts +273 -0
  37. package/src/continuum/compactor.js +2 -1
  38. package/src/continuum/compactor.ts +2 -1
  39. package/src/continuum/sanitizer.js +10 -3
  40. package/src/continuum/sanitizer.ts +9 -3
  41. package/src/continuum/ui/continuumPickerView.js +3 -2
  42. package/src/continuum/ui/continuumPickerView.ts +3 -2
  43. package/src/core/contextCompactor.js +70 -11
  44. package/src/core/contextCompactor.ts +83 -11
  45. package/src/cortex/vectorDb.js +26 -15
  46. package/src/cortex/vectorDb.ts +26 -16
  47. package/src/creative/liveBridge.js +7 -5
  48. package/src/creative/liveBridge.ts +7 -5
  49. package/src/creative/studioScripts.js +16 -5
  50. package/src/creative/studioScripts.ts +14 -5
  51. package/src/decisionPolicy.js +16 -4
  52. package/src/decisionPolicy.ts +14 -4
  53. package/src/documentEngine/antiSlopAuditor.js +10 -5
  54. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  55. package/src/documentEngine/documentForge.js +47 -15
  56. package/src/documentEngine/documentForge.ts +43 -14
  57. package/src/dynamicCatalogue.js +42 -73
  58. package/src/dynamicCatalogue.ts +74 -60
  59. package/src/engines/design.js +2 -1
  60. package/src/engines/design.ts +2 -1
  61. package/src/engines/film.js +4 -4
  62. package/src/engines/film.ts +2 -2
  63. package/src/engines/light.js +2 -1
  64. package/src/engines/light.ts +2 -1
  65. package/src/engines/registry.js +1 -1
  66. package/src/engines/registry.ts +1 -1
  67. package/src/engines/reverseHarness.js +4 -3
  68. package/src/engines/reverseHarness.ts +4 -3
  69. package/src/entrypoint.js +77 -4
  70. package/src/headlessCli.js +305 -0
  71. package/src/headlessCli.ts +381 -0
  72. package/src/historyPruner.js +3 -2
  73. package/src/historyPruner.ts +3 -2
  74. package/src/hooks.js +3 -0
  75. package/src/hooks.ts +3 -0
  76. package/src/implementationPlan.js +21 -11
  77. package/src/implementationPlan.ts +21 -11
  78. package/src/infra/atomicWriter.js +4 -1
  79. package/src/infra/atomicWriter.ts +4 -1
  80. package/src/launchIntent.js +1 -1
  81. package/src/launchIntent.ts +1 -1
  82. package/src/mcp/mcpClient.js +38 -11
  83. package/src/mcp/mcpClient.ts +44 -11
  84. package/src/mcp/mcpRegistry.js +2 -5
  85. package/src/mcp/mcpRegistry.ts +2 -5
  86. package/src/mcp/mcpSecurity.js +189 -0
  87. package/src/mcp/mcpSecurity.ts +190 -0
  88. package/src/memory/scopedFacts.js +1 -1
  89. package/src/memory/scopedFacts.ts +1 -1
  90. package/src/memory/symbolFolder.js +1 -1
  91. package/src/memory/symbolFolder.ts +1 -1
  92. package/src/modelRouter.js +1 -1
  93. package/src/modelRouter.ts +1 -1
  94. package/src/observer/evidence.js +10 -4
  95. package/src/observer/evidence.ts +10 -4
  96. package/src/osKeychain.js +263 -0
  97. package/src/osKeychain.ts +287 -0
  98. package/src/perception.js +3 -2
  99. package/src/perception.ts +3 -2
  100. package/src/planCache.js +2 -2
  101. package/src/planCache.ts +2 -2
  102. package/src/pluginsFactory/pluginsFactory.js +19 -11
  103. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  104. package/src/promptMentions.js +2 -2
  105. package/src/promptMentions.ts +2 -2
  106. package/src/providers/acp.js +1 -1
  107. package/src/providers/acp.ts +1 -1
  108. package/src/providers/anthropic.js +328 -385
  109. package/src/providers/anthropic.ts +386 -0
  110. package/src/providers/antigravity.js +10 -4
  111. package/src/providers/antigravity.ts +10 -4
  112. package/src/providers/base.js +221 -319
  113. package/src/providers/base.ts +340 -0
  114. package/src/providers/byokHttp.js +397 -0
  115. package/src/providers/byokHttp.ts +497 -0
  116. package/src/providers/byokStream.js +748 -0
  117. package/src/providers/byokStream.ts +863 -0
  118. package/src/providers/dashscope-byok.js +98 -81
  119. package/src/providers/dashscope-byok.ts +114 -0
  120. package/src/providers/deepseek.js +74 -64
  121. package/src/providers/deepseek.ts +99 -0
  122. package/src/providers/factory.js +35 -28
  123. package/src/providers/factory.ts +40 -0
  124. package/src/providers/gemini.js +229 -253
  125. package/src/providers/gemini.ts +261 -0
  126. package/src/providers/loopGuard.js +9 -5
  127. package/src/providers/loopGuard.ts +10 -5
  128. package/src/providers/moonshot.js +71 -64
  129. package/src/providers/moonshot.ts +93 -0
  130. package/src/providers/muse.js +82 -152
  131. package/src/providers/muse.ts +122 -0
  132. package/src/providers/ollama.js +116 -93
  133. package/src/providers/ollama.ts +135 -0
  134. package/src/providers/openai-compatible.js +114 -65
  135. package/src/providers/openai-compatible.ts +139 -0
  136. package/src/providers/openai.js +22 -15
  137. package/src/providers/openai.ts +30 -0
  138. package/src/providers/openrouter.js +194 -98
  139. package/src/providers/openrouter.ts +202 -97
  140. package/src/providers/pi.js +6 -0
  141. package/src/providers/pi.ts +6 -0
  142. package/src/providers/qwen-byok.js +97 -71
  143. package/src/providers/qwen-byok.ts +113 -0
  144. package/src/providers/toolContracts.js +40 -14
  145. package/src/providers/toolContracts.ts +35 -14
  146. package/src/providers/wireNormalizer.js +78 -11
  147. package/src/providers/wireNormalizer.ts +68 -12
  148. package/src/providers/xai.js +74 -64
  149. package/src/providers/xai.ts +97 -0
  150. package/src/reliability/assetEvidence.js +4 -2
  151. package/src/reliability/assetEvidence.ts +4 -2
  152. package/src/sandbox.js +486 -530
  153. package/src/sandbox.ts +552 -0
  154. package/src/sandboxPolicy.js +1287 -0
  155. package/src/sandboxPolicy.ts +1381 -0
  156. package/src/sessionJournal.js +55 -3
  157. package/src/sessionJournal.ts +58 -3
  158. package/src/skills/skillResourceSafety.js +19 -8
  159. package/src/skills/skillResourceSafety.ts +16 -7
  160. package/src/skillsManager.js +3 -3
  161. package/src/skillsManager.ts +3 -3
  162. package/src/smartToolsUse.js +28 -4
  163. package/src/smartToolsUse.ts +29 -7
  164. package/src/stallGuard.js +45 -22
  165. package/src/stallGuard.ts +46 -22
  166. package/src/subagentJournal.js +6 -4
  167. package/src/subagentJournal.ts +6 -4
  168. package/src/textDiff.js +6 -1
  169. package/src/textDiff.ts +6 -1
  170. package/src/timeMachine.js +7 -1
  171. package/src/timeMachine.ts +7 -1
  172. package/src/tokenTracker.js +43 -28
  173. package/src/tokenTracker.ts +44 -30
  174. package/src/toolPacks.js +3 -1
  175. package/src/toolPacks.ts +3 -1
  176. package/src/tools/archive.js +245 -35
  177. package/src/tools/archive.ts +244 -35
  178. package/src/tools/computerUse.js +7 -3
  179. package/src/tools/computerUse.ts +7 -3
  180. package/src/tools/creativeApps.js +13 -8
  181. package/src/tools/creativeApps.ts +22 -9
  182. package/src/tools/deferredMcpSearch.js +26 -14
  183. package/src/tools/deferredMcpSearch.ts +26 -14
  184. package/src/tools/desktopOpen.js +69 -10
  185. package/src/tools/desktopOpen.ts +70 -11
  186. package/src/tools/documentForge.js +167 -82
  187. package/src/tools/documentForge.ts +169 -84
  188. package/src/tools/fsEdit.js +101 -30
  189. package/src/tools/fsEdit.ts +105 -32
  190. package/src/tools/fsFind.js +8 -5
  191. package/src/tools/fsFind.ts +7 -4
  192. package/src/tools/fsRead.js +119 -13
  193. package/src/tools/fsRead.ts +124 -13
  194. package/src/tools/fsWrite.js +17 -5
  195. package/src/tools/fsWrite.ts +17 -7
  196. package/src/tools/generateMediaViaApi.js +82 -19
  197. package/src/tools/generateMediaViaApi.ts +80 -19
  198. package/src/tools/memoryRecall.js +62 -11
  199. package/src/tools/memoryRecall.ts +70 -13
  200. package/src/tools/memoryWrite.js +27 -14
  201. package/src/tools/memoryWrite.ts +30 -14
  202. package/src/tools/multiEdit.js +100 -30
  203. package/src/tools/multiEdit.ts +104 -32
  204. package/src/tools/nativeEngine.js +33 -18
  205. package/src/tools/nativeEngine.ts +31 -18
  206. package/src/tools/openSourceToolProvisioner.js +49 -14
  207. package/src/tools/openSourceToolProvisioner.ts +54 -15
  208. package/src/tools/osSandbox.js +513 -0
  209. package/src/tools/osSandbox.ts +588 -0
  210. package/src/tools/payloadSanitizer.js +40 -8
  211. package/src/tools/payloadSanitizer.ts +39 -8
  212. package/src/tools/peerAgent.js +96 -34
  213. package/src/tools/peerAgent.ts +114 -37
  214. package/src/tools/persistentShell.js +8 -3
  215. package/src/tools/pluginsFactory.js +38 -6
  216. package/src/tools/pluginsFactory.ts +42 -6
  217. package/src/tools/readNativeSkill.js +10 -8
  218. package/src/tools/readNativeSkill.ts +10 -8
  219. package/src/tools/requestDecision.js +10 -3
  220. package/src/tools/requestDecision.ts +10 -3
  221. package/src/tools/resolveAutomator.js +91 -17
  222. package/src/tools/resolveAutomator.ts +102 -17
  223. package/src/tools/reverseEngineering.js +168 -41
  224. package/src/tools/reverseEngineering.ts +161 -41
  225. package/src/tools/subprocessEnv.js +197 -0
  226. package/src/tools/subprocessEnv.ts +212 -0
  227. package/src/tools/sysRun.js +108 -35
  228. package/src/tools/sysRun.ts +119 -31
  229. package/src/tools/toolDispatch.js +24 -1
  230. package/src/tools/toolDispatch.ts +21 -1
  231. package/src/tools/toolOutputStore.js +62 -23
  232. package/src/tools/toolOutputStore.ts +56 -23
  233. package/src/tools/toolScanner.js +13 -10
  234. package/src/tools/toolScanner.ts +13 -10
  235. package/src/tools/toolSelfRepair.js +94 -28
  236. package/src/tools/toolSelfRepair.ts +96 -28
  237. package/src/tools/uiForge.js +71 -6
  238. package/src/tools/uiForge.ts +74 -6
  239. package/src/tools/viewImage.js +62 -17
  240. package/src/tools/viewImage.ts +57 -12
  241. package/src/tools/visionInspector.js +15 -3
  242. package/src/tools/visionInspector.ts +15 -3
  243. package/src/tools/walkerSafety.js +2 -0
  244. package/src/tools/walkerSafety.ts +1 -0
  245. package/src/tools/webFetch.js +105 -10
  246. package/src/tools/webFetch.ts +105 -11
  247. package/src/tui/banner.js +3 -2
  248. package/src/tui/banner.ts +3 -2
  249. package/src/tui/consoleGuard.js +12 -4
  250. package/src/tui/consoleGuard.ts +9 -4
  251. package/src/tui/messageInteraction.js +2 -3
  252. package/src/tui/messageInteraction.ts +2 -3
  253. package/src/tui/modelPicker.js +1 -0
  254. package/src/tui/modelPicker.ts +1 -0
  255. package/src/tui/overlay.js +3 -1
  256. package/src/tui/overlay.ts +3 -1
  257. package/src/tui/sessionPicker.js +3 -2
  258. package/src/tui/sessionPicker.ts +3 -2
  259. package/src/tui/sessionPickerView.js +7 -1
  260. package/src/tui/sessionPickerView.ts +6 -1
  261. package/src/tui/toolOutputNormalizer.js +2 -3
  262. package/src/tui/toolOutputNormalizer.ts +4 -3
  263. package/src/tui/viewport.js +4 -4
  264. package/src/tui/viewport.ts +5 -5
  265. package/src/tui/workspaceIdentity.js +2 -1
  266. package/src/tui/workspaceIdentity.ts +2 -1
  267. package/src/uncertainty.js +8 -3
  268. package/src/uncertainty.ts +8 -3
  269. package/src/utils/paths.js +8 -5
  270. package/src/utils/paths.ts +9 -7
  271. package/src/vfeTracker.js +9 -3
  272. package/src/vfeTracker.ts +9 -3
  273. package/src/config.d.ts +0 -2
  274. package/src/providers/base.d.ts +0 -94
  275. package/src/providers/factory.d.ts +0 -1
  276. 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',
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Causyne Agent — Subprocess Environment Secret Isolation (CWE-526)
3
+ *
4
+ * Strips host LLM provider API keys, Causyne internal vault/auth secrets, and
5
+ * high-value cloud/registry secret credentials before spawning shell tools so
6
+ * prompt-injected shell commands or untrusted build scripts cannot exfiltrate
7
+ * ambient credentials via `env` / `printenv`.
8
+ *
9
+ * Developers who intentionally need a specific variable inside a subprocess
10
+ * (for example, running an integration test suite) can opt in via
11
+ * `CAUSYNE_PASSTHROUGH_ENV=VAR_A,VAR_B`. Internal Causyne vault/dev secrets
12
+ * remain permanently excluded from subprocesses.
13
+ */
14
+ export const ALWAYS_BLOCKED_SUBPROCESS_ENV = new Set([
15
+ 'CAUSYNE_VAULT_KEY',
16
+ 'CAUSYNE_DEV_SECRET',
17
+ 'CAUSYNE_DEV_TOKEN'
18
+ ]);
19
+ export const SENSITIVE_EXACT_ENV_KEYS = new Set([
20
+ // LLM & AI provider API keys
21
+ 'OPENAI_API_KEY',
22
+ 'OPENAI_ADMIN_KEY',
23
+ 'OPENAI_ORG_KEY',
24
+ 'ANTHROPIC_API_KEY',
25
+ 'CLAUDE_API_KEY',
26
+ 'GEMINI_API_KEY',
27
+ 'GOOGLE_API_KEY',
28
+ 'GOOGLE_GENERATIVE_AI_API_KEY',
29
+ 'OPENROUTER_API_KEY',
30
+ 'DEEPSEEK_API_KEY',
31
+ 'XAI_API_KEY',
32
+ 'GROK_API_KEY',
33
+ 'MOONSHOT_API_KEY',
34
+ 'KIMI_API_KEY',
35
+ 'DASHSCOPE_API_KEY',
36
+ 'QWEN_API_KEY',
37
+ 'MUSE_API_KEY',
38
+ 'META_API_KEY',
39
+ 'LLAMA_API_KEY',
40
+ 'MISTRAL_API_KEY',
41
+ 'COHERE_API_KEY',
42
+ 'GROQ_API_KEY',
43
+ 'TOGETHER_API_KEY',
44
+ 'PERPLEXITY_API_KEY',
45
+ 'FIREWORKS_API_KEY',
46
+ 'CEREBRAS_API_KEY',
47
+ 'SAMBANOVA_API_KEY',
48
+ 'HUGGINGFACE_API_KEY',
49
+ 'HF_TOKEN',
50
+ 'HUGGING_FACE_HUB_TOKEN',
51
+ 'REPLICATE_API_TOKEN',
52
+ 'VOYAGE_API_KEY',
53
+ 'ELEVENLABS_API_KEY',
54
+ 'FAL_KEY',
55
+ 'STABILITY_API_KEY',
56
+ 'AZURE_OPENAI_API_KEY',
57
+ // Causyne internal auth / vault credentials
58
+ 'CAUSYNE_API_KEY',
59
+ 'CAUSYNE_AUTH_TOKEN',
60
+ 'CAUSYNE_ACCESS_TOKEN',
61
+ 'CAUSYNE_SECRET',
62
+ 'CAUSYNE_VAULT_KEY',
63
+ 'CAUSYNE_DEV_SECRET',
64
+ 'CAUSYNE_DEV_TOKEN',
65
+ // Cloud, package registry, VCS, and infrastructure raw secrets
66
+ 'AWS_SECRET_ACCESS_KEY',
67
+ 'AWS_SESSION_TOKEN',
68
+ 'AWS_SECURITY_TOKEN',
69
+ 'NPM_TOKEN',
70
+ 'NODE_AUTH_TOKEN',
71
+ 'YARN_NPM_AUTH_TOKEN',
72
+ 'PYPI_API_TOKEN',
73
+ 'TWINE_PASSWORD',
74
+ 'CARGO_REGISTRY_TOKEN',
75
+ 'RUBYGEMS_API_KEY',
76
+ 'NUGET_API_KEY',
77
+ 'GITHUB_TOKEN',
78
+ 'GH_TOKEN',
79
+ 'GITLAB_TOKEN',
80
+ 'BITBUCKET_TOKEN',
81
+ 'SLACK_BOT_TOKEN',
82
+ 'SLACK_TOKEN',
83
+ 'DISCORD_TOKEN',
84
+ 'TELEGRAM_BOT_TOKEN',
85
+ 'STRIPE_SECRET_KEY',
86
+ 'STRIPE_API_KEY',
87
+ 'SENDGRID_API_KEY',
88
+ 'TWILIO_AUTH_TOKEN',
89
+ 'DATABASE_PASSWORD',
90
+ 'DB_PASSWORD',
91
+ 'PGPASSWORD',
92
+ 'MYSQL_PWD',
93
+ 'REDIS_PASSWORD',
94
+ 'DOCKER_PASSWORD',
95
+ 'GCP_SERVICE_ACCOUNT_KEY',
96
+ 'GOOGLE_APPLICATION_CREDENTIALS_JSON',
97
+ 'CLOUDFLARE_API_TOKEN',
98
+ 'VERCEL_TOKEN',
99
+ 'NETLIFY_AUTH_TOKEN',
100
+ 'FLY_API_TOKEN',
101
+ 'DIGITALOCEAN_ACCESS_TOKEN',
102
+ 'HEROKU_API_KEY',
103
+ 'DATADOG_API_KEY',
104
+ 'SENTRY_AUTH_TOKEN'
105
+ ]);
106
+ const SENSITIVE_ENV_SUFFIXES = [
107
+ '_API_KEY',
108
+ '_SECRET_KEY',
109
+ '_PRIVATE_KEY',
110
+ '_ACCESS_SECRET',
111
+ '_AUTH_SECRET',
112
+ '_CLIENT_SECRET',
113
+ '_SIGNING_KEY',
114
+ '_ENCRYPTION_KEY',
115
+ '_MASTER_KEY',
116
+ '_VAULT_KEY',
117
+ '_SECRET_TOKEN',
118
+ '_ACCESS_TOKEN',
119
+ '_AUTH_TOKEN',
120
+ '_REFRESH_TOKEN'
121
+ ];
122
+ /**
123
+ * Parses `CAUSYNE_PASSTHROUGH_ENV` (comma-separated exact variable names) into
124
+ * an uppercased allowlist while excluding permanently blocked internal keys.
125
+ */
126
+ export function parsePassthroughAllowlist(env, extra) {
127
+ const allow = new Set();
128
+ const addEntry = (raw) => {
129
+ const trimmed = raw.trim().toUpperCase();
130
+ if (!trimmed || trimmed === '*')
131
+ return;
132
+ if (ALWAYS_BLOCKED_SUBPROCESS_ENV.has(trimmed))
133
+ return;
134
+ allow.add(trimmed);
135
+ };
136
+ const envValue = env.CAUSYNE_PASSTHROUGH_ENV;
137
+ if (typeof envValue === 'string' && envValue.trim().length > 0) {
138
+ for (const part of envValue.split(',')) {
139
+ addEntry(part);
140
+ }
141
+ }
142
+ if (Array.isArray(extra)) {
143
+ for (const part of extra) {
144
+ if (typeof part === 'string')
145
+ addEntry(part);
146
+ }
147
+ }
148
+ return allow;
149
+ }
150
+ /**
151
+ * Returns true if an environment variable name represents a secret credential
152
+ * that must be stripped from shell subprocesses by default.
153
+ */
154
+ export function isSensitiveEnvKey(key) {
155
+ if (typeof key !== 'string' || key.length === 0)
156
+ return false;
157
+ const upper = key.toUpperCase();
158
+ if (ALWAYS_BLOCKED_SUBPROCESS_ENV.has(upper))
159
+ return true;
160
+ if (SENSITIVE_EXACT_ENV_KEYS.has(upper))
161
+ return true;
162
+ if (upper.startsWith('CAUSYNE_')) {
163
+ if (upper.includes('KEY') ||
164
+ upper.includes('TOKEN') ||
165
+ upper.includes('SECRET') ||
166
+ upper.includes('PASSWORD') ||
167
+ upper.includes('CREDENTIAL')) {
168
+ return true;
169
+ }
170
+ }
171
+ for (const suffix of SENSITIVE_ENV_SUFFIXES) {
172
+ if (upper.endsWith(suffix))
173
+ return true;
174
+ }
175
+ return false;
176
+ }
177
+ /**
178
+ * Returns a copy of `baseEnv` (default `process.env`) with sensitive API keys
179
+ * and secrets removed unless explicitly listed in `CAUSYNE_PASSTHROUGH_ENV` or
180
+ * `options.passthrough`. Internal vault/dev keys are never passed through.
181
+ */
182
+ export function sanitizeSubprocessEnv(baseEnv, options) {
183
+ const source = baseEnv ?? process.env;
184
+ const allowlist = parsePassthroughAllowlist(source, options?.passthrough);
185
+ const sanitized = {};
186
+ for (const [key, value] of Object.entries(source)) {
187
+ if (value === undefined)
188
+ continue;
189
+ const upper = key.toUpperCase();
190
+ if (ALWAYS_BLOCKED_SUBPROCESS_ENV.has(upper))
191
+ continue;
192
+ if (isSensitiveEnvKey(key) && !allowlist.has(upper))
193
+ continue;
194
+ sanitized[key] = value;
195
+ }
196
+ return sanitized;
197
+ }