@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.
Files changed (86) 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 +264 -82
  34. package/src/providers/antigravity.ts +273 -87
  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/subagent/sidechainHarness.js +66 -0
  54. package/src/subagent/sidechainHarness.ts +91 -0
  55. package/src/taskContinuation.js +12 -0
  56. package/src/taskContinuation.ts +13 -0
  57. package/src/tokenTracker.js +406 -539
  58. package/src/tokenTracker.ts +569 -0
  59. package/src/toolPacks.d.ts +2 -0
  60. package/src/toolPacks.js +1 -1
  61. package/src/tools/argumentValidation.js +56 -0
  62. package/src/tools/argumentValidation.ts +50 -0
  63. package/src/tools/browserAutomator.js +2 -2
  64. package/src/tools/browserAutomator.ts +3 -2
  65. package/src/tools/deferredMcpSearch.js +188 -201
  66. package/src/tools/deferredMcpSearch.ts +250 -0
  67. package/src/tools/generateMediaViaApi.js +305 -331
  68. package/src/tools/generateMediaViaApi.ts +330 -0
  69. package/src/tools/historyPruner.js +5 -0
  70. package/src/tools/historyPruner.ts +5 -0
  71. package/src/tools/payloadSanitizer.js +92 -0
  72. package/src/tools/payloadSanitizer.ts +113 -0
  73. package/src/tools/registry.d.ts +1 -0
  74. package/src/tools/sysRun.js +47 -18
  75. package/src/tools/sysRun.ts +52 -20
  76. package/src/tools/toolOutputStore.js +180 -0
  77. package/src/tools/toolOutputStore.ts +209 -0
  78. package/src/tools/toolSelfRepair.js +26 -1
  79. package/src/tools/toolSelfRepair.ts +25 -1
  80. package/src/tui/chatRenderer.d.ts +1 -0
  81. package/src/tui/chatRenderer.js +4 -2
  82. package/src/tui/codeStreamRenderer.js +36 -8
  83. package/src/tui/codeStreamRenderer.ts +38 -8
  84. package/src/tui/stageSurface.js +1 -0
  85. package/src/tui/text.js +4 -1
  86. package/src/tokenTracker.d.ts +0 -1
