@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
@@ -1,5 +1,5 @@
1
1
  import fs from 'node:fs/promises';
2
- import { existsSync, statSync, createWriteStream } from 'node:fs';
2
+ import { existsSync, lstatSync, realpathSync, statSync, createWriteStream } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { execFileSync } from 'node:child_process';
5
5
  import { resolveUserPath } from '../utils/paths.js';
@@ -11,6 +11,68 @@ export interface ArchiveArgs {
11
11
  destination: string;
12
12
  }
13
13
 
14
+ export interface ArchiveContext {
15
+ workspaceRoot?: string;
16
+ workspacePaths?: string[];
17
+ grantAllAccess?: boolean;
18
+ parentLoop?: { workspaceRoot?: string };
19
+ }
20
+
21
+ function expandArchivePath(raw: string, baseRoot?: string): string {
22
+ const trimmed = raw.trim();
23
+ if (trimmed === '~' || trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
24
+ return resolveUserPath(trimmed);
25
+ }
26
+ if (path.isAbsolute(trimmed)) return path.resolve(trimmed);
27
+ return path.resolve(baseRoot ? resolveUserPath(baseRoot) : process.cwd(), trimmed);
28
+ }
29
+
30
+ function canonicalArchivePath(target: string): string {
31
+ const resolved = path.resolve(target);
32
+ try {
33
+ return realpathSync(resolved);
34
+ } catch {
35
+ let current = resolved;
36
+ const missing: string[] = [];
37
+ for (let i = 0; i < 64; i++) {
38
+ const parent = path.dirname(current);
39
+ if (parent === current) break;
40
+ missing.unshift(path.basename(current));
41
+ current = parent;
42
+ try {
43
+ return path.join(realpathSync(current), ...missing);
44
+ } catch {
45
+ continue;
46
+ }
47
+ }
48
+ return resolved;
49
+ }
50
+ }
51
+
52
+ function assertArchiveScope(target: string, context?: ArchiveContext): void {
53
+ if (!context || context.grantAllAccess === true) return;
54
+ const configured = Array.isArray(context.workspacePaths)
55
+ ? context.workspacePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map(p => p.trim())
56
+ : [];
57
+ const roots = configured.length > 0
58
+ ? configured
59
+ : [context.parentLoop?.workspaceRoot, context.workspaceRoot]
60
+ .filter((p): p is string => typeof p === 'string' && p.trim().length > 0)
61
+ .map(p => p.trim());
62
+ if (roots.length === 0) return;
63
+ const physical = canonicalArchivePath(target);
64
+ for (const root of roots) {
65
+ try {
66
+ const realRoot = realpathSync(resolveUserPath(root));
67
+ const rel = path.relative(realRoot, physical);
68
+ if (rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel))) return;
69
+ } catch {
70
+ continue;
71
+ }
72
+ }
73
+ throw new Error(`Archive path resolves outside the selected workspace: ${target}`);
74
+ }
75
+
14
76
  export interface ArchiveResult {
15
77
  success: boolean;
16
78
  output?: string;
@@ -33,18 +95,34 @@ export const archive = {
33
95
  }
34
96
  },
35
97
 
