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