@@ -0,0 +1,330 @@
1
+ import { causyneHome, resolveUserPath } from '../utils/paths.js';
2
+ import { validateToolArguments } from './argumentValidation.js';
3
+ import type { ParameterSchema } from './toolSelfRepair.js';
4
+ 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 RouteResult { success?: boolean; buffer?: Buffer; provider?: string; model?: string; costUsd?: number; equivalentTokens?: number; fallbackToPollinations?: boolean; error?: string; [key: string]: unknown; }
7
+ const errorMessage = (error: unknown): string => error instanceof Error ? error.message : String(error);
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+ import crypto from 'crypto';
11
+ import { loadConfig } from '../config.js';
12
+ import { isDevEmulator } from '../devMode.js';
13
+ import { TokenTracker } from '../tokenTracker.js';
14
+
15
+ // Reject HTML/JSON error payloads before saving media output.
16
+ function validateMagicNumbers(buffer: Buffer): boolean {
17
+ if (buffer.length < 4) return false;
18
+ const hex = buffer.toString('hex', 0, 8).toUpperCase();
19
+ // JPEG: FFD8FFE0, PNG: 89504E47, WAV: 52494646 (RIFF), MP3: 494433 (ID3)
20
+ if (hex.startsWith('FFD8FF')) return true; // JPEG
21
+ if (hex.startsWith('89504E47')) return true; // PNG
22
+ 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'
25
+ if (buffer.length >= 8) {
26
+ const boxType = buffer.toString('ascii', 4, 8);
27
+ if (['ftyp', 'moov', 'mdat', 'free'].includes(boxType)) return true;
28
+ }
29
+ return false;
30
+ }
31
+
32
+ const CACHE_DIR = path.join(causyneHome(), 'media-cache');
33
+
34
+ /**
35
+ * Helper to trigger execution path isolation for specialized API providers (Gemini Veo/Imagen, OpenAI DALL-E, Qwen Wan)
36
+ */
37
+ async function routeMultimediaRequest(args: MediaArgs, config: Record<string, any>, sandbox: MediaContext | undefined, tokenTracker: TokenTracker): Promise<RouteResult | null> {
38
+ const { mediaType, prompt, targetProvider = 'auto', targetModel, durationSeconds = 5 } = args;
39
+
40
+ // Auto-resolve provider based on available keys and media type
41
+ let provider = targetProvider;
42
+ let model = targetModel;
43
+
44
+ if (provider === 'auto') {
45
+ if (mediaType === 'video_animation') {
46
+ if (config.geminiApiKey || (config.provider === 'gemini' && config.apiKey)) {
47
+ provider = 'gemini';
48
+ model = model || 'veo-2.0-generate-001';
49
+ } else if (config.dashscopeApiKey || (config.provider === 'qwen' && config.apiKey)) {
50
+ provider = 'qwen';
51
+ model = model || 'wanx-v2.1-t2v-turbo';
52
+ } else if (config.openaiApiKey || (config.provider === 'openai' && config.apiKey)) {
53
+ provider = 'openai';
54
+ model = model || 'sora-2';
55
+
56
+ }
57
+ } else if (mediaType === 'image') {
58
+ // Reuse an already configured provider before selecting another service.
59
+ if (config.museApiKey || ((config.provider === 'muse' || config.provider === 'meta') && config.apiKey)) {
60
+ provider = 'muse';
61
+ model = model || 'muse-image-1.0';
62
+ } else if (config.geminiApiKey || (config.provider === 'gemini' && config.apiKey)) {
63
+ provider = 'gemini';
64
+ model = model || 'imagen-3.0-generate-002';
65
+ } else if (config.openaiApiKey || (config.provider === 'openai' && config.apiKey)) {
66
+ provider = 'openai';
67
+ model = model || 'dall-e-3';
68
+ } else {
69
+ provider = 'pollinations';
70
+ model = model || 'flux';
71
+ }
72
+ }
73
+ }
74
+
75
+ // Pollinations uses its authenticated binary-response endpoint below.
76
+ if (provider === 'pollinations' || provider === 'local' || !['gemini', 'openai', 'qwen', 'muse'].includes(provider)) {
77
+ return null;
78
+ }
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
+
86
+ // 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') {
88
+ // The paid-media consent modal is skipped in Mode C (pre-approved) and in
89
+ // hardened developer emulator mode (secret-gated — see devMode.js).
90
+ if (!isDevEmulator(config) && config.autonomyMode !== 'C') {
91
+ const approvalId = `media_${crypto.randomUUID()}`;
92
+ if (typeof sandbox.emitEvent === 'function') {
93
+ sandbox.emitEvent({
94
+ type: 'approval_request',
95
+ toolCallId: approvalId,
96
+ tool: 'generate_media_via_api (Auto-Switch)',
97
+ args: {
98
+ targetProvider: provider.toUpperCase(),
99
+ targetModel: model,
100
+ mediaType,
101
+ prompt,
102
+ estimatedCostUsd: `$${estimatedCost.toFixed(2)}`,
103
+ estimatedTokens: `~${estimatedTokens.toLocaleString()} Equivalent Tokens`
104
+ },
105
+ risk: 'monetary_cost'
106
+ });
107
+ }
108
+
109
+ const approved = await sandbox.waitForApproval(approvalId);
110
+ if (!approved) {
111
+ return { success: false, code: 'MEDIA_APPROVAL_DENIED', error: 'Paid media generation was declined. No media artifact was produced.' };
112
+ }
113
+ }
114
+ }
115
+
116
+ // Check the estimated monetary ceiling before requesting generation. A failed
117
+ // request must not be recorded as successfully generated media.
118
+ const daily = await tokenTracker.getDailyUsage();
119
+ if (tokenTracker.budget.enabled && tokenTracker.budget.hardStop && tokenTracker.budget.maxCostUsd
120
+ && (daily.totalCostUsd || 0) + estimatedCost > tokenTracker.budget.maxCostUsd) {
121
+ return { success: false, code: 'MEDIA_BUDGET_EXCEEDED', error: 'The estimated media request would exceed the configured monetary budget.' };
122
+ }
123
+
124
+ // Execute actual REST call to the specialized provider (Gemini / OpenAI / Qwen)
125
+ let targetUrl = '';
126
+ const activeProvider = config.provider === 'meta' ? 'muse' : config.provider;
127
+ const apiKey = config[`${provider}ApiKey`] || (provider === 'qwen' ? config.dashscopeApiKey : undefined) || (activeProvider === provider ? config.apiKey : undefined);
128
+ let headers: Record<string, string> = { 'Content-Type': 'application/json' };
129
+ let body: Record<string, unknown> = {};
130
+
131
+ if (provider === 'gemini') {
132
+ headers['x-goog-api-key'] = apiKey;
133
+ if (mediaType === 'video_animation') {
134
+ targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict`;
135
+ body = { instances: [{ prompt }], parameters: { durationSeconds } };
136
+ } else {
137
+ targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict`;
138
+ body = { instances: [{ prompt }], parameters: { sampleCount: 1 } };
139
+ }
140
+ } else if (provider === 'muse') {
141
+ // Muse Image is the only model in the family that outputs images, and there
142
+ // is no video model at all — a video request must fall through to the
143
+ // sovereign hierarchy rather than be billed against an image endpoint.
144
+ if (mediaType !== 'image') return null;
145
+ targetUrl = 'https://api.meta.ai/v1/images/generations';
146
+ headers['Authorization'] = `Bearer ${apiKey}`;
147
+ body = { model: model || 'muse-image-1.0', prompt, n: 1, response_format: 'b64_json' };
148
+ } else if (provider === 'openai') {
149
+ if (mediaType === 'image') {
150
+ targetUrl = 'https://api.openai.com/v1/images/generations';
151
+ headers['Authorization'] = `Bearer ${apiKey}`;
152
+ body = { model: model || 'dall-e-3', prompt, n: 1, response_format: 'b64_json' };
153
+ } else {
154
+ targetUrl = 'https://api.openai.com/v1/video/generations';
155
+ headers['Authorization'] = `Bearer ${apiKey}`;
156
+ body = { model: model || 'sora-2', prompt };
157
+ }
158
+ }
159
+
160
+ 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) });
162
+ 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
+
164
+ const data = await response.json() as { data?: Array<{ b64_json?: string; url?: string }>; predictions?: Array<{ bytesBase64Encoded?: string }>; url?: string };
165
+ let buffer = null;
166
+
167
+
168
+ if ((provider === 'openai' || provider === 'muse') && data.data && data.data[0]?.b64_json) {
169
+ buffer = Buffer.from(data.data[0]!.b64_json!, 'base64');
170
+ } else if (provider === 'gemini' && data.predictions && data.predictions[0]?.bytesBase64Encoded) {
171
+ buffer = Buffer.from(data.predictions[0]!.bytesBase64Encoded!, 'base64');
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
+
179
+ if (!buffer || !validateMagicNumbers(buffer)) return { success: false, code: 'INVALID_MEDIA_RESPONSE', error: `Provider ${provider} did not return a supported media file. No artifact was produced.` };
180
+
181
+ await tokenTracker.trackMediaUsage(provider, mediaType, model || '', quantity);
182
+
183
+ return {
184
+ success: true,
185
+ buffer,
186
+ provider,
187
+ model: model || '',
188
+ costUsd: estimatedCost,
189
+ equivalentTokens: estimatedTokens
190
+ };
191
+ }
192
+
193
+ export const generateMediaViaApi: { schema: { name: string; description: string; parameters: ParameterSchema }; execute: (args: unknown, sandbox?: MediaContext) => Promise<RouteResult> } = {
194
+ schema: {
195
+ name: 'generate_media_via_api',
196
+ 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.',
197
+ parameters: {
198
+ type: 'object',
199
+ properties: {
200
+ mediaType: { type: 'string', enum: ['image', 'audio_tts', 'video_animation'] },
201
+ prompt: { type: 'string' },
202
+ outputPath: { type: 'string', description: 'Destination in the selected workspace. Omit to use a unique generated filename there.' },
203
+ width: { type: 'number' },
204
+ height: { type: 'number' },
205
+ model: { type: 'string' },
206
+ voice: { type: 'string' },
207
+ targetProvider: { type: 'string', enum: ['auto', 'gemini', 'openai', 'qwen', 'pollinations'], description: 'Optional provider routing for specialized models.' },
208
+ targetModel: { type: 'string', description: 'Optional exact model name (e.g. veo-2.0-generate-001, imagen-3.0-generate-002, dall-e-3).' },
209
+ durationSeconds: { type: 'number', description: 'Duration in seconds for video animations (default 5).' }
210
+ },
211
+ required: ['mediaType', 'prompt']
212
+ }
213
+ },
214
+
215
+ execute: async (input: unknown, sandbox?: MediaContext): Promise<RouteResult> => {
216
+ try {
217
+ const issues = validateToolArguments(input, generateMediaViaApi.schema.parameters as ParameterSchema);
218
+ if (issues.length) return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: issues.join('; '), expectedSchema: generateMediaViaApi.schema.parameters };
219
+ const args = input as MediaArgs;
220
+ const workspaceRoot = sandbox?.parentLoop?.workspaceRoot || sandbox?.workspaceRoot || sandbox?.workspacePaths?.[0] || process.cwd();
221
+ const pathPolicy = sandbox?.parentLoop?.sandbox || sandbox;
222
+ if (!args.prompt.trim()) return { success: false, code: 'INVALID_TOOL_ARGUMENTS', error: 'prompt must be a nonempty string' };
223
+ const { mediaType = 'image', prompt = '', width, height, model, voice, targetProvider, targetModel, durationSeconds } = args || {};
224
+ const ext = mediaType === 'audio_tts' ? 'mp3' : mediaType === 'video_animation' ? 'mp4' : 'png';
225
+ const rawOutputPath = typeof args?.outputPath === 'string' && args.outputPath.trim()
226
+ ? args.outputPath.trim()
227
+ : path.join(workspaceRoot, `generated_media_${crypto.randomUUID()}.${ext}`);
228
+ const outputPath = rawOutputPath.startsWith('~') ? resolveUserPath(rawOutputPath) : path.resolve(workspaceRoot, rawOutputPath);
229
+
230
+ if (pathPolicy?.isPathAllowed && !pathPolicy.isPathAllowed(outputPath)) {
231
+ return { success: false, error: `Path outside allowed workspace: ${outputPath}` };
232
+ }
233
+
234
+ const outputDir = path.dirname(outputPath);
235
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
236
+ if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true });
237
+
238
+ // Cache complete media responses.
239
+ const promptHash = crypto.createHash('sha256').update(JSON.stringify(args)).digest('hex');
240
+ const cachedFile = path.join(CACHE_DIR, promptHash);
241
+ if (fs.existsSync(cachedFile) && validateMagicNumbers(fs.readFileSync(cachedFile))) {
242
+ fs.copyFileSync(cachedFile, outputPath);
243
+ return {
244
+ success: true,
245
+ message: `Cache Hit: Loaded instantly from local AI cache. Saved to ${outputPath}`,
246
+ sizeBytes: fs.statSync(outputPath).size,
247
+ mode: 'D / Router (Cached)'
248
+ };
249
+ }
250
+
251
+ const config = loadConfig();
252
+ const tokenTracker = new TokenTracker();
253
+
254
+ // Use the configured media provider first.
255
+ const routeResult = await routeMultimediaRequest(args, config, sandbox, tokenTracker);
256
+ if (routeResult) {
257
+ if (routeResult.success !== true || !routeResult.buffer) return { ...routeResult, success: false };
258
+ fs.writeFileSync(cachedFile, routeResult.buffer);
259
+ fs.writeFileSync(outputPath, routeResult.buffer);
260
+ return {
261
+ success: true,
262
+ message: `Media saved via ${String(routeResult.provider).toUpperCase()} (${routeResult.model}) to ${outputPath}. Estimated cost: $${(routeResult.costUsd || 0).toFixed(2)}.`,
263
+ sizeBytes: routeResult.buffer.length,
264
+ mode: `API (${String(routeResult.provider).toUpperCase()})`
265
+ };
266
+ }
267
+
268
+ // Pollinations generation requires user-configured credentials. Missing keys
269
+ // are a configuration blocker, not a reason to retry anonymous requests.
270
+ const pollinationsKey = config.pollinationsApiKey || process.env.POLLINATIONS_API_KEY;
271
+ if (!pollinationsKey) return {
272
+ success: false, code: 'MEDIA_AUTH_REQUIRED', retryable: false,
273
+ error: 'Image/audio generation requires a configured media provider key. The anonymous Pollinations fallback is unavailable. No media artifact was produced.',
274
+ 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
+ };
276
+ 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') {
278
+ 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.' };
281
+ }
282
+ const query = new URLSearchParams(mediaType === 'image'
283
+ ? { width: String(width || 1024), height: String(height || 1024), model: model || targetModel || 'flux', seed: String(Date.now()) }
284
+ : { voice: voice || 'nova', model: model || targetModel || 'openai-audio' });
285
+ const targetUrl = `https://gen.pollinations.ai/${mediaType === 'image' ? 'image' : 'audio'}/${encodeURIComponent(prompt)}?${query}`;
286
+ let buffer: Buffer | null = null;
287
+ let attempts = 0;
288
+ while (attempts < 3) {
289
+ attempts++;
290
+ const response = await fetch(targetUrl, { headers: { Authorization: `Bearer ${pollinationsKey}` }, signal: sandbox?.signal || AbortSignal.timeout(120_000) });
291
+ if (!response.ok) {
292
+ const retryable = response.status === 429 || response.status >= 500;
293
+ if (!retryable || attempts === 3) return {
294
+ success: false, code: 'MEDIA_PROVIDER_ERROR', status: response.status, attempts, retryable,
295
+ error: `Pollinations returned HTTP ${response.status}. No media artifact was produced.`,
296
+ nextAction: [401, 402, 403].includes(response.status) ? 'The user must check provider authentication, permissions, or balance before retrying.' : 'Check provider availability before retrying.'
297
+ };
298
+ await new Promise<void>((resolve, reject) => {
299
+ const signal = sandbox?.signal;
300
+ const abort = (): void => { clearTimeout(timer); reject(new Error('Media generation aborted')); };
301
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, attempts * 1000);
302
+ if (signal?.aborted) abort(); else signal?.addEventListener('abort', abort, { once: true });
303
+ });
304
+ continue;
305
+ }
306
+ const candidate = Buffer.from(await response.arrayBuffer());
307
+ if (!validateMagicNumbers(candidate)) return { success: false, code: 'INVALID_MEDIA_RESPONSE', attempts, error: 'Provider response is not a supported media file. No artifact was produced.' };
308
+ buffer = candidate;
309
+ break;
310
+ }
311
+ if (!buffer) return { success: false, error: 'Media generation did not produce a file.' };
312
+
313
+ // Generation pricing is service-dependent; do not advertise this route as free.
314
+ await tokenTracker.trackMediaUsage('pollinations', mediaType, 'flux', 1);
315
+
316
+ // Write to cache and output
317
+ fs.writeFileSync(cachedFile, buffer);
318
+ fs.writeFileSync(outputPath, buffer);
319
+
320
+ return {
321
+ success: true,
322
+ message: `Media generated, validated, and cached successfully via Pollinations Mode D. Saved to ${outputPath}`,
323
+ sizeBytes: buffer.length,
324
+ mode: 'D (Validated API)'
325
+ };
326
+ } catch (err) {
327
+ return { success: false, error: errorMessage(err) };
328
+ }
329
+ }
330
+ };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @file src/tools/historyPruner.ts
3
+ * Re-export wrapper for historyPruner adhering to Implementation Plan structure.
4
+ */
5
+ export * from '../historyPruner.js';
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @file src/tools/historyPruner.ts
3
+ * Re-export wrapper for historyPruner adhering to Implementation Plan structure.
4
+ */
5
+ export * from '../historyPruner.js';
@@ -0,0 +1,92 @@
1
+ /**
2
+ * @file src/tools/payloadSanitizer.ts
3
+ * Causyne Agent — Media Payload Ceilings & Format Sniffer
4
+ *
5
+ * Ported & elevated from OpenClaw (src/media/configured-max-bytes.ts).
6
+ * Enforces strict per-media-kind byte limits (images, audio, video) and
7
+ * validates container magic numbers before staging payloads to LLM APIs,
8
+ * preventing multimodal payloads from overflowing context limits.
9
+ *
10
+ * Authorship: Strict TypeScript (Causyne Agent).
11
+ */
12
+ export const DEFAULT_PAYLOAD_LIMITS = {
13
+ maxImageBytes: 5 * 1024 * 1024,
14
+ maxAudioBytes: 10 * 1024 * 1024,
15
+ maxVideoBytes: 25 * 1024 * 1024,
16
+ maxTextChars: 100_000
17
+ };
18
+ export function detectMagicFormat(buffer) {
19
+ if (buffer.length < 4)
20
+ return null;
21
+ const hex = buffer.toString('hex', 0, 12).toUpperCase();
22
+ // Images
23
+ if (hex.startsWith('FFD8FF'))
24
+ return 'jpeg';
25
+ if (hex.startsWith('89504E47'))
26
+ return 'png';
27
+ if (hex.startsWith('47494638'))
28
+ return 'gif';
29
+ if (hex.startsWith('52494646') && buffer.length >= 12 && buffer.toString('ascii', 8, 12) === 'WEBP')
30
+ return 'webp';
31
+ // Audio
32
+ if (hex.startsWith('52494646') && buffer.length >= 12 && buffer.toString('ascii', 8, 12) === 'WAVE')
33
+ return 'wav';
34
+ if (hex.startsWith('494433') || hex.startsWith('FFF3') || hex.startsWith('FFF2') || hex.startsWith('FFE3'))
35
+ return 'mp3';
36
+ // Video: box size followed by 'ftyp' or 'moov'
37
+ if (buffer.length >= 8) {
38
+ const boxType = buffer.toString('ascii', 4, 8);
39
+ if (['ftyp', 'moov', 'mdat', 'free'].includes(boxType))
40
+ return 'mp4';
41
+ }
42
+ return null;
43
+ }
44
+ export function validateMediaPayload(buffer, kind, limits = {}) {
45
+ const byteLength = buffer.length;
46
+ const activeLimits = { ...DEFAULT_PAYLOAD_LIMITS, ...limits };
47
+ let maxAllowed = activeLimits.maxImageBytes;
48
+ if (kind === 'audio')
49
+ maxAllowed = activeLimits.maxAudioBytes;
50
+ if (kind === 'video')
51
+ maxAllowed = activeLimits.maxVideoBytes;
52
+ if (byteLength > maxAllowed) {
53
+ return {
54
+ valid: false,
55
+ byteLength,
56
+ error: `Payload size (${(byteLength / 1024 / 1024).toFixed(2)} MB) exceeds allowed limit of ${(maxAllowed / 1024 / 1024).toFixed(1)} MB for ${kind}.`
57
+ };
58
+ }
59
+ const format = detectMagicFormat(buffer);
60
+ if (!format) {
61
+ return {
62
+ valid: false,
63
+ byteLength,
64
+ error: `Unrecognized or invalid binary format for ${kind} payload. Magic numbers missing.`
65
+ };
66
+ }
67
+ const expectedKindForFormat = {
68
+ jpeg: 'image', png: 'image', gif: 'image', webp: 'image',
69
+ wav: 'audio', mp3: 'audio',
70
+ mp4: 'video'
71
+ };
72
+ if (expectedKindForFormat[format] !== kind) {
73
+ return {
74
+ valid: false,
75
+ byteLength,
76
+ detectedFormat: format,
77
+ error: `Format mismatch: detected '${format}' which is not a valid ${kind} container.`
78
+ };
79
+ }
80
+ return {
81
+ valid: true,
82
+ byteLength,
83
+ detectedFormat: format
84
+ };
85
+ }
86
+ export function sanitizeTextPayload(text, maxChars = DEFAULT_PAYLOAD_LIMITS.maxTextChars) {
87
+ if (text.length <= maxChars)
88
+ return text;
89
+ const half = Math.floor(maxChars / 2);
90
+ const omitted = text.length - maxChars;
91
+ return text.slice(0, half) + `\n[... ${omitted} characters sanitized to protect context budget ...]\n` + text.slice(-half);
92
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * @file src/tools/payloadSanitizer.ts
3
+ * Causyne Agent — Media Payload Ceilings & Format Sniffer
4
+ *
5
+ * Ported & elevated from OpenClaw (src/media/configured-max-bytes.ts).
6
+ * Enforces strict per-media-kind byte limits (images, audio, video) and
7
+ * validates container magic numbers before staging payloads to LLM APIs,
8
+ * preventing multimodal payloads from overflowing context limits.
9
+ *
10
+ * Authorship: Strict TypeScript (Causyne Agent).
11
+ */
12
+
13
+ export interface PayloadLimits {
14
+ readonly maxImageBytes: number; // Default: 5 * 1024 * 1024 (5 MB)
15
+ readonly maxAudioBytes: number; // Default: 10 * 1024 * 1024 (10 MB)
16
+ readonly maxVideoBytes: number; // Default: 25 * 1024 * 1024 (25 MB)
17
+ readonly maxTextChars: number; // Default: 100,000 characters
18
+ }
19
+
20
+ export const DEFAULT_PAYLOAD_LIMITS: PayloadLimits = {
21
+ maxImageBytes: 5 * 1024 * 1024,
22
+ maxAudioBytes: 10 * 1024 * 1024,
23
+ maxVideoBytes: 25 * 1024 * 1024,
24
+ maxTextChars: 100_000
25
+ };
26
+
27
+ export interface MediaValidationResult {
28
+ readonly valid: boolean;
29
+ readonly byteLength: number;
30
+ readonly detectedFormat?: string | undefined;
31
+ readonly error?: string | undefined;
32
+ }
33
+
34
+ export function detectMagicFormat(buffer: Buffer): string | null {
35
+ if (buffer.length < 4) return null;
36
+ const hex = buffer.toString('hex', 0, 12).toUpperCase();
37
+
38
+ // Images
39
+ if (hex.startsWith('FFD8FF')) return 'jpeg';
40
+ if (hex.startsWith('89504E47')) return 'png';
41
+ if (hex.startsWith('47494638')) return 'gif';
42
+ if (hex.startsWith('52494646') && buffer.length >= 12 && buffer.toString('ascii', 8, 12) === 'WEBP') return 'webp';
43
+
44
+ // Audio
45
+ if (hex.startsWith('52494646') && buffer.length >= 12 && buffer.toString('ascii', 8, 12) === 'WAVE') return 'wav';
46
+ if (hex.startsWith('494433') || hex.startsWith('FFF3') || hex.startsWith('FFF2') || hex.startsWith('FFE3')) return 'mp3';
47
+
48
+ // Video: box size followed by 'ftyp' or 'moov'
49
+ if (buffer.length >= 8) {
50
+ const boxType = buffer.toString('ascii', 4, 8);
51
+ if (['ftyp', 'moov', 'mdat', 'free'].includes(boxType)) return 'mp4';
52
+ }
53
+
54
+ return null;
55
+ }
56
+
57
+ export function validateMediaPayload(
58
+ buffer: Buffer,
59
+ kind: 'image' | 'audio' | 'video',
60
+ limits: Partial<PayloadLimits> = {}
61
+ ): MediaValidationResult {
62
+ const byteLength = buffer.length;
63
+ const activeLimits: PayloadLimits = { ...DEFAULT_PAYLOAD_LIMITS, ...limits };
64
+
65
+ let maxAllowed = activeLimits.maxImageBytes;
66
+ if (kind === 'audio') maxAllowed = activeLimits.maxAudioBytes;
67
+ if (kind === 'video') maxAllowed = activeLimits.maxVideoBytes;
68
+
69
+ if (byteLength > maxAllowed) {
70
+ return {
71
+ valid: false,
72
+ byteLength,
73
+ error: `Payload size (${(byteLength / 1024 / 1024).toFixed(2)} MB) exceeds allowed limit of ${(maxAllowed / 1024 / 1024).toFixed(1)} MB for ${kind}.`
74
+ };
75
+ }
76
+
77
+ const format = detectMagicFormat(buffer);
78
+ if (!format) {
79
+ return {
80
+ valid: false,
81
+ byteLength,
82
+ error: `Unrecognized or invalid binary format for ${kind} payload. Magic numbers missing.`
83
+ };
84
+ }
85
+
86
+ const expectedKindForFormat: Record<string, 'image' | 'audio' | 'video'> = {
87
+ jpeg: 'image', png: 'image', gif: 'image', webp: 'image',
88
+ wav: 'audio', mp3: 'audio',
89
+ mp4: 'video'
90
+ };
91
+
92
+ if (expectedKindForFormat[format] !== kind) {
93
+ return {
94
+ valid: false,
95
+ byteLength,
96
+ detectedFormat: format,
97
+ error: `Format mismatch: detected '${format}' which is not a valid ${kind} container.`
98
+ };
99
+ }
100
+
101
+ return {
102
+ valid: true,
103
+ byteLength,
104
+ detectedFormat: format
105
+ };
106
+ }
107
+
108
+ export function sanitizeTextPayload(text: string, maxChars: number = DEFAULT_PAYLOAD_LIMITS.maxTextChars): string {
109
+ if (text.length <= maxChars) return text;
110
+ const half = Math.floor(maxChars / 2);
111
+ const omitted = text.length - maxChars;
112
+ return text.slice(0, half) + `\n[... ${omitted} characters sanitized to protect context budget ...]\n` + text.slice(-half);
113
+ }
@@ -2,3 +2,4 @@ export const TOOL_DEFINITIONS: any;
2
2
  export function getDynamicTools(...args: any[]): any;
3
3
  export function resolveTool(...args: any[]): any;
4
4
  export function canonicalToolName(...args: any[]): any;
5
+ export function getSearchableToolDefinitions(): Promise<Array<{ name: string; description?: string; parameters?: import('./toolSelfRepair.js').ParameterSchema }>>;