36
- async execute(args: ArchiveArgs): Promise<ArchiveResult> {
98
+ async execute(args: ArchiveArgs, context?: ArchiveContext): Promise<ArchiveResult> {
37
99
  try {
38
- if (!args || !args.action || !args.source || !args.destination) {
100
+ if (!args || typeof args !== 'object' || typeof args.action !== 'string' || typeof args.source !== 'string' || typeof args.destination !== 'string' || !args.source.trim() || !args.destination.trim()) {
39
101
  return { success: false, error: 'Missing required arguments: action, source, destination' };
40
102
  }
41
103
 
42
- const source = resolveUserPath(args.source);
43
- const dest = resolveUserPath(args.destination);
104
+ const baseRoot = context?.parentLoop?.workspaceRoot?.trim()
105
+ || context?.workspaceRoot?.trim()
106
+ || context?.workspacePaths?.find((p): p is string => typeof p === 'string' && p.trim().length > 0)?.trim();
107
+ const isHomeOrAbs = (val: string): boolean => {
108
+ const trimmed = val.trim();
109
+ return trimmed === '~' || trimmed.startsWith('~/') || trimmed.startsWith('~\\') || path.isAbsolute(trimmed);
110
+ };
111
+ const source = (!baseRoot || isHomeOrAbs(args.source))
112
+ ? resolveUserPath(args.source)
113
+ : expandArchivePath(args.source, baseRoot);
114
+ const dest = (!baseRoot || isHomeOrAbs(args.destination))
115
+ ? resolveUserPath(args.destination)
116
+ : expandArchivePath(args.destination, baseRoot);
117
+ assertArchiveScope(source, context);
118
+ assertArchiveScope(dest, context);
44
119
 
45
120
  if (!existsSync(source)) {
46
121
  return { success: false, error: `Archive source path not found: ${source}` };
47
122
  }
123
+ if (existsSync(dest) && lstatSync(dest).isSymbolicLink()) {
124
+ return { success: false, error: `Refusing to write through symbolic link destination: ${dest}` };
125
+ }
48
126
 
49
127
  if (args.action === 'extract') {
50
128
  return await extractArchive(source, dest);
@@ -59,6 +137,64 @@ export const archive = {
59
137
  }
60
138
  };
61
139
 
140
+ function isUnsafeArchiveMemberName(member: string): boolean {
141
+ const normalized = member.replace(/\\/g, '/').trim();
142
+ if (!normalized) return true;
143
+ if (normalized.startsWith('/') || /^[a-zA-Z]:/.test(normalized)) return true;
144
+ return normalized.split('/').some(seg => seg === '..');
145
+ }
146
+
147
+ function precheckNativeZipEntries(source: string): void {
148
+ const listing = execFileSync('unzip', ['-Z', '-s', source], {
149
+ stdio: 'pipe',
150
+ encoding: 'utf8',
151
+ timeout: 15_000,
152
+ maxBuffer: 10 * 1024 * 1024,
153
+ windowsHide: true
154
+ });
155
+ for (const line of listing.split('\n')) {
156
+ const trimmed = line.trim();
157
+ if (!trimmed || trimmed.startsWith('Archive:') || trimmed.startsWith('Zip file size:') || /^\d+\s+files?,/.test(trimmed)) continue;
158
+ if (/^l/.test(trimmed)) {
159
+ throw new Error(`Refusing symlink entry inside zip archive: ${trimmed}`);
160
+ }
161
+ const parts = trimmed.split(/\s+/);
162
+ const name = parts.slice(8).join(' ');
163
+ if (name && isUnsafeArchiveMemberName(name)) {
164
+ throw new Error(`Refusing unsafe zip archive path traversal entry: ${name}`);
165
+ }
166
+ }
167
+ }
168
+
169
+ function precheckNativeTarEntries(source: string): void {
170
+ const listing = execFileSync('tar', ['-tvf', source], {
171
+ stdio: 'pipe',
172
+ encoding: 'utf8',
173
+ timeout: 15_000,
174
+ maxBuffer: 10 * 1024 * 1024,
175
+ windowsHide: true
176
+ });
177
+ for (const line of listing.split('\n')) {
178
+ const trimmed = line.trim();
179
+ if (!trimmed) continue;
180
+ if (/^[lhbcp]/.test(trimmed) || trimmed.includes(' -> ')) {
181
+ throw new Error(`Refusing symlink or special device entry inside tar archive: ${trimmed}`);
182
+ }
183
+ }
184
+ const names = execFileSync('tar', ['-tf', source], {
185
+ stdio: 'pipe',
186
+ encoding: 'utf8',
187
+ timeout: 15_000,
188
+ maxBuffer: 10 * 1024 * 1024,
189
+ windowsHide: true
190
+ });
191
+ for (const name of names.split('\n')) {
192
+ if (name.trim() && isUnsafeArchiveMemberName(name)) {
193
+ throw new Error(`Refusing unsafe tar archive path traversal entry: ${name}`);
194
+ }
195
+ }
196
+ }
197
+
62
198
  async function extractArchive(source: string, dest: string): Promise<ArchiveResult> {
63
199
  await fs.mkdir(dest, { recursive: true });
64
200
 
@@ -76,53 +212,107 @@ async function extractArchive(source: string, dest: string): Promise<ArchiveResu
76
212
  const isZip = source.toLowerCase().endsWith('.zip') || source.toLowerCase().endsWith('.jar');
77
213
  const isTar = /\.(tar|tar\.gz|tgz|tar\.bz2|tar\.xz)$/i.test(source);
78
214
 
79
- // 2. Native unzip on macOS / Linux
215
+ // 2. Native unzip on macOS / Linux (pre-checked against Zip-Slip and symlinks)
80
216
  if (isZip) {
81
217
  try {
82
- execFileSync('unzip', ['-q', '-o', source, '-d', dest], { stdio: 'pipe' });
218
+ precheckNativeZipEntries(source);
219
+ execFileSync('unzip', ['-q', '-o', source, '-d', dest], {
220
+ stdio: 'pipe',
221
+ timeout: 60_000,
222
+ maxBuffer: 10 * 1024 * 1024,
223
+ windowsHide: true
224
+ });
83
225
  return { success: true, output: `Extracted successfully to ${dest} (via unzip)` };
84
- } catch {
226
+ } catch (zipErr: any) {
227
+ const msg = String(zipErr?.message || '');
228
+ if (msg.startsWith('Refusing ')) {
229
+ return { success: false, error: msg };
230
+ }
85
231
  // Fall through to python3 or powershell
86
232
  }
87
233
  }
88
234
 
89
- // 3. Native tar on macOS / Linux
235
+ // 3. Native tar on macOS / Linux (pre-checked against Tar-Slip and symlinks)
90
236
  if (isTar || !isZip) {
91
237
  try {
92
- execFileSync('tar', ['-xf', source, '-C', dest], { stdio: 'pipe' });
238
+ precheckNativeTarEntries(source);
239
+ execFileSync('tar', ['-xf', source, '-C', dest], {
240
+ stdio: 'pipe',
241
+ timeout: 60_000,
242
+ maxBuffer: 10 * 1024 * 1024,
243
+ windowsHide: true
244
+ });
93
245
  return { success: true, output: `Extracted successfully to ${dest} (via tar)` };
94
- } catch {
246
+ } catch (tarErr: any) {
247
+ const msg = String(tarErr?.message || '');
248
+ if (msg.startsWith('Refusing ')) {
249
+ return { success: false, error: msg };
250
+ }
95
251
  // Fall through
96
252
  }
97
253
  }
98
254
 
99
- // 4. Cross-platform Python standard library fallback
255
+ // 4. Cross-platform Python standard library fallback (Zip-Slip & Tar-Slip safe)
100
256
  try {
101
257
  execFileSync('python3', [
102
258
  '-c',
103
- 'import zipfile, tarfile, sys, os\n' +
104
- 'src, dst = sys.argv[1], sys.argv[2]\n' +
259
+ 'import zipfile, tarfile, sys, os, stat\n' +
260
+ 'src, dst = sys.argv[1], os.path.realpath(sys.argv[2])\n' +
261
+ 'max_bytes = 256 * 1024 * 1024\n' +
262
+ 'def safe_target(name):\n' +
263
+ ' if not name or name.startswith("/") or name.startswith("\\\\") or (len(name) > 1 and name[1] == ":"):\n' +
264
+ ' raise ValueError(f"Unsafe archive entry path: {name}")\n' +
265
+ ' out = os.path.realpath(os.path.join(dst, name))\n' +
266
+ ' if out != dst and not out.startswith(dst + os.sep):\n' +
267
+ ' raise ValueError(f"Archive path traversal blocked: {name}")\n' +
268
+ ' return out\n' +
105
269
  'if zipfile.is_zipfile(src):\n' +
106
270
  ' with zipfile.ZipFile(src, "r") as z:\n' +
271
+ ' total = 0\n' +
272
+ ' for info in z.infolist():\n' +
273
+ ' if stat.S_ISLNK(info.external_attr >> 16):\n' +
274
+ ' raise ValueError(f"Refusing symlink archive entry: {info.filename}")\n' +
275
+ ' total += info.file_size\n' +
276
+ ' if total > max_bytes:\n' +
277
+ ' raise ValueError("Archive exceeds 256 MB uncompressed safety limit")\n' +
278
+ ' safe_target(info.filename)\n' +
107
279
  ' z.extractall(dst)\n' +
108
280
  'elif tarfile.is_tarfile(src):\n' +
109
281
  ' with tarfile.open(src, "r:*") as t:\n' +
110
- ' t.extractall(dst)\n' +
282
+ ' total = 0\n' +
283
+ ' members = t.getmembers()\n' +
284
+ ' for m in members:\n' +
285
+ ' if m.issym() or m.islnk() or m.isdev() or m.isfifo():\n' +
286
+ ' raise ValueError(f"Refusing unsafe tar entry: {m.name}")\n' +
287
+ ' total += max(0, m.size)\n' +
288
+ ' if total > max_bytes:\n' +
289
+ ' raise ValueError("Archive exceeds 256 MB uncompressed safety limit")\n' +
290
+ ' safe_target(m.name)\n' +
291
+ ' t.extractall(dst, members=members)\n' +
111
292
  'else:\n' +
112
293
  ' raise ValueError("Unrecognized archive format")\n',
113
294
  source,
114
295
  dest
115
- ], { stdio: 'pipe' });
296
+ ], { stdio: 'pipe', timeout: 60_000, maxBuffer: 10 * 1024 * 1024, windowsHide: true });
116
297
  return { success: true, output: `Extracted successfully to ${dest} (via python3)` };
117
- } catch {
298
+ } catch (pyErr: any) {
299
+ const pyMsg = String(pyErr?.stderr || pyErr?.message || '');
300
+ if (/traversal|unsafe|symlink|256 MB/i.test(pyMsg)) {
301
+ return { success: false, error: `Refused unsafe archive extraction: ${pyMsg.trim()}` };
302
+ }
118
303
  // Fall through
119
304
  }
120
305
 
121
306
  // 5. Windows PowerShell fallback
122
307
  if (process.platform === 'win32') {
123
308
  try {
124
- const psScript = `Expand-Archive -Path '${source.replace(/'/g, "''")}' -DestinationPath '${dest.replace(/'/g, "''")}' -Force`;
125
- execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', psScript], { stdio: 'pipe' });
309
+ const psScript = `Expand-Archive -LiteralPath '${source.replace(/'/g, "''")}' -DestinationPath '${dest.replace(/'/g, "''")}' -Force`;
310
+ execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', psScript], {
311
+ stdio: 'pipe',
312
+ timeout: 60_000,
313
+ maxBuffer: 10 * 1024 * 1024,
314
+ windowsHide: true
315
+ });
126
316
  return { success: true, output: `Extracted successfully to ${dest} (via PowerShell)` };
127
317
  } catch (e: any) {
128
318
  return { success: false, error: `PowerShell extraction failed: ${e.message}` };
@@ -140,23 +330,39 @@ async function compressArchive(source: string, dest: string): Promise<ArchiveRes
140
330
  try {
141
331
  const archiver = await loadCapabilityPackage('archiver');
142
332
  if (typeof archiver === 'function') {
143
- return await new Promise<ArchiveResult>(async (resolve) => {
333
+ return await new Promise<ArchiveResult>((resolve) => {
334
+ let settled = false;
335
+ const settle = (res: ArchiveResult): void => {
336
+ if (settled) return;
337
+ settled = true;
338
+ resolve(res);
339
+ };
144
340
  const output = createWriteStream(dest);
145
- const format = dest.toLowerCase().endsWith('.tar') || dest.toLowerCase().endsWith('.tar.gz') ? 'tar' : 'zip';
146
- const archiveStream = archiver(format, { zlib: { level: 9 } });
341
+ const lowerDest = dest.toLowerCase();
342
+ const isTarGz = lowerDest.endsWith('.tar.gz') || lowerDest.endsWith('.tgz');
343
+ const format = lowerDest.endsWith('.tar') || isTarGz ? 'tar' : 'zip';
344
+ const archiveStream = archiver(format, format === 'tar' ? { gzip: isTarGz } : { zlib: { level: 9 } });
147
345
 
148
- output.on('close', () => resolve({ success: true, output: `Compressed ${archiveStream.pointer()} total bytes to ${dest}` }));
149
- archiveStream.on('error', (err: any) => resolve({ success: false, error: err.message }));
346
+ output.on('close', () => settle({ success: true, output: `Compressed ${archiveStream.pointer()} total bytes to ${dest}` }));
347
+ output.on('error', (err: any) => settle({ success: false, error: err?.message || String(err) }));
348
+ archiveStream.on('error', (err: any) => settle({ success: false, error: err?.message || String(err) }));
150
349
 
151
350
  archiveStream.pipe(output);
152
351
 
153
- const stat = statSync(source);
154
- if (stat.isDirectory()) {
155
- archiveStream.directory(source, false);
156
- } else {
157
- archiveStream.file(source, { name: path.basename(source) });
352
+ try {
353
+ const stat = statSync(source);
354
+ if (stat.isDirectory()) {
355
+ archiveStream.directory(source, false);
356
+ } else {
357
+ archiveStream.file(source, { name: path.basename(source) });
358
+ }
359
+ Promise.resolve(archiveStream.finalize()).catch((err: any) => {
360
+ settle({ success: false, error: err?.message || String(err) });
361
+ });
362
+ } catch (err: any) {
363
+ output.destroy();
364
+ settle({ success: false, error: err?.message || String(err) });
158
365
  }
159
- await archiveStream.finalize();
160
366
  });
161
367
  }
162
368
  } catch {
@@ -165,15 +371,17 @@ async function compressArchive(source: string, dest: string): Promise<ArchiveRes
165
371
 
166
372
  const isZip = dest.toLowerCase().endsWith('.zip');
167
373
  const isTar = /\.(tar|tar\.gz|tgz)$/i.test(dest);
374
+ const isTarGz = /\.(tar\.gz|tgz)$/i.test(dest);
168
375
  const stat = statSync(source);
376
+ const execOpts = { stdio: 'pipe' as const, timeout: 60_000, maxBuffer: 10 * 1024 * 1024, windowsHide: true };
169
377
 
170
378
  // 2. Native zip on macOS / Linux
171
379
  if (isZip) {
172
380
  try {
173
381
  if (stat.isDirectory()) {
174
- execFileSync('zip', ['-q', '-r', dest, '.'], { cwd: source, stdio: 'pipe' });
382
+ execFileSync('zip', ['-q', '-r', dest, '.'], { cwd: source, ...execOpts });
175
383
  } else {
176
- execFileSync('zip', ['-q', dest, path.basename(source)], { cwd: path.dirname(source), stdio: 'pipe' });
384
+ execFileSync('zip', ['-q', dest, '--', path.basename(source)], { cwd: path.dirname(source), ...execOpts });
177
385
  }
178
386
  return { success: true, output: `Compressed successfully to ${dest} (via zip)` };
179
387
  } catch {
@@ -184,10 +392,11 @@ async function compressArchive(source: string, dest: string): Promise<ArchiveRes
184
392
  // 3. Native tar on macOS / Linux
185
393
  if (isTar) {
186
394
  try {
395
+ const tarFlag = isTarGz ? '-czf' : '-cf';
187
396
  if (stat.isDirectory()) {
188
- execFileSync('tar', ['-czf', dest, '-C', source, '.'], { stdio: 'pipe' });
397
+ execFileSync('tar', [tarFlag, dest, '-C', source, '.'], execOpts);
189
398
  } else {
190
- execFileSync('tar', ['-czf', dest, '-C', path.dirname(source), path.basename(source)], { stdio: 'pipe' });
399
+ execFileSync('tar', [tarFlag, dest, '-C', path.dirname(source), '--', path.basename(source)], execOpts);
191
400
  }
192
401
  return { success: true, output: `Compressed successfully to ${dest} (via tar)` };
193
402
  } catch {
@@ -212,7 +421,7 @@ async function compressArchive(source: string, dest: string): Promise<ArchiveRes
212
421
  ' z.write(src, os.path.basename(src))\n',
213
422
  source,
214
423
  dest
215
- ], { stdio: 'pipe' });
424
+ ], execOpts);
216
425
  return { success: true, output: `Compressed successfully to ${dest} (via python3 zipfile)` };
217
426
  } catch (pyErr: any) {
218
427
  return { success: false, error: `Compression failed: ${pyErr?.message || String(pyErr)}` };
@@ -61,12 +61,15 @@ export const computerUse = {
61
61
  }
62
62
  },
63
63
  async execute(args = {}, context = {}) {
64
+ if (!args || typeof args !== 'object' || Array.isArray(args)) {
65
+ return { success: false, error: 'computer_use requires an arguments object.' };
66
+ }
64
67
  const screen = args.screenContext || { width: 1920, height: 1080, scaleFactor: 1 };
65
68
  const app = typeof args.app === 'string' ? args.app.trim() : '';
66
69
  let desktopActions = [];
67
70
  // Mode 1: Parse full model prediction from vision grounding engine
68
- if (args.prediction || args.action === 'execute_prediction') {
69
- const pred = args.prediction || '';
71
+ if (args.prediction !== undefined || args.action === 'execute_prediction') {
72
+ const pred = typeof args.prediction === 'string' ? args.prediction : '';
70
73
  if (!pred.trim()) {
71
74
  return { success: false, error: 'No prediction string provided for execute_prediction.' };
72
75
  }
@@ -108,7 +111,8 @@ export const computerUse = {
108
111
  const keyMap = {
109
112
  return: 36, enter: 36, tab: 48, space: 49, backspace: 51, escape: 53, esc: 53
110
113
  };
111
- const keyCode = keyMap[keyName.toLowerCase()];
114
+ const normalizedKey = keyName.toLowerCase();
115
+ const keyCode = Object.hasOwn(keyMap, normalizedKey) ? keyMap[normalizedKey] : undefined;
112
116
  if (keyCode !== undefined) {
113
117
  desktopActions.push({ verb: 'key', keyCode });
114
118
  }
@@ -76,14 +76,17 @@ export const computerUse = {
76
76
  },
77
77
 
78
78
  async execute(args: ComputerUseArgs = {}, context: any = {}): Promise<{ success: boolean; output?: string; error?: string; actions?: any[] }> {
79
+ if (!args || typeof args !== 'object' || Array.isArray(args)) {
80
+ return { success: false, error: 'computer_use requires an arguments object.' };
81
+ }
79
82
  const screen: ScreenContext = args.screenContext || { width: 1920, height: 1080, scaleFactor: 1 };
80
83
  const app = typeof args.app === 'string' ? args.app.trim() : '';
81
84
 
82
85
  let desktopActions: any[] = [];
83
86
 
84
87
  // Mode 1: Parse full model prediction from vision grounding engine
85
- if (args.prediction || args.action === 'execute_prediction') {
86
- const pred = args.prediction || '';
88
+ if (args.prediction !== undefined || args.action === 'execute_prediction') {
89
+ const pred = typeof args.prediction === 'string' ? args.prediction : '';
87
90
  if (!pred.trim()) {
88
91
  return { success: false, error: 'No prediction string provided for execute_prediction.' };
89
92
  }
@@ -116,7 +119,8 @@ export const computerUse = {
116
119
  const keyMap: Record<string, number> = {
117
120
  return: 36, enter: 36, tab: 48, space: 49, backspace: 51, escape: 53, esc: 53
118
121
  };
119
- const keyCode = keyMap[keyName.toLowerCase()];
122
+ const normalizedKey = keyName.toLowerCase();
123
+ const keyCode = Object.hasOwn(keyMap, normalizedKey) ? keyMap[normalizedKey] : undefined;
120
124
  if (keyCode !== undefined) {
121
125
  desktopActions.push({ verb: 'key', keyCode });
122
126
  } else if (/^[a-z0-9]$/i.test(keyName)) {
@@ -293,29 +293,34 @@ export const creativeApps = {
293
293
  },
294
294
  async execute(value, context = {}) {
295
295
  try {
296
- if (!value || typeof value !== 'object')
296
+ if (!value || typeof value !== 'object' || Array.isArray(value))
297
297
  throw new Error('Expected creative app arguments');
298
298
  const args = value;
299
+ const safeContext = context && typeof context === 'object' ? context : {};
300
+ const workspace = safeContext.parentLoop?.workspaceRoot?.trim()
301
+ || safeContext.workspaceRoot?.trim()
302
+ || safeContext.workspacePaths?.find((p) => typeof p === 'string' && p.trim().length > 0)?.trim()
303
+ || process.cwd();
299
304
  if (args.action === 'status')
300
305
  return { success: true, apps: await creativeAppStatus() };
301
306
  if (args.action === 'studio_edit')
302
- return await runStudioEdit(args, process.cwd(), context.signal);
307
+ return await runStudioEdit(args, workspace, safeContext.signal);
303
308
  if (args.action === 'blender_batch')
304
- return await runBlenderBatch(args, process.cwd(), context.signal);
309
+ return await runBlenderBatch(args, workspace, safeContext.signal);
305
310
  if (args.action === 'studio_pipeline')
306
- return await runStudioPipeline(args, process.cwd(), context.signal);
311
+ return await runStudioPipeline(args, workspace, safeContext.signal);
307
312
  if (args.action === 'live_bridge')
308
- return await runAdobeLiveBridge(args, process.cwd(), context.signal);
313
+ return await runAdobeLiveBridge(args, workspace, safeContext.signal);
309
314
  if (args.action === 'engine_bridge')
310
- return await runGameEngineBridge(args, process.cwd(), context.signal);
315
+ return await runGameEngineBridge(args, workspace, safeContext.signal);
311
316
  if (args.action === 'verify_bridge')
312
- return await verifyAllCreativeAndGameBridges(process.cwd());
317
+ return await verifyAllCreativeAndGameBridges(workspace);
313
318
  if (args.action === 'scaffold_uxp') {
314
319
  return await scaffoldCausyneUxpPlugin(typeof args.outputDir === 'string' && args.outputDir.trim()
315
320
  ? args.outputDir.trim()
316
321
  : typeof args.output === 'string' && args.output.trim()
317
322
  ? args.output.trim()
318
- : 'causyne-uxp-bridge', process.cwd(), { websocketPort: typeof args.websocketPort === 'number' ? args.websocketPort : undefined });
323
+ : 'causyne-uxp-bridge', workspace, { websocketPort: typeof args.websocketPort === 'number' ? args.websocketPort : undefined });
319
324
  }
320
325
  throw new Error('Unknown creative app action');
321
326
  }
@@ -298,17 +298,30 @@ export const creativeApps = {
298
298
  }, required: ['action'], additionalProperties: false
299
299
  }
300
300
  },
301
- async execute(value: unknown, context: { signal?: AbortSignal } = {}) {
301
+ async execute(
302
+ value: unknown,
303
+ context: {
304
+ signal?: AbortSignal;
305
+ workspaceRoot?: string;
306
+ workspacePaths?: string[];
307
+ parentLoop?: { workspaceRoot?: string };
308
+ } = {}
309
+ ) {
302
310
  try {
303
- if (!value || typeof value !== 'object') throw new Error('Expected creative app arguments');
311
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Expected creative app arguments');
304
312
  const args = value as Record<string, unknown>;
313
+ const safeContext = context && typeof context === 'object' ? context : {};
314
+ const workspace = safeContext.parentLoop?.workspaceRoot?.trim()
315
+ || safeContext.workspaceRoot?.trim()
316
+ || safeContext.workspacePaths?.find((p): p is string => typeof p === 'string' && p.trim().length > 0)?.trim()
317
+ || process.cwd();
305
318
  if (args.action === 'status') return { success: true, apps: await creativeAppStatus() };
306
- if (args.action === 'studio_edit') return await runStudioEdit(args, process.cwd(), context.signal);
307
- if (args.action === 'blender_batch') return await runBlenderBatch(args, process.cwd(), context.signal);
308
- if (args.action === 'studio_pipeline') return await runStudioPipeline(args, process.cwd(), context.signal);
309
- if (args.action === 'live_bridge') return await runAdobeLiveBridge(args, process.cwd(), context.signal);
310
- if (args.action === 'engine_bridge') return await runGameEngineBridge(args, process.cwd(), context.signal);
311
- if (args.action === 'verify_bridge') return await verifyAllCreativeAndGameBridges(process.cwd());
319
+ if (args.action === 'studio_edit') return await runStudioEdit(args, workspace, safeContext.signal);
320
+ if (args.action === 'blender_batch') return await runBlenderBatch(args, workspace, safeContext.signal);
321
+ if (args.action === 'studio_pipeline') return await runStudioPipeline(args, workspace, safeContext.signal);
322
+ if (args.action === 'live_bridge') return await runAdobeLiveBridge(args, workspace, safeContext.signal);
323
+ if (args.action === 'engine_bridge') return await runGameEngineBridge(args, workspace, safeContext.signal);
324
+ if (args.action === 'verify_bridge') return await verifyAllCreativeAndGameBridges(workspace);
312
325
  if (args.action === 'scaffold_uxp') {
313
326
  return await scaffoldCausyneUxpPlugin(
314
327
  typeof args.outputDir === 'string' && args.outputDir.trim()
@@ -316,7 +329,7 @@ export const creativeApps = {
316
329
  : typeof args.output === 'string' && args.output.trim()
317
330
  ? args.output.trim()
318
331
  : 'causyne-uxp-bridge',
319
- process.cwd(),
332
+ workspace,
320
333
  { websocketPort: typeof args.websocketPort === 'number' ? args.websocketPort : undefined }
321
334
  );
322
335
  }
@@ -170,26 +170,28 @@ export const deferredMcpSearch = {
170
170
  },
171
171
  async execute(args, context = {}) {
172
172
  try {
173
- const rawQueries = args.queries;
173
+ const safeArgs = args && typeof args === 'object' && !Array.isArray(args) ? args : {};
174
+ const safeContext = context && typeof context === 'object' ? context : {};
175
+ const rawQueries = safeArgs.queries;
174
176
  const joinedQueries = Array.isArray(rawQueries)
175
177
  ? rawQueries.map((item) => String(item ?? '').trim()).filter(Boolean).join(' ')
176
178
  : (typeof rawQueries === 'string' ? rawQueries : '');
177
- const rawQuery = Array.isArray(args.query)
178
- ? args.query.map((item) => String(item ?? '').trim()).filter(Boolean).join(' ')
179
- : args.query;
180
- const query = String(rawQuery ?? args.q ?? args.search ?? args.term ??
181
- args.regex ?? args.description ?? args.pattern ?? joinedQueries ?? '').trim();
179
+ const rawQuery = Array.isArray(safeArgs.query)
180
+ ? safeArgs.query.map((item) => String(item ?? '').trim()).filter(Boolean).join(' ')
181
+ : safeArgs.query;
182
+ const query = String(rawQuery ?? safeArgs.q ?? safeArgs.search ?? safeArgs.term ??
183
+ safeArgs.regex ?? safeArgs.description ?? safeArgs.pattern ?? joinedQueries ?? '').trim();
182
184
  if (query.length > MAX_TOOL_SEARCH_QUERY) {
183
185
  return { success: false, error: `Search query exceeds ${MAX_TOOL_SEARCH_QUERY} characters. Use a shorter capability description.` };
184
186
  }
185
- const requestedPack = args.pack ? String(args.pack).toLowerCase() : null;
186
- const definitions = context.parentLoop?.searchableTools
187
- ? await context.parentLoop.searchableTools() : await toolDefinitions();
187
+ const requestedPack = safeArgs.pack ? String(safeArgs.pack).toLowerCase() : null;
188
+ const definitions = safeContext.parentLoop?.searchableTools
189
+ ? await safeContext.parentLoop.searchableTools() : await toolDefinitions();
188
190
  const hints = new Map(buildToolsList(definitions).map((entry) => [entry.name, entry.hint]));
189
- if (Array.isArray(args.names) && args.names.length > 0) {
191
+ if (Array.isArray(safeArgs.names) && safeArgs.names.length > 0) {
190
192
  const available = new Map(definitions.map((definition) => [definition.name.toLowerCase(), definition.name]));
191
- const chosen = [...new Set(args.names.map((name) => available.get(String(name).toLowerCase())).filter((name) => Boolean(name)))];
192
- if (chosen.length !== new Set(args.names.map((name) => String(name).toLowerCase())).size) {
193
+ const chosen = [...new Set(safeArgs.names.map((name) => available.get(String(name).toLowerCase())).filter((name) => Boolean(name)))];
194
+ if (chosen.length !== new Set(safeArgs.names.map((name) => String(name).toLowerCase())).size) {
193
195
  return { success: false, error: 'One or more selected tools are unavailable under the current policy. Select exact names from the current catalog.' };
194
196
  }
195
197
  return { success: true, output: `Selected ${chosen.length} tool schemas for your next turn:\n${chosen.map((name) => `- ${name}: ${hints.get(name) || 'tool'}`).join('\n')}`, _unlock_tools: chosen };
@@ -199,7 +201,17 @@ export const deferredMcpSearch = {
199
201
  }
200
202
  // Whole-pack load. Cheaper than five searches when the agent already
201
203
  // knows it is starting a game or a media pipeline.
202
- if (requestedPack && requestedPack !== 'all' && Object.hasOwn(PACKS, requestedPack)) {
204
+ if (requestedPack === 'all') {
205
+ const allPackTools = definitions.filter(d => !isResidentTool(d.name));
206
+ return {
207
+ success: true,
208
+ output: `Loaded all capability packs (${allPackTools.length} tools). These are now callable:\n` +
209
+ allPackTools.map(d => `- ${d.name}: ${hints.get(d.name) || 'tool'}`).join('\n'),
210
+ _unlock_packs: [...PACK_NAMES],
211
+ _unlock_tools: allPackTools.map(d => d.name)
212
+ };
213
+ }
214
+ if (requestedPack && Object.hasOwn(PACKS, requestedPack)) {
203
215
  const packTools = definitions.filter(d => packForTool(d.name) === requestedPack);
204
216
  return {
205
217
  success: true,
@@ -209,7 +221,7 @@ export const deferredMcpSearch = {
209
221
  _unlock_tools: packTools.map(d => d.name)
210
222
  };
211
223
  }
212
- const limit = typeof args.limit === 'number' && Number.isInteger(args.limit) && args.limit > 0 ? Math.min(args.limit, 25) : 8;
224
+ const limit = typeof safeArgs.limit === 'number' && Number.isInteger(safeArgs.limit) && safeArgs.limit > 0 ? Math.min(safeArgs.limit, 25) : 8;
213
225
  const lower = query.toLowerCase();
214
226
  const terms = queryTerms(query);
215
227
  const pattern = buildPattern(query);