@causyne/agent 1.20.10 → 1.20.12

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 (88) hide show
  1. package/LICENSE +1 -1
  2. package/docs/ARCHITECTURE.md +24 -1
  3. package/package.json +1 -1
  4. package/src/acp/client.js +9 -2
  5. package/src/acp/client.ts +11 -2
  6. package/src/acp/protocol.ts +9 -0
  7. package/src/agentLoop.js +504 -119
  8. package/src/agentLoop.ts +477 -121
  9. package/src/browser/browserRuntime.js +47 -0
  10. package/src/browser/browserRuntime.ts +45 -0
  11. package/src/browser/causyneBrowser.js +60 -31
  12. package/src/browser/causyneBrowser.ts +37 -12
  13. package/src/browser/workspacePreview.js +52 -0
  14. package/src/browser/workspacePreview.ts +49 -0
  15. package/src/core/planCache.js +5 -0
  16. package/src/core/planCache.ts +5 -0
  17. package/src/decisionPolicy.js +9 -0
  18. package/src/decisionPolicy.ts +8 -0
  19. package/src/historyPruner.js +251 -0
  20. package/src/historyPruner.ts +263 -0
  21. package/src/infra/atomicWriter.js +49 -0
  22. package/src/infra/atomicWriter.ts +63 -0
  23. package/src/infra/telemetry.js +38 -0
  24. package/src/infra/telemetry.ts +68 -0
  25. package/src/observer/coldObserver.js +12 -7
  26. package/src/observer/coldObserver.ts +12 -7
  27. package/src/observer/evidence.js +8 -2
  28. package/src/observer/evidence.ts +9 -2
  29. package/src/outputRecovery.js +36 -0
  30. package/src/outputRecovery.ts +33 -0
  31. package/src/providers/acp.js +114 -46
  32. package/src/providers/acp.ts +129 -46
  33. package/src/providers/antigravity.js +262 -91
  34. package/src/providers/antigravity.ts +270 -99
  35. package/src/providers/antigravityBridge.js +58 -0
  36. package/src/providers/antigravityBridge.ts +51 -0
  37. package/src/providers/base.d.ts +9 -0
  38. package/src/providers/budgetEnforcer.js +110 -0
  39. package/src/providers/budgetEnforcer.ts +122 -0
  40. package/src/providers/collaborationPolicy.js +6 -0
  41. package/src/providers/collaborationPolicy.ts +7 -0
  42. package/src/providers/loopGuard.js +84 -0
  43. package/src/providers/loopGuard.ts +105 -0
  44. package/src/providers/pi.js +19 -6
  45. package/src/providers/pi.ts +19 -7
  46. package/src/providers/toolContracts.js +36 -0
  47. package/src/providers/toolContracts.ts +48 -0
  48. package/src/session/sidechainEvents.js +49 -0
  49. package/src/session/sidechainEvents.ts +98 -0
  50. package/src/skillsManager.d.ts +1 -0
  51. package/src/smartToolsUse.js +123 -4
  52. package/src/smartToolsUse.ts +136 -4
  53. package/src/stallGuard.js +3 -12
  54. package/src/stallGuard.ts +3 -12
  55. package/src/subagent/sidechainHarness.js +66 -0
  56. package/src/subagent/sidechainHarness.ts +91 -0
  57. package/src/taskContinuation.js +12 -0
  58. package/src/taskContinuation.ts +13 -0
  59. package/src/tokenTracker.js +406 -539
  60. package/src/tokenTracker.ts +569 -0
  61. package/src/toolPacks.d.ts +2 -0
  62. package/src/toolPacks.js +1 -1
  63. package/src/tools/argumentValidation.js +56 -0
  64. package/src/tools/argumentValidation.ts +50 -0
  65. package/src/tools/browserAutomator.js +2 -2
  66. package/src/tools/browserAutomator.ts +3 -2
  67. package/src/tools/deferredMcpSearch.js +188 -201
  68. package/src/tools/deferredMcpSearch.ts +250 -0
  69. package/src/tools/generateMediaViaApi.js +305 -331
  70. package/src/tools/generateMediaViaApi.ts +330 -0
  71. package/src/tools/historyPruner.js +5 -0
  72. package/src/tools/historyPruner.ts +5 -0
  73. package/src/tools/payloadSanitizer.js +92 -0
  74. package/src/tools/payloadSanitizer.ts +113 -0
  75. package/src/tools/registry.d.ts +1 -0
  76. package/src/tools/sysRun.js +47 -18
  77. package/src/tools/sysRun.ts +52 -20
  78. package/src/tools/toolOutputStore.js +180 -0
  79. package/src/tools/toolOutputStore.ts +209 -0
  80. package/src/tools/toolSelfRepair.js +26 -1
  81. package/src/tools/toolSelfRepair.ts +25 -1
  82. package/src/tui/chatRenderer.d.ts +1 -0
  83. package/src/tui/chatRenderer.js +4 -2
  84. package/src/tui/codeStreamRenderer.js +36 -8
  85. package/src/tui/codeStreamRenderer.ts +38 -8
  86. package/src/tui/stageSurface.js +1 -0
  87. package/src/tui/text.js +4 -1
  88. package/src/tokenTracker.d.ts +0 -1
