@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
@@ -56,11 +56,14 @@ async function physicalTarget(target: string): Promise<string> {
56
56
 
57
57
  async function checkScope(target: string, context?: FsWriteContext): Promise<void> {
58
58
  if (!context || context.grantAllAccess === true) return;
59
- const roots = Array.isArray(context.workspacePaths) && context.workspacePaths.length > 0
60
- ? context.workspacePaths
61
- : [context.parentLoop?.workspaceRoot, context.workspaceRoot].filter(
62
- (value): value is string => typeof value === 'string' && value.length > 0
63
- );
59
+ const configuredPaths = Array.isArray(context.workspacePaths)
60
+ ? context.workspacePaths.filter((value): value is string => typeof value === 'string' && value.trim().length > 0).map(value => value.trim())
61
+ : [];
62
+ const roots = configuredPaths.length > 0
63
+ ? configuredPaths
64
+ : [context.parentLoop?.workspaceRoot, context.workspaceRoot]
65
+ .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)
66
+ .map(value => value.trim());
64
67
  if (roots.length === 0) return;
65
68
  const physical = await physicalTarget(target);
66
69
  for (const root of roots) {
@@ -102,11 +105,18 @@ export const fsWrite = {
102
105
  if (typeof args.content !== 'string') {
103
106
  return { success: false, error: 'fs_write requires content as a string. Do not infer or invent missing file content.' };
104
107
  }
105
- if (args.path.endsWith('/') || args.path.endsWith('\\')) {
108
+ const trimmedPath = args.path.trim();
109
+ if (trimmedPath.endsWith('/') || trimmedPath.endsWith('\\')) {
106
110
  return { success: false, error: `Target ${args.path} ends in a directory separator. Add a filename such as index.html.` };
107
111
  }
108
112
 
109
- const target = path.resolve(expandHome(args.path.trim()));
113
+ const expandedPath = expandHome(trimmedPath);
114
+ const baseRoot = context?.parentLoop?.workspaceRoot?.trim()
115
+ || context?.workspaceRoot?.trim()
116
+ || context?.workspacePaths?.find((value): value is string => typeof value === 'string' && value.trim().length > 0)?.trim();
117
+ const target = path.isAbsolute(expandedPath)
118
+ ? path.resolve(expandedPath)
119
+ : path.resolve(baseRoot ? path.resolve(expandHome(baseRoot)) : process.cwd(), expandedPath);
110
120
  let temporary = '';
111
121
  try {
112
122
  await checkScope(target, context);
@@ -1,5 +1,17 @@
1
1
  import { causyneHome, resolveUserPath } from '../utils/paths.js';
2
+ import { assertPublicWebUrl } from '../browser/urlPolicy.js';
2
3
  import { validateToolArguments } from './argumentValidation.js';
4
+ function resolveApprovalHost(sandbox) {
5
+ if (typeof sandbox?.waitForApproval === 'function')
6
+ return sandbox;
7
+ if (typeof sandbox?.parentLoop?.waitForApproval === 'function')
8
+ return sandbox.parentLoop;
9
+ return undefined;
10
+ }
11
+ function buildMediaSignal(signal, timeoutMs = 120_000) {
12
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
13
+ return signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
14
+ }
3
15
  const errorMessage = (error) => error instanceof Error ? error.message : String(error);
4
16
  import fs from 'fs';
5
17
  import path from 'path';
@@ -19,12 +31,14 @@ function validateMagicNumbers(buffer) {
19
31
  return true; // PNG
20
32
  if (hex.startsWith('52494646'))
21
33
  return true; // WAV/RIFF
22
- if (hex.startsWith('494433'))
23
- return true; // MP3 (ID3)
24
- // MP4 video container check: box size (4 bytes) followed by box type 'ftyp' (66747970 in hex) or 'moov' or 'mdat'
34
+ if (hex.startsWith('494433') || hex.startsWith('FFFB') || hex.startsWith('FFFA') || hex.startsWith('FFF3') || hex.startsWith('FFF2') || hex.startsWith('FFE3'))
35
+ return true; // MP3 (ID3 or MPEG frame sync)
36
+ // MP4 video container check: valid ISO BMFF box size (4 bytes) followed by box type 'ftyp', 'moov', 'mdat', or 'free'
25
37
  if (buffer.length >= 8) {
38
+ const boxSize = buffer.readUInt32BE(0);
26
39
  const boxType = buffer.toString('ascii', 4, 8);
27
- if (['ftyp', 'moov', 'mdat', 'free'].includes(boxType))
40
+ const validBoxSize = boxSize === 0 || boxSize === 1 || (boxSize >= 8 && boxSize < 0x20000000);
41
+ if (validBoxSize && ['ftyp', 'moov', 'mdat', 'free'].includes(boxType))
28
42
  return true;
29
43
  }
30
44
  return false;
@@ -37,7 +51,7 @@ async function routeMultimediaRequest(args, config, sandbox, tokenTracker) {
37
51
  const { mediaType, prompt, targetProvider = 'auto', targetModel, durationSeconds = 5 } = args;
38
52
  // Auto-resolve provider based on available keys and media type
39
53
  let provider = targetProvider;
40
- let model = targetModel;
54
+ let model = targetModel || args.model;
41
55
  if (provider === 'auto') {
42
56
  if (mediaType === 'video_animation') {
43
57
  if (config.geminiApiKey || (config.provider === 'gemini' && config.apiKey)) {
@@ -77,19 +91,23 @@ async function routeMultimediaRequest(args, config, sandbox, tokenTracker) {
77
91
  if (provider === 'pollinations' || provider === 'local' || !['gemini', 'openai', 'qwen', 'muse'].includes(provider)) {
78
92
  return null;
79
93
  }
94
+ if (provider === 'qwen') {
95
+ return { success: false, code: 'MEDIA_PROVIDER_UNAVAILABLE', error: `No supported authenticated ${mediaType} endpoint is configured for ${provider}. No media artifact was produced.` };
96
+ }
80
97
  // Calculate estimated cost and equivalent tokens
81
98
  const quantity = mediaType === 'video_animation' ? durationSeconds : 1;
82
99
  const unitPrice = tokenTracker.getMediaPricing(provider, model || '', mediaType);
83
100
  const estimatedCost = unitPrice * quantity;
84
101
  const estimatedTokens = Math.round(estimatedCost / 0.000002);
85
102
  // Pre-Flight Consent Modal (`approval_request`) for Paid API Handoffs (unless in Mode C/Super Max and pre-approved)
86
- if (sandbox && typeof sandbox.waitForApproval === 'function') {
103
+ const approvalHost = resolveApprovalHost(sandbox);
104
+ if (approvalHost && typeof approvalHost.waitForApproval === 'function') {
87
105
  // The paid-media consent modal is skipped in Mode C (pre-approved) and in
88
106
  // hardened developer emulator mode (secret-gated — see devMode.js).
89
107
  if (!isDevEmulator(config) && config.autonomyMode !== 'C') {
90
108
  const approvalId = `media_${crypto.randomUUID()}`;
91
- if (typeof sandbox.emitEvent === 'function') {
92
- sandbox.emitEvent({
109
+ if (typeof approvalHost.emitEvent === 'function') {
110
+ approvalHost.emitEvent({
93
111
  type: 'approval_request',
94
112
  toolCallId: approvalId,
95
113
  tool: 'generate_media_via_api (Auto-Switch)',
@@ -104,7 +122,7 @@ async function routeMultimediaRequest(args, config, sandbox, tokenTracker) {
104
122
  risk: 'monetary_cost'
105
123
  });
106
124
  }
107
- const approved = await sandbox.waitForApproval(approvalId);
125
+ const approved = await approvalHost.waitForApproval(approvalId);
108
126
  if (!approved) {
109
127
  return { success: false, code: 'MEDIA_APPROVAL_DENIED', error: 'Paid media generation was declined. No media artifact was produced.' };
110
128
  }
@@ -124,13 +142,18 @@ async function routeMultimediaRequest(args, config, sandbox, tokenTracker) {
124
142
  let headers = { 'Content-Type': 'application/json' };
125
143
  let body = {};
126
144
  if (provider === 'gemini') {
145
+ model = model || (mediaType === 'video_animation' ? 'veo-2.0-generate-001' : 'imagen-3.0-generate-002');
146
+ if (!/^[A-Za-z0-9._-]+$/.test(model)) {
147
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'Invalid Gemini media model identifier.' };
148
+ }
149
+ const encodedModel = encodeURIComponent(model);
127
150
  headers['x-goog-api-key'] = apiKey;
128
151
  if (mediaType === 'video_animation') {
129
- targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict`;
152
+ targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${encodedModel}:predict`;
130
153
  body = { instances: [{ prompt }], parameters: { durationSeconds } };
131
154
  }
132
155
  else {
133
- targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict`;
156
+ targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${encodedModel}:predict`;
134
157
  body = { instances: [{ prompt }], parameters: { sampleCount: 1 } };
135
158
  }
136
159
  }
@@ -158,7 +181,7 @@ async function routeMultimediaRequest(args, config, sandbox, tokenTracker) {
158
181
  }
159
182
  if (!targetUrl || !apiKey)
160
183
  return { success: false, code: 'MEDIA_PROVIDER_UNAVAILABLE', error: `No supported authenticated ${mediaType} endpoint is configured for ${provider}. No media artifact was produced.` };
161
- const response = await fetch(targetUrl, { method: 'POST', headers, body: JSON.stringify(body), signal: sandbox?.signal || AbortSignal.timeout(120_000) });
184
+ const response = await fetch(targetUrl, { method: 'POST', headers, body: JSON.stringify(body), signal: buildMediaSignal(sandbox?.signal) });
162
185
  if (!response.ok)
163
186
  return { success: false, code: 'MEDIA_PROVIDER_ERROR', status: response.status, retryable: response.status === 429 || response.status >= 500, error: `Media provider ${provider} returned HTTP ${response.status}. No media artifact was produced.` };
164
187
  const data = await response.json();
@@ -171,8 +194,22 @@ async function routeMultimediaRequest(args, config, sandbox, tokenTracker) {
171
194
  }
172
195
  else if (data.url || (data.data && data.data[0]?.url)) {
173
196
  const mediaUrl = data.url || data.data[0].url;
174
- const mediaResp = await fetch(mediaUrl);
197
+ const verifiedUrl = await assertPublicWebUrl(mediaUrl);
198
+ if (verifiedUrl.protocol !== 'https:') {
199
+ return { success: false, code: 'INVALID_MEDIA_RESPONSE', error: `Provider ${provider} returned a non-HTTPS media download URL.` };
200
+ }
201
+ const mediaResp = await fetch(verifiedUrl, { redirect: 'error', signal: buildMediaSignal(sandbox?.signal) });
202
+ if (!mediaResp.ok) {
203
+ return { success: false, code: 'MEDIA_PROVIDER_ERROR', status: mediaResp.status, error: `Media download returned HTTP ${mediaResp.status}.` };
204
+ }
205
+ const declaredLen = Number(mediaResp.headers.get('content-length') ?? '0');
206
+ if (Number.isFinite(declaredLen) && declaredLen > 50 * 1024 * 1024) {
207
+ return { success: false, code: 'INVALID_MEDIA_RESPONSE', error: 'Media download exceeds 50 MB limit.' };
208
+ }
175
209
  const ab = await mediaResp.arrayBuffer();
210
+ if (ab.byteLength > 50 * 1024 * 1024) {
211
+ return { success: false, code: 'INVALID_MEDIA_RESPONSE', error: 'Media download exceeds 50 MB limit.' };
212
+ }
176
213
  buffer = Buffer.from(ab);
177
214
  }
178
215
  if (!buffer || !validateMagicNumbers(buffer))
@@ -218,15 +255,39 @@ export const generateMediaViaApi = {
218
255
  const pathPolicy = sandbox?.parentLoop?.sandbox || sandbox;
219
256
  if (!args.prompt.trim())
220
257
  return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'prompt must be a nonempty string' };
258
+ if (args.durationSeconds !== undefined && (!Number.isFinite(args.durationSeconds) || args.durationSeconds <= 0 || args.durationSeconds > 60)) {
259
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'durationSeconds must be a finite number between 0 and 60' };
260
+ }
261
+ if (args.width !== undefined && (!Number.isFinite(args.width) || args.width < 64 || args.width > 4096)) {
262
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'width must be between 64 and 4096' };
263
+ }
264
+ if (args.height !== undefined && (!Number.isFinite(args.height) || args.height < 64 || args.height > 4096)) {
265
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'height must be between 64 and 4096' };
266
+ }
221
267
  const { mediaType = 'image', prompt = '', width, height, model, voice, targetProvider, targetModel, durationSeconds } = args || {};
222
268
  const ext = mediaType === 'audio_tts' ? 'mp3' : mediaType === 'video_animation' ? 'mp4' : 'png';
223
269
  const rawOutputPath = typeof args?.outputPath === 'string' && args.outputPath.trim()
224
270
  ? args.outputPath.trim()
225
271
  : path.join(workspaceRoot, `generated_media_${crypto.randomUUID()}.${ext}`);
226
- const outputPath = rawOutputPath.startsWith('~') ? resolveUserPath(rawOutputPath) : path.resolve(workspaceRoot, rawOutputPath);
272
+ const isHomePath = rawOutputPath === '~' || rawOutputPath.startsWith('~/') || rawOutputPath.startsWith('~\\');
273
+ const outputPath = isHomePath ? resolveUserPath(rawOutputPath) : path.resolve(workspaceRoot, rawOutputPath);
227
274
  if (pathPolicy?.isPathAllowed && !pathPolicy.isPathAllowed(outputPath)) {
228
275
  return { success: false, error: `Path outside allowed workspace: ${outputPath}` };
229
276
  }
277
+ try {
278
+ const existingStat = fs.lstatSync(outputPath);
279
+ if (existingStat.isDirectory()) {
280
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: `outputPath is an existing directory: ${outputPath}` };
281
+ }
282
+ if (existingStat.isSymbolicLink() || !existingStat.isFile()) {
283
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: `Refusing to overwrite symlink or non-regular file: ${outputPath}` };
284
+ }
285
+ }
286
+ catch (statErr) {
287
+ if (statErr?.code !== 'ENOENT') {
288
+ return { success: false, error: errorMessage(statErr) };
289
+ }
290
+ }
230
291
  const outputDir = path.dirname(outputPath);
231
292
  if (!fs.existsSync(outputDir))
232
293
  fs.mkdirSync(outputDir, { recursive: true });
@@ -271,10 +332,11 @@ export const generateMediaViaApi = {
271
332
  };
272
333
  if (mediaType === 'video_animation')
273
334
  return { success: false, code: 'MEDIA_PROVIDER_UNAVAILABLE', error: 'No supported video endpoint is configured. No media artifact was produced.' };
274
- if (sandbox?.waitForApproval && !isDevEmulator(config) && config.autonomyMode !== 'C') {
335
+ const approvalHost = resolveApprovalHost(sandbox);
336
+ if (approvalHost?.waitForApproval && !isDevEmulator(config) && config.autonomyMode !== 'C') {
275
337
  const approvalId = `media_${crypto.randomUUID()}`;
276
- sandbox.emitEvent?.({ type: 'approval_request', toolCallId: approvalId, tool: 'generate_media_via_api', args: { mediaType, targetProvider: 'pollinations' }, risk: 'monetary_cost' });
277
- if (!await sandbox.waitForApproval(approvalId))
338
+ approvalHost.emitEvent?.({ type: 'approval_request', toolCallId: approvalId, tool: 'generate_media_via_api', args: { mediaType, targetProvider: 'pollinations' }, risk: 'monetary_cost' });
339
+ if (!await approvalHost.waitForApproval(approvalId))
278
340
  return { success: false, code: 'MEDIA_APPROVAL_DENIED', error: 'Media generation was declined. No artifact was produced.' };
279
341
  }
280
342
  const query = new URLSearchParams(mediaType === 'image'
@@ -285,7 +347,7 @@ export const generateMediaViaApi = {
285
347
  let attempts = 0;
286
348
  while (attempts < 3) {
287
349
  attempts++;
288
- const response = await fetch(targetUrl, { headers: { Authorization: `Bearer ${pollinationsKey}` }, signal: sandbox?.signal || AbortSignal.timeout(120_000) });
350
+ const response = await fetch(targetUrl, { headers: { Authorization: `Bearer ${pollinationsKey}` }, signal: buildMediaSignal(sandbox?.signal) });
289
351
  if (!response.ok) {
290
352
  const retryable = response.status === 429 || response.status >= 500;
291
353
  if (!retryable || attempts === 3)
@@ -314,7 +376,8 @@ export const generateMediaViaApi = {
314
376
  if (!buffer)
315
377
  return { success: false, error: 'Media generation did not produce a file.' };
316
378
  // Generation pricing is service-dependent; do not advertise this route as free.
317
- await tokenTracker.trackMediaUsage('pollinations', mediaType, 'flux', 1);
379
+ const trackedModel = model || targetModel || (mediaType === 'audio_tts' ? 'openai-audio' : 'flux');
380
+ await tokenTracker.trackMediaUsage('pollinations', mediaType, trackedModel, 1);
318
381
  // Write to cache and output
319
382
  fs.writeFileSync(cachedFile, buffer);
320
383
  fs.writeFileSync(outputPath, buffer);
@@ -1,8 +1,19 @@
1
1
  import { causyneHome, resolveUserPath } from '../utils/paths.js';
2
+ import { assertPublicWebUrl } from '../browser/urlPolicy.js';
2
3
  import { validateToolArguments } from './argumentValidation.js';
3
4
  import type { ParameterSchema } from './toolSelfRepair.js';
4
5
  interface MediaArgs { mediaType: 'image' | 'audio_tts' | 'video_animation'; prompt: string; outputPath?: string; width?: number; height?: number; model?: string; voice?: string; targetProvider?: string; targetModel?: string; durationSeconds?: number; }
5
- interface MediaContext { isPathAllowed?: (path: string) => boolean; waitForApproval?: (id: string) => Promise<boolean>; emitEvent?: (event: Record<string, unknown>) => void; signal?: AbortSignal; workspaceRoot?: string; workspacePaths?: string[]; parentLoop?: { workspaceRoot?: string; sandbox?: { isPathAllowed?: (path: string) => boolean } }; }
6
+ interface ApprovalHost { waitForApproval?: (id: string) => Promise<boolean>; emitEvent?: (event: Record<string, unknown>) => void; }
7
+ interface MediaContext extends ApprovalHost { isPathAllowed?: (path: string) => boolean; signal?: AbortSignal; workspaceRoot?: string; workspacePaths?: string[]; parentLoop?: ApprovalHost & { workspaceRoot?: string; sandbox?: { isPathAllowed?: (path: string) => boolean } }; }
8
+ function resolveApprovalHost(sandbox?: MediaContext): ApprovalHost | undefined {
9
+ if (typeof sandbox?.waitForApproval === 'function') return sandbox;
10
+ if (typeof sandbox?.parentLoop?.waitForApproval === 'function') return sandbox.parentLoop;
11
+ return undefined;
12
+ }
13
+ function buildMediaSignal(signal?: AbortSignal, timeoutMs = 120_000): AbortSignal {
14
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
15
+ return signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
16
+ }
6
17
  interface RouteResult { success?: boolean; buffer?: Buffer; provider?: string; model?: string; costUsd?: number; equivalentTokens?: number; fallbackToPollinations?: boolean; error?: string; [key: string]: unknown; }
7
18
  const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error);
8
19
  import fs from 'fs';
@@ -20,11 +31,13 @@ function validateMagicNumbers(buffer: Buffer): boolean {
20
31
  if (hex.startsWith('FFD8FF')) return true; // JPEG
21
32
  if (hex.startsWith('89504E47')) return true; // PNG
22
33
  if (hex.startsWith('52494646')) return true; // WAV/RIFF
23
- if (hex.startsWith('494433')) return true; // MP3 (ID3)
24
- // MP4 video container check: box size (4 bytes) followed by box type 'ftyp' (66747970 in hex) or 'moov' or 'mdat'
34
+ if (hex.startsWith('494433') || hex.startsWith('FFFB') || hex.startsWith('FFFA') || hex.startsWith('FFF3') || hex.startsWith('FFF2') || hex.startsWith('FFE3')) return true; // MP3 (ID3 or MPEG frame sync)
35
+ // MP4 video container check: valid ISO BMFF box size (4 bytes) followed by box type 'ftyp', 'moov', 'mdat', or 'free'
25
36
  if (buffer.length >= 8) {
37
+ const boxSize = buffer.readUInt32BE(0);
26
38
  const boxType = buffer.toString('ascii', 4, 8);
27
- if (['ftyp', 'moov', 'mdat', 'free'].includes(boxType)) return true;
39
+ const validBoxSize = boxSize === 0 || boxSize === 1 || (boxSize >= 8 && boxSize < 0x20000000);
40
+ if (validBoxSize && ['ftyp', 'moov', 'mdat', 'free'].includes(boxType)) return true;
28
41
  }
29
42
  return false;
30
43
  }
@@ -39,7 +52,7 @@ async function routeMultimediaRequest(args: MediaArgs, config: Record<string, an
39
52
 
40
53
  // Auto-resolve provider based on available keys and media type
41
54
  let provider = targetProvider;
42
- let model = targetModel;
55
+ let model = targetModel || args.model;
43
56
 
44
57
  if (provider === 'auto') {
45
58
  if (mediaType === 'video_animation') {
@@ -76,6 +89,9 @@ async function routeMultimediaRequest(args: MediaArgs, config: Record<string, an
76
89
  if (provider === 'pollinations' || provider === 'local' || !['gemini', 'openai', 'qwen', 'muse'].includes(provider)) {
77
90
  return null;
78
91
  }
92
+ if (provider === 'qwen') {
93
+ return { success: false, code: 'MEDIA_PROVIDER_UNAVAILABLE', error: `No supported authenticated ${mediaType} endpoint is configured for ${provider}. No media artifact was produced.` };
94
+ }
79
95
 
80
96
  // Calculate estimated cost and equivalent tokens
81
97
  const quantity = mediaType === 'video_animation' ? durationSeconds : 1;
@@ -84,13 +100,14 @@ async function routeMultimediaRequest(args: MediaArgs, config: Record<string, an
84
100
  const estimatedTokens = Math.round(estimatedCost / 0.000002);
85
101
 
86
102
  // Pre-Flight Consent Modal (`approval_request`) for Paid API Handoffs (unless in Mode C/Super Max and pre-approved)
87
- if (sandbox && typeof sandbox.waitForApproval === 'function') {
103
+ const approvalHost = resolveApprovalHost(sandbox);
104
+ if (approvalHost && typeof approvalHost.waitForApproval === 'function') {
88
105
  // The paid-media consent modal is skipped in Mode C (pre-approved) and in
89
106
  // hardened developer emulator mode (secret-gated — see devMode.js).
90
107
  if (!isDevEmulator(config) && config.autonomyMode !== 'C') {
91
108
  const approvalId = `media_${crypto.randomUUID()}`;
92
- if (typeof sandbox.emitEvent === 'function') {
93
- sandbox.emitEvent({
109
+ if (typeof approvalHost.emitEvent === 'function') {
110
+ approvalHost.emitEvent({
94
111
  type: 'approval_request',
95
112
  toolCallId: approvalId,
96
113
  tool: 'generate_media_via_api (Auto-Switch)',
@@ -106,7 +123,7 @@ async function routeMultimediaRequest(args: MediaArgs, config: Record<string, an
106
123
  });
107
124
  }
108
125
 
109
- const approved = await sandbox.waitForApproval(approvalId);
126
+ const approved = await approvalHost.waitForApproval(approvalId);
110
127
  if (!approved) {
111
128
  return { success: false, code: 'MEDIA_APPROVAL_DENIED', error: 'Paid media generation was declined. No media artifact was produced.' };
112
129
  }
@@ -129,12 +146,17 @@ async function routeMultimediaRequest(args: MediaArgs, config: Record<string, an
129
146
  let body: Record<string, unknown> = {};
130
147
 
131
148
  if (provider === 'gemini') {
149
+ model = model || (mediaType === 'video_animation' ? 'veo-2.0-generate-001' : 'imagen-3.0-generate-002');
150
+ if (!/^[A-Za-z0-9._-]+$/.test(model)) {
151
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'Invalid Gemini media model identifier.' };
152
+ }
153
+ const encodedModel = encodeURIComponent(model);
132
154
  headers['x-goog-api-key'] = apiKey;
133
155
  if (mediaType === 'video_animation') {
134
- targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict`;
156
+ targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${encodedModel}:predict`;
135
157
  body = { instances: [{ prompt }], parameters: { durationSeconds } };
136
158
  } else {
137
- targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict`;
159
+ targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${encodedModel}:predict`;
138
160
  body = { instances: [{ prompt }], parameters: { sampleCount: 1 } };
139
161
  }
140
162
  } else if (provider === 'muse') {
@@ -158,7 +180,7 @@ async function routeMultimediaRequest(args: MediaArgs, config: Record<string, an
158
180
  }
159
181
 
160
182
  if (!targetUrl || !apiKey) return { success: false, code: 'MEDIA_PROVIDER_UNAVAILABLE', error: `No supported authenticated ${mediaType} endpoint is configured for ${provider}. No media artifact was produced.` };
161
- const response = await fetch(targetUrl, { method: 'POST', headers, body: JSON.stringify(body), signal: sandbox?.signal || AbortSignal.timeout(120_000) });
183
+ const response = await fetch(targetUrl, { method: 'POST', headers, body: JSON.stringify(body), signal: buildMediaSignal(sandbox?.signal) });
162
184
  if (!response.ok) return { success: false, code: 'MEDIA_PROVIDER_ERROR', status: response.status, retryable: response.status === 429 || response.status >= 500, error: `Media provider ${provider} returned HTTP ${response.status}. No media artifact was produced.` };
163
185
 
164
186
  const data = await response.json() as { data?: Array<{ b64_json?: string; url?: string }>; predictions?: Array<{ bytesBase64Encoded?: string }>; url?: string };
@@ -171,8 +193,22 @@ async function routeMultimediaRequest(args: MediaArgs, config: Record<string, an
171
193
  buffer = Buffer.from(data.predictions[0]!.bytesBase64Encoded!, 'base64');
172
194
  } else if (data.url || (data.data && data.data[0]?.url)) {
173
195
  const mediaUrl = data.url || data.data![0]!.url!;
174
- const mediaResp = await fetch(mediaUrl);
196
+ const verifiedUrl = await assertPublicWebUrl(mediaUrl);
197
+ if (verifiedUrl.protocol !== 'https:') {
198
+ return { success: false, code: 'INVALID_MEDIA_RESPONSE', error: `Provider ${provider} returned a non-HTTPS media download URL.` };
199
+ }
200
+ const mediaResp = await fetch(verifiedUrl, { redirect: 'error', signal: buildMediaSignal(sandbox?.signal) });
201
+ if (!mediaResp.ok) {
202
+ return { success: false, code: 'MEDIA_PROVIDER_ERROR', status: mediaResp.status, error: `Media download returned HTTP ${mediaResp.status}.` };
203
+ }
204
+ const declaredLen = Number(mediaResp.headers.get('content-length') ?? '0');
205
+ if (Number.isFinite(declaredLen) && declaredLen > 50 * 1024 * 1024) {
206
+ return { success: false, code: 'INVALID_MEDIA_RESPONSE', error: 'Media download exceeds 50 MB limit.' };
207
+ }
175
208
  const ab = await mediaResp.arrayBuffer();
209
+ if (ab.byteLength > 50 * 1024 * 1024) {
210
+ return { success: false, code: 'INVALID_MEDIA_RESPONSE', error: 'Media download exceeds 50 MB limit.' };
211
+ }
176
212
  buffer = Buffer.from(ab);
177
213
  }
178
214
 
@@ -220,16 +256,39 @@ export const generateMediaViaApi: { schema: { name: string; description: string;
220
256
  const workspaceRoot = sandbox?.parentLoop?.workspaceRoot || sandbox?.workspaceRoot || sandbox?.workspacePaths?.[0] || process.cwd();
221
257
  const pathPolicy = sandbox?.parentLoop?.sandbox || sandbox;
222
258
  if (!args.prompt.trim()) return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'prompt must be a nonempty string' };
259
+ if (args.durationSeconds !== undefined && (!Number.isFinite(args.durationSeconds) || args.durationSeconds <= 0 || args.durationSeconds > 60)) {
260
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'durationSeconds must be a finite number between 0 and 60' };
261
+ }
262
+ if (args.width !== undefined && (!Number.isFinite(args.width) || args.width < 64 || args.width > 4096)) {
263
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'width must be between 64 and 4096' };
264
+ }
265
+ if (args.height !== undefined && (!Number.isFinite(args.height) || args.height < 64 || args.height > 4096)) {
266
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'height must be between 64 and 4096' };
267
+ }
223
268
  const { mediaType = 'image', prompt = '', width, height, model, voice, targetProvider, targetModel, durationSeconds } = args || {};
224
269
  const ext = mediaType === 'audio_tts' ? 'mp3' : mediaType === 'video_animation' ? 'mp4' : 'png';
225
270
  const rawOutputPath = typeof args?.outputPath === 'string' && args.outputPath.trim()
226
271
  ? args.outputPath.trim()
227
272
  : path.join(workspaceRoot, `generated_media_${crypto.randomUUID()}.${ext}`);
228
- const outputPath = rawOutputPath.startsWith('~') ? resolveUserPath(rawOutputPath) : path.resolve(workspaceRoot, rawOutputPath);
273
+ const isHomePath = rawOutputPath === '~' || rawOutputPath.startsWith('~/') || rawOutputPath.startsWith('~\\');
274
+ const outputPath = isHomePath ? resolveUserPath(rawOutputPath) : path.resolve(workspaceRoot, rawOutputPath);
229
275
 
230
276
  if (pathPolicy?.isPathAllowed && !pathPolicy.isPathAllowed(outputPath)) {
231
277
  return { success: false, error: `Path outside allowed workspace: ${outputPath}` };
232
278
  }
279
+ try {
280
+ const existingStat = fs.lstatSync(outputPath);
281
+ if (existingStat.isDirectory()) {
282
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: `outputPath is an existing directory: ${outputPath}` };
283
+ }
284
+ if (existingStat.isSymbolicLink() || !existingStat.isFile()) {
285
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: `Refusing to overwrite symlink or non-regular file: ${outputPath}` };
286
+ }
287
+ } catch (statErr: unknown) {
288
+ if ((statErr as NodeJS.ErrnoException)?.code !== 'ENOENT') {
289
+ return { success: false, error: errorMessage(statErr) };
290
+ }
291
+ }
233
292
 
234
293
  const outputDir = path.dirname(outputPath);
235
294
  if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
@@ -274,10 +333,11 @@ export const generateMediaViaApi: { schema: { name: string; description: string;
274
333
  nextAction: 'Use another already configured capability when it satisfies the request. If procedural drawing is an appropriate alternative, identify it accurately. If a generation service is essential, report the missing credentials without repeatedly retrying or asking for secrets in chat.'
275
334
  };
276
335
  if (mediaType === 'video_animation') return { success: false, code: 'MEDIA_PROVIDER_UNAVAILABLE', error: 'No supported video endpoint is configured. No media artifact was produced.' };
277
- if (sandbox?.waitForApproval && !isDevEmulator(config) && config.autonomyMode !== 'C') {
336
+ const approvalHost = resolveApprovalHost(sandbox);
337
+ if (approvalHost?.waitForApproval && !isDevEmulator(config) && config.autonomyMode !== 'C') {
278
338
  const approvalId = `media_${crypto.randomUUID()}`;
279
- sandbox.emitEvent?.({ type: 'approval_request', toolCallId: approvalId, tool: 'generate_media_via_api', args: { mediaType, targetProvider: 'pollinations' }, risk: 'monetary_cost' });
280
- if (!await sandbox.waitForApproval(approvalId)) return { success: false, code: 'MEDIA_APPROVAL_DENIED', error: 'Media generation was declined. No artifact was produced.' };
339
+ approvalHost.emitEvent?.({ type: 'approval_request', toolCallId: approvalId, tool: 'generate_media_via_api', args: { mediaType, targetProvider: 'pollinations' }, risk: 'monetary_cost' });
340
+ if (!await approvalHost.waitForApproval(approvalId)) return { success: false, code: 'MEDIA_APPROVAL_DENIED', error: 'Media generation was declined. No artifact was produced.' };
281
341
  }
282
342
  const query = new URLSearchParams(mediaType === 'image'
283
343
  ? { width: String(width || 1024), height: String(height || 1024), model: model || targetModel || 'flux', seed: String(Date.now()) }
@@ -287,7 +347,7 @@ export const generateMediaViaApi: { schema: { name: string; description: string;
287
347
  let attempts = 0;
288
348
  while (attempts < 3) {
289
349
  attempts++;
290
- const response = await fetch(targetUrl, { headers: { Authorization: `Bearer ${pollinationsKey}` }, signal: sandbox?.signal || AbortSignal.timeout(120_000) });
350
+ const response = await fetch(targetUrl, { headers: { Authorization: `Bearer ${pollinationsKey}` }, signal: buildMediaSignal(sandbox?.signal) });
291
351
  if (!response.ok) {
292
352
  const retryable = response.status === 429 || response.status >= 500;
293
353
  if (!retryable || attempts === 3) return {
@@ -311,7 +371,8 @@ export const generateMediaViaApi: { schema: { name: string; description: string;
311
371
  if (!buffer) return { success: false, error: 'Media generation did not produce a file.' };
312
372
 
313
373
  // Generation pricing is service-dependent; do not advertise this route as free.
314
- await tokenTracker.trackMediaUsage('pollinations', mediaType, 'flux', 1);
374
+ const trackedModel = model || targetModel || (mediaType === 'audio_tts' ? 'openai-audio' : 'flux');
375
+ await tokenTracker.trackMediaUsage('pollinations', mediaType, trackedModel, 1);
315
376
 
316
377
  // Write to cache and output
317
378
  fs.writeFileSync(cachedFile, buffer);
@@ -11,10 +11,28 @@
11
11
  *
12
12
  * Authorship: Strict TypeScript (Causyne Agent).
13
13
  */
14
+ import fs from 'node:fs';
14
15
  import os from 'node:os';
15
16
  import path from 'node:path';
16
17
  import { episodicStore } from '../memory/episodicStore.js';
17
18
  import { foldSourceFileOutline } from '../memory/symbolFolder.js';
19
+ const MAX_OUTLINE_FILE_BYTES = 2 * 1024 * 1024;
20
+ function safeOptionalInt(value) {
21
+ return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined;
22
+ }
23
+ function expandOutlineHome(raw) {
24
+ const trimmed = raw.trim();
25
+ if (trimmed === '~')
26
+ return os.homedir();
27
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
28
+ return path.join(os.homedir(), trimmed.slice(2));
29
+ }
30
+ return trimmed;
31
+ }
32
+ function isWithinOutlineRoot(root, candidate) {
33
+ const rel = path.relative(root, candidate);
34
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
35
+ }
18
36
  export const memoryRecall = {
19
37
  schema: {
20
38
  name: 'memory_recall',
@@ -77,21 +95,26 @@ export const memoryRecall = {
77
95
  const args = (rawArgs && typeof rawArgs === 'object' && !Array.isArray(rawArgs)
78
96
  ? rawArgs
79
97
  : {});
80
- const rawFileCandidate = String(args.filePath ?? args.path ?? args.file_path ?? args.filepath ?? args.target ?? '').trim();
98
+ const rawCandidateValue = args.filePath ?? args.path ?? args.file_path ?? args.filepath ?? args.target;
99
+ const rawFileCandidate = typeof rawCandidateValue === 'string' ? rawCandidateValue.trim() : '';
81
100
  const inferredAction = args.action
82
101
  ?? (rawFileCandidate ? 'outline' : undefined)
83
102
  ?? (args.anchorId !== undefined ? 'timeline' : undefined)
84
103
  ?? (Array.isArray(args.ids) && args.ids.length > 0 ? 'get' : undefined)
85
104
  ?? 'search';
86
105
  const action = inferredAction;
87
- const workspace = context.parentLoop?.workspaceRoot ?? context.workspaceRoot ?? process.cwd();
106
+ const workspace = context?.parentLoop?.workspaceRoot
107
+ ?? context?.workspaceRoot
108
+ ?? context?.workspacePaths?.find((p) => typeof p === 'string' && p.trim().length > 0)
109
+ ?? process.cwd();
110
+ const safeQuery = typeof args.query === 'string' ? args.query : undefined;
88
111
  try {
89
112
  if (action === 'search') {
90
113
  const res = episodicStore.searchIndex({
91
- query: args.query,
114
+ query: safeQuery,
92
115
  workspace,
93
116
  type: args.type,
94
- limit: args.limit,
117
+ limit: safeOptionalInt(args.limit),
95
118
  workspaceOnly: args.workspaceOnly
96
119
  });
97
120
  const formatted = res.results.length === 0
@@ -116,8 +139,8 @@ export const memoryRecall = {
116
139
  const windowResult = episodicStore.getTimelineWindow({
117
140
  anchorId: args.anchorId,
118
141
  workspace,
119
- depthBefore: args.depthBefore,
120
- depthAfter: args.depthAfter
142
+ depthBefore: safeOptionalInt(args.depthBefore),
143
+ depthAfter: safeOptionalInt(args.depthAfter)
121
144
  });
122
145
  if (!windowResult.anchor) {
123
146
  return {
@@ -173,13 +196,41 @@ export const memoryRecall = {
173
196
  if (!rawFileCandidate) {
174
197
  return { success: false, error: 'Missing required parameter "filePath" for action="outline".' };
175
198
  }
176
- const expanded = rawFileCandidate.startsWith('~/')
177
- ? path.join(os.homedir(), rawFileCandidate.slice(2))
178
- : rawFileCandidate;
199
+ const expanded = expandOutlineHome(rawFileCandidate);
179
200
  const targetPath = path.isAbsolute(expanded)
180
- ? expanded
201
+ ? path.resolve(expanded)
181
202
  : path.resolve(workspace, expanded);
182
- const outline = foldSourceFileOutline(targetPath, args.query);
203
+ const pathPolicy = context?.parentLoop?.sandbox ?? context;
204
+ if (context?.grantAllAccess !== true) {
205
+ if (typeof pathPolicy?.isPathAllowed === 'function' && !pathPolicy.isPathAllowed(targetPath)) {
206
+ return { success: false, error: `Path outside allowed workspace: ${targetPath}` };
207
+ }
208
+ const configuredRoots = Array.isArray(context?.workspacePaths)
209
+ ? context.workspacePaths.filter((p) => typeof p === 'string' && p.trim().length > 0)
210
+ : [context?.parentLoop?.workspaceRoot, context?.workspaceRoot].filter((p) => typeof p === 'string' && p.trim().length > 0);
211
+ if (configuredRoots.length > 0) {
212
+ const realTarget = fs.realpathSync(targetPath);
213
+ const allowed = configuredRoots.some((root) => {
214
+ try {
215
+ return isWithinOutlineRoot(fs.realpathSync(path.resolve(expandOutlineHome(root))), realTarget);
216
+ }
217
+ catch {
218
+ return false;
219
+ }
220
+ });
221
+ if (!allowed) {
222
+ return { success: false, error: `Path outside allowed workspace: ${targetPath}` };
223
+ }
224
+ }
225
+ }
226
+ const stat = fs.statSync(targetPath);
227
+ if (!stat.isFile()) {
228
+ return { success: false, error: `Outline target is not a regular file: ${targetPath}` };
229
+ }
230
+ if (stat.size > MAX_OUTLINE_FILE_BYTES) {
231
+ return { success: false, error: `File exceeds ${MAX_OUTLINE_FILE_BYTES / (1024 * 1024)} MB outline limit: ${targetPath}` };
232
+ }
233
+ const outline = foldSourceFileOutline(targetPath, safeQuery);
183
234
  return {
184
235
  success: true,
185
236
  action: 'outline',