@causyne/agent 1.20.11 → 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.
- package/LICENSE +1 -1
- package/docs/ARCHITECTURE.md +24 -1
- package/package.json +1 -1
- package/src/acp/client.js +9 -2
- package/src/acp/client.ts +11 -2
- package/src/acp/protocol.ts +9 -0
- package/src/agentLoop.js +504 -119
- package/src/agentLoop.ts +477 -121
- package/src/browser/browserRuntime.js +47 -0
- package/src/browser/browserRuntime.ts +45 -0
- package/src/browser/causyneBrowser.js +60 -31
- package/src/browser/causyneBrowser.ts +37 -12
- package/src/browser/workspacePreview.js +52 -0
- package/src/browser/workspacePreview.ts +49 -0
- package/src/core/planCache.js +5 -0
- package/src/core/planCache.ts +5 -0
- package/src/decisionPolicy.js +9 -0
- package/src/decisionPolicy.ts +8 -0
- package/src/historyPruner.js +251 -0
- package/src/historyPruner.ts +263 -0
- package/src/infra/atomicWriter.js +49 -0
- package/src/infra/atomicWriter.ts +63 -0
- package/src/infra/telemetry.js +38 -0
- package/src/infra/telemetry.ts +68 -0
- package/src/observer/coldObserver.js +12 -7
- package/src/observer/coldObserver.ts +12 -7
- package/src/observer/evidence.js +8 -2
- package/src/observer/evidence.ts +9 -2
- package/src/outputRecovery.js +36 -0
- package/src/outputRecovery.ts +33 -0
- package/src/providers/acp.js +114 -46
- package/src/providers/acp.ts +129 -46
- package/src/providers/antigravity.js +264 -82
- package/src/providers/antigravity.ts +273 -87
- package/src/providers/antigravityBridge.js +58 -0
- package/src/providers/antigravityBridge.ts +51 -0
- package/src/providers/base.d.ts +9 -0
- package/src/providers/budgetEnforcer.js +110 -0
- package/src/providers/budgetEnforcer.ts +122 -0
- package/src/providers/collaborationPolicy.js +6 -0
- package/src/providers/collaborationPolicy.ts +7 -0
- package/src/providers/loopGuard.js +84 -0
- package/src/providers/loopGuard.ts +105 -0
- package/src/providers/pi.js +19 -6
- package/src/providers/pi.ts +19 -7
- package/src/providers/toolContracts.js +36 -0
- package/src/providers/toolContracts.ts +48 -0
- package/src/session/sidechainEvents.js +49 -0
- package/src/session/sidechainEvents.ts +98 -0
- package/src/skillsManager.d.ts +1 -0
- package/src/smartToolsUse.js +123 -4
- package/src/smartToolsUse.ts +136 -4
- package/src/subagent/sidechainHarness.js +66 -0
- package/src/subagent/sidechainHarness.ts +91 -0
- package/src/taskContinuation.js +12 -0
- package/src/taskContinuation.ts +13 -0
- package/src/tokenTracker.js +406 -539
- package/src/tokenTracker.ts +569 -0
- package/src/toolPacks.d.ts +2 -0
- package/src/toolPacks.js +1 -1
- package/src/tools/argumentValidation.js +56 -0
- package/src/tools/argumentValidation.ts +50 -0
- package/src/tools/browserAutomator.js +2 -2
- package/src/tools/browserAutomator.ts +3 -2
- package/src/tools/deferredMcpSearch.js +188 -201
- package/src/tools/deferredMcpSearch.ts +250 -0
- package/src/tools/generateMediaViaApi.js +305 -331
- package/src/tools/generateMediaViaApi.ts +330 -0
- package/src/tools/historyPruner.js +5 -0
- package/src/tools/historyPruner.ts +5 -0
- package/src/tools/payloadSanitizer.js +92 -0
- package/src/tools/payloadSanitizer.ts +113 -0
- package/src/tools/registry.d.ts +1 -0
- package/src/tools/sysRun.js +47 -18
- package/src/tools/sysRun.ts +52 -20
- package/src/tools/toolOutputStore.js +180 -0
- package/src/tools/toolOutputStore.ts +209 -0
- package/src/tools/toolSelfRepair.js +26 -1
- package/src/tools/toolSelfRepair.ts +25 -1
- package/src/tui/chatRenderer.d.ts +1 -0
- package/src/tui/chatRenderer.js +4 -2
- package/src/tui/codeStreamRenderer.js +36 -8
- package/src/tui/codeStreamRenderer.ts +38 -8
- package/src/tui/stageSurface.js +1 -0
- package/src/tui/text.js +4 -1
- 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
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
if (
|
|
22
|
-
|
|
23
|
-
|
|
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
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
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
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
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
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
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
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
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
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
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
|
-
|
|
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
|
};
|