@@ -1,358 +1,332 @@
1
+ import { causyneHome, resolveUserPath } from '../utils/paths.js';
2
+ import { validateToolArguments } from './argumentValidation.js';
3
+ const errorMessage = (error) => error instanceof Error ? error.message : String(error);
1
4
  import fs from 'fs';
2
5
  import path from 'path';
3
- import os from 'os';
4
6
  import crypto from 'crypto';
5
7
  import { loadConfig } from '../config.js';
6
8
  import { isDevEmulator } from '../devMode.js';
7
9
  import { TokenTracker } from '../tokenTracker.js';
8
-
9
- // Phase 5 & 6 AGI Upgrade: Validated Generation across Image, Audio, and Video (Magic Numbers)
10
+ // Reject HTML/JSON error payloads before saving media output.
10
11
  function validateMagicNumbers(buffer) {
11
- if (buffer.length < 4) return false;
12
- const hex = buffer.toString('hex', 0, 8).toUpperCase();
13
- // JPEG: FFD8FFE0, PNG: 89504E47, WAV: 52494646 (RIFF), MP3: 494433 (ID3)
14
- if (hex.startsWith('FFD8FF')) return true; // JPEG
15
- if (hex.startsWith('89504E47')) return true; // PNG
16
- if (hex.startsWith('52494646')) return true; // WAV/RIFF
17
- if (hex.startsWith('494433')) return true; // MP3 (ID3)
18
- // MP4 video container check: box size (4 bytes) followed by box type 'ftyp' (66747970 in hex) or 'moov' or 'mdat'
19
- if (buffer.length >= 8) {
20
- const boxType = buffer.toString('ascii', 4, 8);
21
- if (['ftyp', 'moov', 'mdat', 'free'].includes(boxType)) return true;
22
- }
23
- return false;
12
+ if (buffer.length < 4)
13
+ return false;
14
+ const hex = buffer.toString('hex', 0, 8).toUpperCase();
15
+ // JPEG: FFD8FFE0, PNG: 89504E47, WAV: 52494646 (RIFF), MP3: 494433 (ID3)
16
+ if (hex.startsWith('FFD8FF'))
17
+ return true; // JPEG
18
+ if (hex.startsWith('89504E47'))
19
+ return true; // PNG
20
+ if (hex.startsWith('52494646'))
21
+ 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'
25
+ if (buffer.length >= 8) {
26
+ const boxType = buffer.toString('ascii', 4, 8);
27
+ if (['ftyp', 'moov', 'mdat', 'free'].includes(boxType))
28
+ return true;
29
+ }
30
+ return false;
24
31
  }
25
-
26
- const CACHE_DIR = path.join(os.homedir(), '.causyne_media_cache');
27
-
32
+ const CACHE_DIR = path.join(causyneHome(), 'media-cache');
28
33
  /**
29
34
  * Helper to trigger execution path isolation for specialized API providers (Gemini Veo/Imagen, OpenAI DALL-E, Qwen Wan)
30
35
  */
31
36
  async function routeMultimediaRequest(args, config, sandbox, tokenTracker) {
32
- const { mediaType, prompt, targetProvider = 'auto', targetModel, durationSeconds = 5 } = args;
33
-
34
- // Auto-resolve provider based on available keys and media type
35
- let provider = targetProvider;
36
- let model = targetModel;
37
-
38
- if (provider === 'auto') {
39
- if (mediaType === 'video_animation') {
40
- if (config.geminiApiKey || (config.provider === 'gemini' && config.apiKey)) {
41
- provider = 'gemini';
42
- model = model || 'veo-2.0-generate-001';
43
- } else if (config.dashscopeApiKey || (config.provider === 'qwen' && config.apiKey)) {
44
- provider = 'qwen';
45
- model = model || 'wanx-v2.1-t2v-turbo';
46
- } else if (config.openaiApiKey || (config.provider === 'openai' && config.apiKey)) {
47
- provider = 'openai';
48
- model = model || 'sora-2';
49
- // Fallback to Sovereign 5-Stage Hierarchy when no video API keys exist
50
- return {
51
- success: true,
52
- mode: 'Fallback (Sovereign 5-Stage Hierarchy)',
53
- message: `No paid video generation API key (Gemini/Qwen/OpenAI) configured. Stage 2 Fallback: Please invoke 'check_system_specs' FIRST to verify if local hardware (RAM >= 8GB, Disk > 10GB) can run local video models via 'manage_local_ai_dependencies'. If local hardware is insufficient or declined, transition to Stage 4 (web_search + web_fetch for stock video assets) or Stage 5 (execute_procedural_media Mode A for HTML5 Canvas/Python animation).`
54
- };
55
- }
56
- } else if (mediaType === 'image') {
57
- // Muse Image first when the session is already on Meta Model API: same key,
58
- // same base URL, and $0.01 an image is the cheapest paid route here by a
59
- // wide margin. It is checked before the others so a Muse user is not sent
60
- // to a second vendor they never configured.
61
- if (config.museApiKey || ((config.provider === 'muse' || config.provider === 'meta') && config.apiKey)) {
62
- provider = 'muse';
63
- model = model || 'muse-image-1.0';
64
- } else if (config.geminiApiKey || (config.provider === 'gemini' && config.apiKey)) {
65
- provider = 'gemini';
66
- model = model || 'imagen-3.0-generate-002';
67
- } else if (config.openaiApiKey || (config.provider === 'openai' && config.apiKey)) {
68
- provider = 'openai';
69
- model = model || 'dall-e-3';
70
- } else {
71
- provider = 'pollinations';
72
- model = model || 'flux';
73
- }
37
+ const { mediaType, prompt, targetProvider = 'auto', targetModel, durationSeconds = 5 } = args;
38
+ // Auto-resolve provider based on available keys and media type
39
+ let provider = targetProvider;
40
+ let model = targetModel;
41
+ if (provider === 'auto') {
42
+ if (mediaType === 'video_animation') {
43
+ if (config.geminiApiKey || (config.provider === 'gemini' && config.apiKey)) {
44
+ provider = 'gemini';
45
+ model = model || 'veo-2.0-generate-001';
46
+ }
47
+ else if (config.dashscopeApiKey || (config.provider === 'qwen' && config.apiKey)) {
48
+ provider = 'qwen';
49
+ model = model || 'wanx-v2.1-t2v-turbo';
50
+ }
51
+ else if (config.openaiApiKey || (config.provider === 'openai' && config.apiKey)) {
52
+ provider = 'openai';
53
+ model = model || 'sora-2';
54
+ }
55
+ }
56
+ else if (mediaType === 'image') {
57
+ // Reuse an already configured provider before selecting another service.
58
+ if (config.museApiKey || ((config.provider === 'muse' || config.provider === 'meta') && config.apiKey)) {
59
+ provider = 'muse';
60
+ model = model || 'muse-image-1.0';
61
+ }
62
+ else if (config.geminiApiKey || (config.provider === 'gemini' && config.apiKey)) {
63
+ provider = 'gemini';
64
+ model = model || 'imagen-3.0-generate-002';
65
+ }
66
+ else if (config.openaiApiKey || (config.provider === 'openai' && config.apiKey)) {
67
+ provider = 'openai';
68
+ model = model || 'dall-e-3';
69
+ }
70
+ else {
71
+ provider = 'pollinations';
72
+ model = model || 'flux';
73
+ }
74
+ }
74
75
  }
75
- }
76
-
77
- // If routing to Pollinations or Free Mode, return null so standard execution continues
78
- if (provider === 'pollinations' || provider === 'local' || !['gemini', 'openai', 'qwen', 'muse'].includes(provider)) {
79
- return null;
80
- }
81
-
82
- // Calculate estimated cost and equivalent tokens
83
- const quantity = mediaType === 'video_animation' ? durationSeconds : 1;
84
- const unitPrice = tokenTracker.getMediaPricing(provider, model || '', mediaType);
85
- const estimatedCost = unitPrice * quantity;
86
- const estimatedTokens = Math.round(estimatedCost / 0.000002);
87
-
88
- // Pre-Flight Consent Modal (`approval_request`) for Paid API Handoffs (unless in Mode C/Super Max and pre-approved)
89
- if (sandbox && typeof sandbox.waitForApproval === 'function') {
90
- // The paid-media consent modal is skipped in Mode C (pre-approved) and in
91
- // hardened developer emulator mode (secret-gated — see devMode.js).
92
- if (!isDevEmulator(config) && config.autonomyMode !== 'C') {
93
- if (typeof sandbox.emitEvent === 'function') {
94
- sandbox.emitEvent({
95
- type: 'approval_request',
96
- toolCallId: `media_${Date.now()}`,
97
- tool: 'generate_media_via_api (Auto-Switch)',
98
- args: {
99
- targetProvider: provider.toUpperCase(),
100
- targetModel: model,
101
- mediaType,
102
- prompt,
103
- estimatedCostUsd: `$${estimatedCost.toFixed(2)}`,
104
- estimatedTokens: `~${estimatedTokens.toLocaleString()} Equivalent Tokens`
105
- },
106
- risk: 'monetary_cost'
107
- });
108
- }
109
-
110
- const approved = await sandbox.waitForApproval(`media_${Date.now()}`);
111
- if (!approved) {
112
- // User denied paid API -> Seamless routing across Sovereign 5-Stage Hierarchy
113
- if (mediaType === 'image') {
114
- return {
115
- fallbackToPollinations: true,
116
- message: `User denied Stage 1 paid API switch ($${estimatedCost.toFixed(2)}). Note: If local hardware allows and user prefers local processing, you may run 'check_system_specs' for Stage 2 (Local Stable Diffusion). Otherwise, auto-routing to free Pollinations.ai Mode D (Stage 3).`
117
- };
118
- } else {
119
- return {
120
- success: true,
121
- mode: 'Fallback (Stage 2 / Stage 4 / Stage 5)',
122
- message: `User denied Stage 1 paid API switch ($${estimatedCost.toFixed(2)}). Stage 2 Fallback: Please invoke 'open_source_tool_provisioner' (or 'check_system_specs') right now. It checks local hardware (RAM, Apple Silicon Metal/CUDA, disk space), discovers top open-source tools matching the intent (e.g., F5-TTS/Kokoro for voice cloning, Whisper for transcription), and provides compute specs with mandatory Human-In-The-Loop approval before installation.`
123
- };
76
+ // Pollinations uses its authenticated binary-response endpoint below.
77
+ if (provider === 'pollinations' || provider === 'local' || !['gemini', 'openai', 'qwen', 'muse'].includes(provider)) {
78
+ return null;
79
+ }
80
+ // Calculate estimated cost and equivalent tokens
81
+ const quantity = mediaType === 'video_animation' ? durationSeconds : 1;
82
+ const unitPrice = tokenTracker.getMediaPricing(provider, model || '', mediaType);
83
+ const estimatedCost = unitPrice * quantity;
84
+ const estimatedTokens = Math.round(estimatedCost / 0.000002);
85
+ // 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') {
87
+ // The paid-media consent modal is skipped in Mode C (pre-approved) and in
88
+ // hardened developer emulator mode (secret-gated — see devMode.js).
89
+ if (!isDevEmulator(config) && config.autonomyMode !== 'C') {
90
+ const approvalId = `media_${crypto.randomUUID()}`;
91
+ if (typeof sandbox.emitEvent === 'function') {
92
+ sandbox.emitEvent({
93
+ type: 'approval_request',
94
+ toolCallId: approvalId,
95
+ tool: 'generate_media_via_api (Auto-Switch)',
96
+ args: {
97
+ targetProvider: provider.toUpperCase(),
98
+ targetModel: model,
99
+ mediaType,
100
+ prompt,
101
+ estimatedCostUsd: `$${estimatedCost.toFixed(2)}`,
102
+ estimatedTokens: `~${estimatedTokens.toLocaleString()} Equivalent Tokens`
103
+ },
104
+ risk: 'monetary_cost'
105
+ });
106
+ }
107
+ const approved = await sandbox.waitForApproval(approvalId);
108
+ if (!approved) {
109
+ return { success: false, code: 'MEDIA_APPROVAL_DENIED', error: 'Paid media generation was declined. No media artifact was produced.' };
110
+ }
124
111
  }
125
- }
126
112
  }
127
- }
128
-
129
- // Enforce budget kill-switch and track usage
130
- const tracking = await tokenTracker.trackMediaUsage(provider, mediaType, model, quantity);
131
- if (!tracking.allowed) {
132
- return {
133
- success: false,
134
- error: tracking.reason || `Monetary budget exceeded for ${provider} media generation ($${estimatedCost.toFixed(2)}).`
135
- };
136
- }
137
-
138
- // Execute actual REST call to the specialized provider (Gemini / OpenAI / Qwen)
139
- let targetUrl = '';
140
- let apiKey = config[`${provider}ApiKey`] || config.apiKey;
141
- let headers = { 'Content-Type': 'application/json' };
142
- let body = {};
143
-
144
- if (provider === 'gemini') {
145
- if (mediaType === 'video_animation') {
146
- targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict?key=${apiKey}`;
147
- body = { instances: [{ prompt }], parameters: { durationSeconds } };
148
- } else {
149
- targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict?key=${apiKey}`;
150
- body = { instances: [{ prompt }], parameters: { sampleCount: 1 } };
113
+ // Check the estimated monetary ceiling before requesting generation. A failed
114
+ // request must not be recorded as successfully generated media.
115
+ const daily = await tokenTracker.getDailyUsage();
116
+ if (tokenTracker.budget.enabled && tokenTracker.budget.hardStop && tokenTracker.budget.maxCostUsd
117
+ && (daily.totalCostUsd || 0) + estimatedCost > tokenTracker.budget.maxCostUsd) {
118
+ return { success: false, code: 'MEDIA_BUDGET_EXCEEDED', error: 'The estimated media request would exceed the configured monetary budget.' };
151
119
  }
152
- } else if (provider === 'muse') {
153
- // Muse Image is the only model in the family that outputs images, and there
154
- // is no video model at all — a video request must fall through to the
155
- // sovereign hierarchy rather than be billed against an image endpoint.
156
- if (mediaType !== 'image') return null;
157
- targetUrl = 'https://api.meta.ai/v1/images/generations';
158
- headers['Authorization'] = `Bearer ${apiKey}`;
159
- body = { model: model || 'muse-image-1.0', prompt, n: 1, response_format: 'b64_json' };
160
- } else if (provider === 'openai') {
161
- if (mediaType === 'image') {
162
- targetUrl = 'https://api.openai.com/v1/images/generations';
163
- headers['Authorization'] = `Bearer ${apiKey}`;
164
- body = { model: model || 'dall-e-3', prompt, n: 1, response_format: 'b64_json' };
165
- } else {
166
- targetUrl = 'https://api.openai.com/v1/video/generations';
167
- headers['Authorization'] = `Bearer ${apiKey}`;
168
- body = { model: model || 'sora-2', prompt };
120
+ // Execute actual REST call to the specialized provider (Gemini / OpenAI / Qwen)
121
+ let targetUrl = '';
122
+ const activeProvider = config.provider === 'meta' ? 'muse' : config.provider;
123
+ const apiKey = config[`${provider}ApiKey`] || (provider === 'qwen' ? config.dashscopeApiKey : undefined) || (activeProvider === provider ? config.apiKey : undefined);
124
+ let headers = { 'Content-Type': 'application/json' };
125
+ let body = {};
126
+ if (provider === 'gemini') {
127
+ headers['x-goog-api-key'] = apiKey;
128
+ if (mediaType === 'video_animation') {
129
+ targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict`;
130
+ body = { instances: [{ prompt }], parameters: { durationSeconds } };
131
+ }
132
+ else {
133
+ targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict`;
134
+ body = { instances: [{ prompt }], parameters: { sampleCount: 1 } };
135
+ }
169
136
  }
170
- }
171
-
172
- const response = await fetch(targetUrl, { method: 'POST', headers, body: JSON.stringify(body) });
173
- if (!response.ok) {
174
- const errText = await response.text();
175
- // If API endpoint is unreachable or fails, fallback gracefully if image
176
- if (mediaType === 'image') {
177
- return {
178
- fallbackToPollinations: true,
179
- message: `Specialized provider (${provider}) returned error: ${response.status}. Falling back to free Pollinations.ai Mode D.`
180
- };
137
+ else if (provider === 'muse') {
138
+ // Muse Image is the only model in the family that outputs images, and there
139
+ // is no video model at all — a video request must fall through to the
140
+ // sovereign hierarchy rather than be billed against an image endpoint.
141
+ if (mediaType !== 'image')
142
+ return null;
143
+ targetUrl = 'https://api.meta.ai/v1/images/generations';
144
+ headers['Authorization'] = `Bearer ${apiKey}`;
145
+ body = { model: model || 'muse-image-1.0', prompt, n: 1, response_format: 'b64_json' };
181
146
  }
182
- throw new Error(`Specialized ${provider} API failure (${response.status}): ${errText}`);
183
- }
184
-
185
- const data = await response.json();
186
- let buffer = null;
187
-
188
-
189
- if ((provider === 'openai' || provider === 'muse') && data.data && data.data[0]?.b64_json) {
190
- buffer = Buffer.from(data.data[0].b64_json, 'base64');
191
- } else if (provider === 'gemini' && data.predictions && data.predictions[0]?.bytesBase64Encoded) {
192
- buffer = Buffer.from(data.predictions[0].bytesBase64Encoded, 'base64');
193
- } else if (data.url || (data.data && data.data[0]?.url)) {
194
- const mediaUrl = data.url || data.data[0].url;
195
- const mediaResp = await fetch(mediaUrl);
196
- const ab = await mediaResp.arrayBuffer();
197
- buffer = Buffer.from(ab);
198
- }
199
-
200
- if (!buffer || !validateMagicNumbers(buffer)) {
201
- if (mediaType === 'image') {
202
- return { fallbackToPollinations: true, message: `Invalid buffer from ${provider}. Falling back to Pollinations.ai.` };
147
+ else if (provider === 'openai') {
148
+ if (mediaType === 'image') {
149
+ targetUrl = 'https://api.openai.com/v1/images/generations';
150
+ headers['Authorization'] = `Bearer ${apiKey}`;
151
+ body = { model: model || 'dall-e-3', prompt, n: 1, response_format: 'b64_json' };
152
+ }
153
+ else {
154
+ targetUrl = 'https://api.openai.com/v1/video/generations';
155
+ headers['Authorization'] = `Bearer ${apiKey}`;
156
+ body = { model: model || 'sora-2', prompt };
157
+ }
203
158
  }
204
- throw new Error(`Failed to extract valid media buffer from ${provider} API response.`);
205
- }
206
-
207
- return {
208
- success: true,
209
- buffer,
210
- provider,
211
- model,
212
- costUsd: estimatedCost,
213
- equivalentTokens: estimatedTokens
214
- };
159
+ if (!targetUrl || !apiKey)
160
+ 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) });
162
+ if (!response.ok)
163
+ 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
+ const data = await response.json();
165
+ let buffer = null;
166
+ if ((provider === 'openai' || provider === 'muse') && data.data && data.data[0]?.b64_json) {
167
+ buffer = Buffer.from(data.data[0].b64_json, 'base64');
168
+ }
169
+ else if (provider === 'gemini' && data.predictions && data.predictions[0]?.bytesBase64Encoded) {
170
+ buffer = Buffer.from(data.predictions[0].bytesBase64Encoded, 'base64');
171
+ }
172
+ else if (data.url || (data.data && data.data[0]?.url)) {
173
+ const mediaUrl = data.url || data.data[0].url;
174
+ const mediaResp = await fetch(mediaUrl);
175
+ const ab = await mediaResp.arrayBuffer();
176
+ buffer = Buffer.from(ab);
177
+ }
178
+ if (!buffer || !validateMagicNumbers(buffer))
179
+ return { success: false, code: 'INVALID_MEDIA_RESPONSE', error: `Provider ${provider} did not return a supported media file. No artifact was produced.` };
180
+ await tokenTracker.trackMediaUsage(provider, mediaType, model || '', quantity);
181
+ return {
182
+ success: true,
183
+ buffer,
184
+ provider,
185
+ model: model || '',
186
+ costUsd: estimatedCost,
187
+ equivalentTokens: estimatedTokens
188
+ };
215
189
  }
216
-
217
190
  export const generateMediaViaApi = {
218
- schema: {
219
- name: 'generate_media_via_api',
220
- description: 'Mode D / Auto-Router: Generate validated images, audio TTS, or video animations. Supports automatic multi-provider handoff (Gemini Veo/Imagen, DALL-E 3, Qwen Wan) with interactive user approval and free fallback.',
221
- parameters: {
222
- type: 'object',
223
- properties: {
224
- mediaType: { type: 'string', enum: ['image', 'audio_tts', 'video_animation'] },
225
- prompt: { type: 'string' },
226
- outputPath: { type: 'string' },
227
- width: { type: 'number' },
228
- height: { type: 'number' },
229
- model: { type: 'string' },
230
- voice: { type: 'string' },
231
- targetProvider: { type: 'string', enum: ['auto', 'gemini', 'openai', 'qwen', 'pollinations'], description: 'Optional provider routing for specialized models.' },
232
- targetModel: { type: 'string', description: 'Optional exact model name (e.g. veo-2.0-generate-001, imagen-3.0-generate-002, dall-e-3).' },
233
- durationSeconds: { type: 'number', description: 'Duration in seconds for video animations (default 5).' }
234
- },
235
- required: ['mediaType', 'prompt', 'outputPath']
236
- }
237
- },
238
-
239
- execute: async (args, sandbox) => {
240
- try {
241
- const { mediaType, prompt, width, height, model, voice, targetProvider, targetModel, durationSeconds } = args;
242
- let outputPath = args.outputPath.replace(/^~\//, os.homedir() + '/');
243
- outputPath = path.resolve(outputPath);
244
-
245
- if (sandbox && sandbox.isPathAllowed && !sandbox.isPathAllowed(outputPath)) {
246
- return { success: false, error: `Path outside allowed workspace: ${outputPath}` };
247
- }
248
-
249
- const outputDir = path.dirname(outputPath);
250
- if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
251
- if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true });
252
-
253
- // Phase 5 AGI Upgrade: Caching Layer
254
- const promptHash = crypto.createHash('sha256').update(`${mediaType}_${prompt}_${model || targetModel}_${voice || targetProvider}`).digest('hex');
255
- const cachedFile = path.join(CACHE_DIR, promptHash);
256
- if (fs.existsSync(cachedFile)) {
257
- fs.copyFileSync(cachedFile, outputPath);
258
- return { success: true, message: `Cache Hit: Loaded instantly from local AI cache. Saved to ${outputPath}`, mode: 'D / Router (Cached)' };
259
- }
260
-
261
- const config = loadConfig();
262
- const tokenTracker = new TokenTracker();
263
-
264
- // Attempt specialized AGI Auto-Routing first
265
- const routeResult = await routeMultimediaRequest(args, config, sandbox, tokenTracker);
266
- if (routeResult) {
267
- if (routeResult.fallbackToPollinations !== true) {
268
- if (!routeResult.buffer && routeResult.success) {
269
- // Handled fallback message (e.g. Mode A recommendation)
270
- return routeResult;
271
- }
272
- if (routeResult.buffer) {
273
- fs.writeFileSync(cachedFile, routeResult.buffer);
274
- fs.writeFileSync(outputPath, routeResult.buffer);
191
+ schema: {
192
+ name: 'generate_media_via_api',
193
+ description: 'Mode D / Auto-Router: Generate validated images, audio TTS, or video animations. Supports automatic multi-provider handoff (Gemini Veo/Imagen, DALL-E 3, Qwen Wan) with interactive user approval and configured provider routing. No artifact is produced when authentication or funding is unavailable.',
194
+ parameters: {
195
+ type: 'object',
196
+ properties: {
197
+ mediaType: { type: 'string', enum: ['image', 'audio_tts', 'video_animation'] },
198
+ prompt: { type: 'string' },
199
+ outputPath: { type: 'string', description: 'Destination in the selected workspace. Omit to use a unique generated filename there.' },
200
+ width: { type: 'number' },
201
+ height: { type: 'number' },
202
+ model: { type: 'string' },
203
+ voice: { type: 'string' },
204
+ targetProvider: { type: 'string', enum: ['auto', 'gemini', 'openai', 'qwen', 'pollinations'], description: 'Optional provider routing for specialized models.' },
205
+ targetModel: { type: 'string', description: 'Optional exact model name (e.g. veo-2.0-generate-001, imagen-3.0-generate-002, dall-e-3).' },
206
+ durationSeconds: { type: 'number', description: 'Duration in seconds for video animations (default 5).' }
207
+ },
208
+ required: ['mediaType', 'prompt']
209
+ }
210
+ },
211
+ execute: async (input, sandbox) => {
212
+ try {
213
+ const issues = validateToolArguments(input, generateMediaViaApi.schema.parameters);
214
+ if (issues.length)
215
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: issues.join('; '), expectedSchema: generateMediaViaApi.schema.parameters };
216
+ const args = input;
217
+ const workspaceRoot = sandbox?.parentLoop?.workspaceRoot || sandbox?.workspaceRoot || sandbox?.workspacePaths?.[0] || process.cwd();
218
+ const pathPolicy = sandbox?.parentLoop?.sandbox || sandbox;
219
+ if (!args.prompt.trim())
220
+ return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'prompt must be a nonempty string' };
221
+ const { mediaType = 'image', prompt = '', width, height, model, voice, targetProvider, targetModel, durationSeconds } = args || {};
222
+ const ext = mediaType === 'audio_tts' ? 'mp3' : mediaType === 'video_animation' ? 'mp4' : 'png';
223
+ const rawOutputPath = typeof args?.outputPath === 'string' && args.outputPath.trim()
224
+ ? args.outputPath.trim()
225
+ : path.join(workspaceRoot, `generated_media_${crypto.randomUUID()}.${ext}`);
226
+ const outputPath = rawOutputPath.startsWith('~') ? resolveUserPath(rawOutputPath) : path.resolve(workspaceRoot, rawOutputPath);
227
+ if (pathPolicy?.isPathAllowed && !pathPolicy.isPathAllowed(outputPath)) {
228
+ return { success: false, error: `Path outside allowed workspace: ${outputPath}` };
229
+ }
230
+ const outputDir = path.dirname(outputPath);
231
+ if (!fs.existsSync(outputDir))
232
+ fs.mkdirSync(outputDir, { recursive: true });
233
+ if (!fs.existsSync(CACHE_DIR))
234
+ fs.mkdirSync(CACHE_DIR, { recursive: true });
235
+ // Cache complete media responses.
236
+ const promptHash = crypto.createHash('sha256').update(JSON.stringify(args)).digest('hex');
237
+ const cachedFile = path.join(CACHE_DIR, promptHash);
238
+ if (fs.existsSync(cachedFile) && validateMagicNumbers(fs.readFileSync(cachedFile))) {
239
+ fs.copyFileSync(cachedFile, outputPath);
240
+ return {
241
+ success: true,
242
+ message: `Cache Hit: Loaded instantly from local AI cache. Saved to ${outputPath}`,
243
+ sizeBytes: fs.statSync(outputPath).size,
244
+ mode: 'D / Router (Cached)'
245
+ };
246
+ }
247
+ const config = loadConfig();
248
+ const tokenTracker = new TokenTracker();
249
+ // Use the configured media provider first.
250
+ const routeResult = await routeMultimediaRequest(args, config, sandbox, tokenTracker);
251
+ if (routeResult) {
252
+ if (routeResult.success !== true || !routeResult.buffer)
253
+ return { ...routeResult, success: false };
254
+ fs.writeFileSync(cachedFile, routeResult.buffer);
255
+ fs.writeFileSync(outputPath, routeResult.buffer);
256
+ return {
257
+ success: true,
258
+ message: `Media saved via ${String(routeResult.provider).toUpperCase()} (${routeResult.model}) to ${outputPath}. Estimated cost: $${(routeResult.costUsd || 0).toFixed(2)}.`,
259
+ sizeBytes: routeResult.buffer.length,
260
+ mode: `API (${String(routeResult.provider).toUpperCase()})`
261
+ };
262
+ }
263
+ // Pollinations generation requires user-configured credentials. Missing keys
264
+ // are a configuration blocker, not a reason to retry anonymous requests.
265
+ const pollinationsKey = config.pollinationsApiKey || process.env.POLLINATIONS_API_KEY;
266
+ if (!pollinationsKey)
267
+ return {
268
+ success: false, code: 'MEDIA_AUTH_REQUIRED', retryable: false,
269
+ error: 'Image/audio generation requires a configured media provider key. The anonymous Pollinations fallback is unavailable. No media artifact was produced.',
270
+ 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.'
271
+ };
272
+ if (mediaType === 'video_animation')
273
+ 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') {
275
+ 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))
278
+ return { success: false, code: 'MEDIA_APPROVAL_DENIED', error: 'Media generation was declined. No artifact was produced.' };
279
+ }
280
+ const query = new URLSearchParams(mediaType === 'image'
281
+ ? { width: String(width || 1024), height: String(height || 1024), model: model || targetModel || 'flux', seed: String(Date.now()) }
282
+ : { voice: voice || 'nova', model: model || targetModel || 'openai-audio' });
283
+ const targetUrl = `https://gen.pollinations.ai/${mediaType === 'image' ? 'image' : 'audio'}/${encodeURIComponent(prompt)}?${query}`;
284
+ let buffer = null;
285
+ let attempts = 0;
286
+ while (attempts < 3) {
287
+ attempts++;
288
+ const response = await fetch(targetUrl, { headers: { Authorization: `Bearer ${pollinationsKey}` }, signal: sandbox?.signal || AbortSignal.timeout(120_000) });
289
+ if (!response.ok) {
290
+ const retryable = response.status === 429 || response.status >= 500;
291
+ if (!retryable || attempts === 3)
292
+ return {
293
+ success: false, code: 'MEDIA_PROVIDER_ERROR', status: response.status, attempts, retryable,
294
+ error: `Pollinations returned HTTP ${response.status}. No media artifact was produced.`,
295
+ nextAction: [401, 402, 403].includes(response.status) ? 'The user must check provider authentication, permissions, or balance before retrying.' : 'Check provider availability before retrying.'
296
+ };
297
+ await new Promise((resolve, reject) => {
298
+ const signal = sandbox?.signal;
299
+ const abort = () => { clearTimeout(timer); reject(new Error('Media generation aborted')); };
300
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, attempts * 1000);
301
+ if (signal?.aborted)
302
+ abort();
303
+ else
304
+ signal?.addEventListener('abort', abort, { once: true });
305
+ });
306
+ continue;
307
+ }
308
+ const candidate = Buffer.from(await response.arrayBuffer());
309
+ if (!validateMagicNumbers(candidate))
310
+ return { success: false, code: 'INVALID_MEDIA_RESPONSE', attempts, error: 'Provider response is not a supported media file. No artifact was produced.' };
311
+ buffer = candidate;
312
+ break;
313
+ }
314
+ if (!buffer)
315
+ return { success: false, error: 'Media generation did not produce a file.' };
316
+ // Generation pricing is service-dependent; do not advertise this route as free.
317
+ await tokenTracker.trackMediaUsage('pollinations', mediaType, 'flux', 1);
318
+ // Write to cache and output
319
+ fs.writeFileSync(cachedFile, buffer);
320
+ fs.writeFileSync(outputPath, buffer);
275
321
  return {
276
- success: true,
277
- message: `Media generated and validated via ${routeResult.provider.toUpperCase()} (${routeResult.model}). Cost: $${routeResult.costUsd.toFixed(2)} (~${routeResult.equivalentTokens} Equivalent Tokens). Saved to ${outputPath}`,
278
- sizeBytes: routeResult.buffer.length,
279
- mode: `Auto-Switch (${routeResult.provider.toUpperCase()})`
322
+ success: true,
323
+ message: `Media generated, validated, and cached successfully via Pollinations Mode D. Saved to ${outputPath}`,
324
+ sizeBytes: buffer.length,
325
+ mode: 'D (Validated API)'
280
326
  };
281
- }
282
- if (routeResult.error) return routeResult;
283
327
  }
284
- // If routeResult.fallbackToPollinations is true, we proceed right into Pollinations below!
285
- }
286
-
287
- // Default / Fallback: Pollinations.ai Mode D
288
- let targetUrl = '';
289
- let fetchOptions = {};
290
-
291
- if (mediaType === 'image') {
292
- const imgWidth = width || 1024;
293
- const imgHeight = height || 1024;
294
- const imgModel = model || 'flux';
295
- targetUrl = `https://image.pollinations.ai/prompt/${encodeURIComponent(prompt)}?width=${imgWidth}&height=${imgHeight}&model=${imgModel}&nologo=true&seed=${Date.now()}`;
296
- } else if (mediaType === 'audio_tts') {
297
- targetUrl = `https://api.pollinations.ai/tts?text=${encodeURIComponent(prompt)}&voice=${voice || 'nova'}`;
298
- } else {
299
- // Fallback across Sovereign 5-Stage Hierarchy when video_animation/music is routed to Pollinations
300
- return {
301
- success: true,
302
- mode: 'Fallback (Stage 2 / Stage 4 / Stage 5)',
303
- message: `Pollinations.ai (Stage 3) does not natively generate video animations or instrumental music directly. Stage 2 Fallback: Please invoke 'check_system_specs' right now to verify if local hardware (RAM >= 8GB) can run local models via 'manage_local_ai_dependencies'. If local hardware is insufficient or declined, transition to Stage 4 (web_search + web_fetch for stock video/music assets) or Stage 5 (execute_procedural_media Mode A for HTML5 Canvas/Python animation or WAV audio).`
304
- };
305
- }
306
-
307
- // Phase 5 AGI Upgrade: Auto-Retry Loop (3 retries, exponential backoff)
308
- let buffer = null;
309
- let attempts = 0;
310
- let lastError = '';
311
-
312
- while (attempts < 3) {
313
- attempts++;
314
- try {
315
- const response = await fetch(targetUrl, fetchOptions);
316
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
317
-
318
- const arrayBuffer = await response.arrayBuffer();
319
- buffer = Buffer.from(arrayBuffer);
320
-
321
- // Phase 5 AGI Upgrade: Magic Number Verification
322
- if (!validateMagicNumbers(buffer)) {
323
- throw new Error(`Invalid Magic Numbers (Corrupted/Unsupported format returned). Length: ${buffer.length}`);
324
- }
325
- break; // Success
326
- } catch (e) {
327
- lastError = e.message;
328
- if (attempts < 3) {
329
- await new Promise(res => setTimeout(res, attempts * 2000)); // Exponential backoff 2s, 4s
330
- }
328
+ catch (err) {
329
+ return { success: false, error: errorMessage(err) };
331
330
  }
332
- }
333
-
334
- if (!buffer) {
335
- return {
336
- success: false,
337
- error: `Pollinations API (Stage 3) failed after 3 attempts. Last error: ${lastError}. Sovereign Hierarchy Fallback: Please transition to Stage 4 (web_search + web_fetch to locate matching royalty-free assets online) or Stage 5 (execute_procedural_media Mode A to generate procedurally from scratch).`
338
- };
339
- }
340
-
341
- // Track free Mode D usage in Equivalent Units
342
- await tokenTracker.trackMediaUsage('pollinations', mediaType, 'flux', 1);
343
-
344
- // Write to cache and output
345
- fs.writeFileSync(cachedFile, buffer);
346
- fs.writeFileSync(outputPath, buffer);
347
-
348
- return {
349
- success: true,
350
- message: `Media generated, validated, and cached successfully via Pollinations Mode D. Saved to ${outputPath}`,
351
- sizeBytes: buffer.length,
352
- mode: 'D (Validated API)'
353
- };
354
- } catch (err) {
355
- return { success: false, error: err.message };
356
331
  }
357
- }
358
332
  };