@causyne/agent 0.0.0-stage → 1.10.1
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 +102 -0
- package/README.md +31 -2
- package/SECURITY.md +24 -0
- package/bin/causyne.js +13 -0
- package/docs/ARCHITECTURE.md +63 -0
- package/docs/PROVENANCE.md +29 -0
- package/docs/SECURITY_REVIEW.md +89 -0
- package/docs/THIRD_PARTY_NOTICES.md +49 -0
- package/native-skills/ai-engineering/context-window-management/SKILL.md +43 -0
- package/native-skills/ai-engineering/llm-evaluation/SKILL.md +46 -0
- package/native-skills/ai-engineering/model-cost-and-latency/SKILL.md +46 -0
- package/native-skills/ai-engineering/prompt-construction/SKILL.md +42 -0
- package/native-skills/ai-engineering/retrieval-augmented-generation/SKILL.md +42 -0
- package/native-skills/ai-engineering/structured-output-and-schemas/SKILL.md +45 -0
- package/native-skills/ai-engineering/tool-calling-agents/SKILL.md +43 -0
- package/native-skills/android/app-performance-profiling/SKILL.md +42 -0
- package/native-skills/android/background-work-scheduling/SKILL.md +47 -0
- package/native-skills/android/compose-state-and-recomposition/SKILL.md +43 -0
- package/native-skills/android/gradle-build-configuration/SKILL.md +41 -0
- package/native-skills/android/lifecycle-and-leaks/SKILL.md +46 -0
- package/native-skills/android/play-store-release/SKILL.md +43 -0
- package/native-skills/android/room-and-persistence/SKILL.md +40 -0
- package/native-skills/backend/authentication-and-sessions/SKILL.md +45 -0
- package/native-skills/backend/background-jobs-and-queues/SKILL.md +42 -0
- package/native-skills/backend/caching-strategy/SKILL.md +44 -0
- package/native-skills/backend/graceful-shutdown/SKILL.md +42 -0
- package/native-skills/backend/rate-limiting-and-quotas/SKILL.md +40 -0
- package/native-skills/backend/rest-api-design/SKILL.md +40 -0
- package/native-skills/backend/webhook-delivery-and-receipt/SKILL.md +43 -0
- package/native-skills/cloud/cost-optimisation/SKILL.md +46 -0
- package/native-skills/cloud/iam-least-privilege/SKILL.md +43 -0
- package/native-skills/cloud/infrastructure-as-code/SKILL.md +43 -0
- package/native-skills/cloud/multi-region-and-failover/SKILL.md +43 -0
- package/native-skills/cloud/serverless-patterns/SKILL.md +47 -0
- package/native-skills/data/data-quality-monitoring/SKILL.md +51 -0
- package/native-skills/data/etl-pipeline-reliability/SKILL.md +43 -0
- package/native-skills/data/exploratory-analysis/SKILL.md +43 -0
- package/native-skills/data/metric-definition/SKILL.md +42 -0
- package/native-skills/data/notebook-to-production/SKILL.md +43 -0
- package/native-skills/database/backup-and-recovery/SKILL.md +43 -0
- package/native-skills/database/connection-pooling/SKILL.md +42 -0
- package/native-skills/database/data-integrity-and-constraints/SKILL.md +42 -0
- package/native-skills/database/query-optimisation/SKILL.md +38 -0
- package/native-skills/database/safe-migrations/SKILL.md +47 -0
- package/native-skills/database/schema-design/SKILL.md +38 -0
- package/native-skills/database/transactions-and-isolation/SKILL.md +41 -0
- package/native-skills/design/colour-system-construction/SKILL.md +38 -0
- package/native-skills/design/design-direction-brief/SKILL.md +41 -0
- package/native-skills/design/motion-and-transitions/SKILL.md +38 -0
- package/native-skills/design/responsive-strategy/SKILL.md +39 -0
- package/native-skills/design/spacing-and-rhythm/SKILL.md +38 -0
- package/native-skills/design/type-scale-and-hierarchy/SKILL.md +39 -0
- package/native-skills/design/visual-qa-loop/SKILL.md +42 -0
- package/native-skills/devops/docker-multi-stage-builds/SKILL.md +60 -0
- package/native-skills/devops/github-actions-ci/SKILL.md +60 -0
- package/native-skills/devops/incident-triage/SKILL.md +38 -0
- package/native-skills/devops/kubernetes-deployment-hardening/SKILL.md +64 -0
- package/native-skills/devops/observability-baseline/SKILL.md +38 -0
- package/native-skills/devops/secret-management/SKILL.md +40 -0
- package/native-skills/devops/terraform-state-and-modules/SKILL.md +36 -0
- package/native-skills/devops/zero-downtime-deploys/SKILL.md +40 -0
- package/native-skills/git/bisect-regression-hunt/SKILL.md +43 -0
- package/native-skills/git/branch-strategy/SKILL.md +39 -0
- package/native-skills/git/commit-hygiene/SKILL.md +41 -0
- package/native-skills/git/history-recovery/SKILL.md +44 -0
- package/native-skills/git/large-repository-surgery/SKILL.md +46 -0
- package/native-skills/git/merge-conflict-resolution/SKILL.md +42 -0
- package/native-skills/media/cinematic-3d-shot/SKILL.md +104 -0
- package/native-skills/mobile/app-startup-optimisation/SKILL.md +41 -0
- package/native-skills/mobile/cross-platform-tradeoffs/SKILL.md +42 -0
- package/native-skills/mobile/deep-linking/SKILL.md +39 -0
- package/native-skills/mobile/mobile-storage-security/SKILL.md +45 -0
- package/native-skills/mobile/offline-first-sync/SKILL.md +42 -0
- package/native-skills/mobile/push-notifications/SKILL.md +38 -0
- package/native-skills/performance/algorithmic-complexity/SKILL.md +43 -0
- package/native-skills/performance/concurrency-and-parallelism/SKILL.md +42 -0
- package/native-skills/performance/load-testing/SKILL.md +42 -0
- package/native-skills/performance/memory-and-leak-hunting/SKILL.md +41 -0
- package/native-skills/performance/network-and-payload-efficiency/SKILL.md +42 -0
- package/native-skills/performance/profiling-methodology/SKILL.md +46 -0
- package/native-skills/python/async-correctness/SKILL.md +40 -0
- package/native-skills/python/cli-tool-construction/SKILL.md +44 -0
- package/native-skills/python/data-processing-pipelines/SKILL.md +38 -0
- package/native-skills/python/environment-isolation/SKILL.md +41 -0
- package/native-skills/python/packaging-and-distribution/SKILL.md +56 -0
- package/native-skills/python/pytest-suite-design/SKILL.md +39 -0
- package/native-skills/python/type-hints-and-static-checking/SKILL.md +42 -0
- package/native-skills/security/authorization-model/SKILL.md +42 -0
- package/native-skills/security/crypto-usage/SKILL.md +48 -0
- package/native-skills/security/dependency-supply-chain/SKILL.md +42 -0
- package/native-skills/security/input-validation-and-injection/SKILL.md +44 -0
- package/native-skills/security/secure-file-uploads/SKILL.md +46 -0
- package/native-skills/security/security-headers-and-csp/SKILL.md +44 -0
- package/native-skills/security/threat-modelling/SKILL.md +46 -0
- package/native-skills/testing/end-to-end-test-stability/SKILL.md +42 -0
- package/native-skills/testing/property-based-testing/SKILL.md +46 -0
- package/native-skills/testing/regression-test-from-a-bug/SKILL.md +41 -0
- package/native-skills/testing/snapshot-and-visual-regression/SKILL.md +42 -0
- package/native-skills/testing/test-doubles-and-mocking/SKILL.md +43 -0
- package/native-skills/testing/test-strategy-and-pyramid/SKILL.md +39 -0
- package/native-skills/testing/writing-good-assertions/SKILL.md +42 -0
- package/native-skills/web/accessible-components/SKILL.md +45 -0
- package/native-skills/web/api-client-resilience/SKILL.md +39 -0
- package/native-skills/web/bundle-size-reduction/SKILL.md +38 -0
- package/native-skills/web/core-web-vitals/SKILL.md +40 -0
- package/native-skills/web/css-layout-systems/SKILL.md +41 -0
- package/native-skills/web/form-validation-ux/SKILL.md +39 -0
- package/native-skills/web/react-state-architecture/SKILL.md +41 -0
- package/native-skills/web/ssr-hydration-correctness/SKILL.md +45 -0
- package/package.json +68 -4
- package/src/agentLoop.js +2458 -0
- package/src/appChannel.js +109 -0
- package/src/approvalGrants.js +66 -0
- package/src/auditLog.js +52 -0
- package/src/autoUpdate.js +12 -0
- package/src/capabilities.js +36 -0
- package/src/checkpoints.js +1199 -0
- package/src/cliMode.js +638 -0
- package/src/commands.js +805 -0
- package/src/compiledSkills.js +540 -0
- package/src/config.js +130 -0
- package/src/contextManager.js +498 -0
- package/src/cortex/autoCondenser.js +192 -0
- package/src/cortex/provisioner.js +27 -0
- package/src/cortex/vectorDb.js +447 -0
- package/src/designPalettes.js +99 -0
- package/src/devMode.js +6 -0
- package/src/embodimentSession.js +180 -0
- package/src/entrypoint.js +194 -0
- package/src/execSafe.js +21 -0
- package/src/gitSnapshot.js +378 -0
- package/src/mcp/jsonRpc.js +165 -0
- package/src/mcp/mcpClient.js +136 -0
- package/src/mcp/mcpRegistry.js +207 -0
- package/src/memory.js +62 -0
- package/src/memoryManager.js +124 -0
- package/src/modelCatalogue.js +132 -0
- package/src/modelIds.js +42 -0
- package/src/modelRouter.js +145 -0
- package/src/outputStore.js +246 -0
- package/src/perception.js +124 -0
- package/src/planCache.js +437 -0
- package/src/procSignal.js +32 -0
- package/src/providers/anthropic.js +408 -0
- package/src/providers/base.js +328 -0
- package/src/providers/dashscope-byok.js +86 -0
- package/src/providers/deepseek.js +80 -0
- package/src/providers/factory.js +37 -0
- package/src/providers/gemini.js +346 -0
- package/src/providers/moonshot.js +73 -0
- package/src/providers/muse.js +169 -0
- package/src/providers/ollama.js +104 -0
- package/src/providers/openai-compatible.js +84 -0
- package/src/providers/openai.js +20 -0
- package/src/providers/qwen-byok.js +76 -0
- package/src/providers/xai.js +73 -0
- package/src/provisioning/capabilityConsent.js +24 -0
- package/src/provisioning/capabilityProvisioner.js +271 -0
- package/src/provisioning/capabilityTools.js +29 -0
- package/src/reporting.js +373 -0
- package/src/sandbox.js +529 -0
- package/src/sessionStore.js +279 -0
- package/src/skillsManager.js +288 -0
- package/src/slopDetector.js +307 -0
- package/src/taskBuffer.js +45 -0
- package/src/taskShape.js +241 -0
- package/src/textDiff.js +150 -0
- package/src/tokenTracker.js +560 -0
- package/src/tool-scripts/ax_snapshot.applescript +39 -0
- package/src/tool-scripts/ax_snapshot.ps1 +10 -0
- package/src/tool-scripts/desktop_act.applescript +58 -0
- package/src/tool-scripts/resolve_automator.py +119 -0
- package/src/toolPacks.js +524 -0
- package/src/tools/archive.js +63 -0
- package/src/tools/astryxOracle.js +78 -0
- package/src/tools/axSnapshot.js +165 -0
- package/src/tools/blenderAutomator.js +349 -0
- package/src/tools/browserAutomator.js +252 -0
- package/src/tools/checkSystemSpecs.js +64 -0
- package/src/tools/clipboard.js +36 -0
- package/src/tools/codeSearchAst.js +101 -0
- package/src/tools/codeSearcher.js +230 -0
- package/src/tools/codeTools.js +262 -0
- package/src/tools/codebaseSearch.js +75 -0
- package/src/tools/createSkill.js +129 -0
- package/src/tools/deferredMcpSearch.js +246 -0
- package/src/tools/desktopAct.js +208 -0
- package/src/tools/desktopOpen.js +34 -0
- package/src/tools/dynamicLoader.js +44 -0
- package/src/tools/executeProceduralMedia.js +93 -0
- package/src/tools/fsDelete.js +51 -0
- package/src/tools/fsEdit.js +105 -0
- package/src/tools/fsFind.js +128 -0
- package/src/tools/fsList.js +77 -0
- package/src/tools/fsMove.js +57 -0
- package/src/tools/fsRead.js +87 -0
- package/src/tools/fsSearch.js +198 -0
- package/src/tools/fsWrite.js +41 -0
- package/src/tools/gameAiBehaviorTree.js +208 -0
- package/src/tools/gameAnimationRig.js +194 -0
- package/src/tools/gameAssetFetcher.js +372 -0
- package/src/tools/gameAssetHarvester.js +210 -0
- package/src/tools/gameAudioSynth.js +267 -0
- package/src/tools/gameBuilder.js +886 -0
- package/src/tools/gameCanvasAudit.js +101 -0
- package/src/tools/gameCinematicSequencer.js +151 -0
- package/src/tools/gameDataForge.js +124 -0
- package/src/tools/gameDialogueTreeGen.js +166 -0
- package/src/tools/gameEconomyBalancer.js +161 -0
- package/src/tools/gameEntitySpawner.js +207 -0
- package/src/tools/gameLoreForge.js +153 -0
- package/src/tools/gameQuestArcBuilder.js +152 -0
- package/src/tools/gameSceneBuilder.js +158 -0
- package/src/tools/gameShaderForge.js +181 -0
- package/src/tools/gameTilemapGenerator.js +164 -0
- package/src/tools/gameUiHudBuilder.js +292 -0
- package/src/tools/gameVfxEmitterGen.js +108 -0
- package/src/tools/gameWebRuntimeInspector.js +91 -0
- package/src/tools/generateMediaViaApi.js +358 -0
- package/src/tools/gitExec.js +54 -0
- package/src/tools/godotAutomator.js +437 -0
- package/src/tools/manageLocalAiDependencies.js +220 -0
- package/src/tools/memoryWrite.js +99 -0
- package/src/tools/multiEdit.js +107 -0
- package/src/tools/palmierAutomator.js +104 -0
- package/src/tools/pdfReader.js +112 -0
- package/src/tools/persistentShell.js +148 -0
- package/src/tools/printer.js +316 -0
- package/src/tools/procTerm.js +91 -0
- package/src/tools/processList.js +52 -0
- package/src/tools/readNativeSkill.js +39 -0
- package/src/tools/registry.js +277 -0
- package/src/tools/resolveAutomator.js +102 -0
- package/src/tools/screenshot.js +75 -0
- package/src/tools/subagentOrchestrator.js +305 -0
- package/src/tools/sysRun.js +125 -0
- package/src/tools/todoWrite.js +75 -0
- package/src/tools/toolDispatch.js +127 -0
- package/src/tools/toolForge.js +124 -0
- package/src/tools/updatePlan.js +88 -0
- package/src/tools/viewImage.js +82 -0
- package/src/tools/visionInspector.js +154 -0
- package/src/tools/webFetch.js +74 -0
- package/src/tools/webSearch.js +82 -0
- package/src/tui/ask.js +164 -0
- package/src/tui/banner.js +158 -0
- package/src/tui/block.js +152 -0
- package/src/tui/chatRenderer.js +953 -0
- package/src/tui/completion.js +424 -0
- package/src/tui/dialogs.js +606 -0
- package/src/tui/diff.js +296 -0
- package/src/tui/history.js +135 -0
- package/src/tui/home.js +217 -0
- package/src/tui/invocation.js +105 -0
- package/src/tui/keys.js +443 -0
- package/src/tui/lineEditor.js +256 -0
- package/src/tui/overlay.js +256 -0
- package/src/tui/prompt.js +1258 -0
- package/src/tui/selectList.js +335 -0
- package/src/tui/stage.js +330 -0
- package/src/tui/stageSurface.js +609 -0
- package/src/tui/statusLine.js +254 -0
- package/src/tui/text.js +345 -0
- package/src/tui/theme.js +393 -0
- package/src/tui/toolDisplay.js +176 -0
- package/src/tui/transcript.js +235 -0
- package/src/tui/viewport.js +337 -0
- package/src/uncertainty.js +271 -0
- package/src/userSkills.js +265 -0
- package/src/utils/cli_ui.js +0 -0
- package/src/utils/inquirer.js +12 -0
- package/src/utils/paths.js +37 -0
- package/src/version.js +38 -0
- package/src/vfeTracker.js +220 -0
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import crypto from 'crypto';
|
|
5
|
+
import { loadConfig } from '../config.js';
|
|
6
|
+
import { isDevEmulator } from '../devMode.js';
|
|
7
|
+
import { TokenTracker } from '../tokenTracker.js';
|
|
8
|
+
|
|
9
|
+
// Phase 5 & 6 AGI Upgrade: Validated Generation across Image, Audio, and Video (Magic Numbers)
|
|
10
|
+
function validateMagicNumbers(buffer) {
|
|
11
|
+
if (buffer.length < 4) return false;
|
|
12
|
+
const hex = buffer.toString('hex', 0, 8).toUpperCase();
|
|
13
|
+
// JPEG: FFD8FFE0, PNG: 89504E47, WAV: 52494646 (RIFF), MP3: 494433 (ID3)
|
|
14
|
+
if (hex.startsWith('FFD8FF')) return true; // JPEG
|
|
15
|
+
if (hex.startsWith('89504E47')) return true; // PNG
|
|
16
|
+
if (hex.startsWith('52494646')) return true; // WAV/RIFF
|
|
17
|
+
if (hex.startsWith('494433')) return true; // MP3 (ID3)
|
|
18
|
+
// MP4 video container check: box size (4 bytes) followed by box type 'ftyp' (66747970 in hex) or 'moov' or 'mdat'
|
|
19
|
+
if (buffer.length >= 8) {
|
|
20
|
+
const boxType = buffer.toString('ascii', 4, 8);
|
|
21
|
+
if (['ftyp', 'moov', 'mdat', 'free'].includes(boxType)) return true;
|
|
22
|
+
}
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const CACHE_DIR = path.join(os.homedir(), '.causyne_media_cache');
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Helper to trigger execution path isolation for specialized API providers (Gemini Veo/Imagen, OpenAI DALL-E, Qwen Wan)
|
|
30
|
+
*/
|
|
31
|
+
async function routeMultimediaRequest(args, config, sandbox, tokenTracker) {
|
|
32
|
+
const { mediaType, prompt, targetProvider = 'auto', targetModel, durationSeconds = 5 } = args;
|
|
33
|
+
|
|
34
|
+
// Auto-resolve provider based on available keys and media type
|
|
35
|
+
let provider = targetProvider;
|
|
36
|
+
let model = targetModel;
|
|
37
|
+
|
|
38
|
+
if (provider === 'auto') {
|
|
39
|
+
if (mediaType === 'video_animation') {
|
|
40
|
+
if (config.geminiApiKey || (config.provider === 'gemini' && config.apiKey)) {
|
|
41
|
+
provider = 'gemini';
|
|
42
|
+
model = model || 'veo-2.0-generate-001';
|
|
43
|
+
} else if (config.dashscopeApiKey || (config.provider === 'qwen' && config.apiKey)) {
|
|
44
|
+
provider = 'qwen';
|
|
45
|
+
model = model || 'wanx-v2.1-t2v-turbo';
|
|
46
|
+
} else if (config.openaiApiKey || (config.provider === 'openai' && config.apiKey)) {
|
|
47
|
+
provider = 'openai';
|
|
48
|
+
model = model || 'sora-2';
|
|
49
|
+
// Fallback to Sovereign 5-Stage Hierarchy when no video API keys exist
|
|
50
|
+
return {
|
|
51
|
+
success: true,
|
|
52
|
+
mode: 'Fallback (Sovereign 5-Stage Hierarchy)',
|
|
53
|
+
message: `No paid video generation API key (Gemini/Qwen/OpenAI) configured. Stage 2 Fallback: Please invoke 'check_system_specs' FIRST to verify if local hardware (RAM >= 8GB, Disk > 10GB) can run local video models via 'manage_local_ai_dependencies'. If local hardware is insufficient or declined, transition to Stage 4 (web_search + web_fetch for stock video assets) or Stage 5 (execute_procedural_media Mode A for HTML5 Canvas/Python animation).`
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
} else if (mediaType === 'image') {
|
|
57
|
+
// Muse Image first when the session is already on Meta Model API: same key,
|
|
58
|
+
// same base URL, and $0.01 an image is the cheapest paid route here by a
|
|
59
|
+
// wide margin. It is checked before the others so a Muse user is not sent
|
|
60
|
+
// to a second vendor they never configured.
|
|
61
|
+
if (config.museApiKey || ((config.provider === 'muse' || config.provider === 'meta') && config.apiKey)) {
|
|
62
|
+
provider = 'muse';
|
|
63
|
+
model = model || 'muse-image-1.0';
|
|
64
|
+
} else if (config.geminiApiKey || (config.provider === 'gemini' && config.apiKey)) {
|
|
65
|
+
provider = 'gemini';
|
|
66
|
+
model = model || 'imagen-3.0-generate-002';
|
|
67
|
+
} else if (config.openaiApiKey || (config.provider === 'openai' && config.apiKey)) {
|
|
68
|
+
provider = 'openai';
|
|
69
|
+
model = model || 'dall-e-3';
|
|
70
|
+
} else {
|
|
71
|
+
provider = 'pollinations';
|
|
72
|
+
model = model || 'flux';
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// If routing to Pollinations or Free Mode, return null so standard execution continues
|
|
78
|
+
if (provider === 'pollinations' || provider === 'local' || !['gemini', 'openai', 'qwen', 'muse'].includes(provider)) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Calculate estimated cost and equivalent tokens
|
|
83
|
+
const quantity = mediaType === 'video_animation' ? durationSeconds : 1;
|
|
84
|
+
const unitPrice = tokenTracker.getMediaPricing(provider, model || '', mediaType);
|
|
85
|
+
const estimatedCost = unitPrice * quantity;
|
|
86
|
+
const estimatedTokens = Math.round(estimatedCost / 0.000002);
|
|
87
|
+
|
|
88
|
+
// Pre-Flight Consent Modal (`approval_request`) for Paid API Handoffs (unless in Mode C/Super Max and pre-approved)
|
|
89
|
+
if (sandbox && typeof sandbox.waitForApproval === 'function') {
|
|
90
|
+
// The paid-media consent modal is skipped in Mode C (pre-approved) and in
|
|
91
|
+
// hardened developer emulator mode (secret-gated — see devMode.js).
|
|
92
|
+
if (!isDevEmulator(config) && config.autonomyMode !== 'C') {
|
|
93
|
+
if (typeof sandbox.emitEvent === 'function') {
|
|
94
|
+
sandbox.emitEvent({
|
|
95
|
+
type: 'approval_request',
|
|
96
|
+
toolCallId: `media_${Date.now()}`,
|
|
97
|
+
tool: 'generate_media_via_api (Auto-Switch)',
|
|
98
|
+
args: {
|
|
99
|
+
targetProvider: provider.toUpperCase(),
|
|
100
|
+
targetModel: model,
|
|
101
|
+
mediaType,
|
|
102
|
+
prompt,
|
|
103
|
+
estimatedCostUsd: `$${estimatedCost.toFixed(2)}`,
|
|
104
|
+
estimatedTokens: `~${estimatedTokens.toLocaleString()} Equivalent Tokens`
|
|
105
|
+
},
|
|
106
|
+
risk: 'monetary_cost'
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const approved = await sandbox.waitForApproval(`media_${Date.now()}`);
|
|
111
|
+
if (!approved) {
|
|
112
|
+
// User denied paid API -> Seamless routing across Sovereign 5-Stage Hierarchy
|
|
113
|
+
if (mediaType === 'image') {
|
|
114
|
+
return {
|
|
115
|
+
fallbackToPollinations: true,
|
|
116
|
+
message: `User denied Stage 1 paid API switch ($${estimatedCost.toFixed(2)}). Note: If local hardware allows and user prefers local processing, you may run 'check_system_specs' for Stage 2 (Local Stable Diffusion). Otherwise, auto-routing to free Pollinations.ai Mode D (Stage 3).`
|
|
117
|
+
};
|
|
118
|
+
} else {
|
|
119
|
+
return {
|
|
120
|
+
success: true,
|
|
121
|
+
mode: 'Fallback (Stage 2 / Stage 4 / Stage 5)',
|
|
122
|
+
message: `User denied Stage 1 paid API switch ($${estimatedCost.toFixed(2)}). Stage 2 Fallback: Please invoke 'check_system_specs' right now. If RAM >= 8GB and Disk > 10GB, propose local processing via 'manage_local_ai_dependencies' (e.g., Kokoro TTS/diffusers/whisper.cpp). If hardware is insufficient or user prefers no local downloads, transition to Stage 4 (web_search for existing royalty-free assets) or Stage 5 (execute_procedural_media Mode A).`
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Enforce budget kill-switch and track usage
|
|
130
|
+
const tracking = await tokenTracker.trackMediaUsage(provider, mediaType, model, quantity);
|
|
131
|
+
if (!tracking.allowed) {
|
|
132
|
+
return {
|
|
133
|
+
success: false,
|
|
134
|
+
error: tracking.reason || `Monetary budget exceeded for ${provider} media generation ($${estimatedCost.toFixed(2)}).`
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Execute actual REST call to the specialized provider (Gemini / OpenAI / Qwen)
|
|
139
|
+
let targetUrl = '';
|
|
140
|
+
let apiKey = config[`${provider}ApiKey`] || config.apiKey;
|
|
141
|
+
let headers = { 'Content-Type': 'application/json' };
|
|
142
|
+
let body = {};
|
|
143
|
+
|
|
144
|
+
if (provider === 'gemini') {
|
|
145
|
+
if (mediaType === 'video_animation') {
|
|
146
|
+
targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict?key=${apiKey}`;
|
|
147
|
+
body = { instances: [{ prompt }], parameters: { durationSeconds } };
|
|
148
|
+
} else {
|
|
149
|
+
targetUrl = `https://generativelanguage.googleapis.com/v1beta/models/${model}:predict?key=${apiKey}`;
|
|
150
|
+
body = { instances: [{ prompt }], parameters: { sampleCount: 1 } };
|
|
151
|
+
}
|
|
152
|
+
} else if (provider === 'muse') {
|
|
153
|
+
// Muse Image is the only model in the family that outputs images, and there
|
|
154
|
+
// is no video model at all — a video request must fall through to the
|
|
155
|
+
// sovereign hierarchy rather than be billed against an image endpoint.
|
|
156
|
+
if (mediaType !== 'image') return null;
|
|
157
|
+
targetUrl = 'https://api.meta.ai/v1/images/generations';
|
|
158
|
+
headers['Authorization'] = `Bearer ${apiKey}`;
|
|
159
|
+
body = { model: model || 'muse-image-1.0', prompt, n: 1, response_format: 'b64_json' };
|
|
160
|
+
} else if (provider === 'openai') {
|
|
161
|
+
if (mediaType === 'image') {
|
|
162
|
+
targetUrl = 'https://api.openai.com/v1/images/generations';
|
|
163
|
+
headers['Authorization'] = `Bearer ${apiKey}`;
|
|
164
|
+
body = { model: model || 'dall-e-3', prompt, n: 1, response_format: 'b64_json' };
|
|
165
|
+
} else {
|
|
166
|
+
targetUrl = 'https://api.openai.com/v1/video/generations';
|
|
167
|
+
headers['Authorization'] = `Bearer ${apiKey}`;
|
|
168
|
+
body = { model: model || 'sora-2', prompt };
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const response = await fetch(targetUrl, { method: 'POST', headers, body: JSON.stringify(body) });
|
|
173
|
+
if (!response.ok) {
|
|
174
|
+
const errText = await response.text();
|
|
175
|
+
// If API endpoint is unreachable or fails, fallback gracefully if image
|
|
176
|
+
if (mediaType === 'image') {
|
|
177
|
+
return {
|
|
178
|
+
fallbackToPollinations: true,
|
|
179
|
+
message: `Specialized provider (${provider}) returned error: ${response.status}. Falling back to free Pollinations.ai Mode D.`
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
throw new Error(`Specialized ${provider} API failure (${response.status}): ${errText}`);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const data = await response.json();
|
|
186
|
+
let buffer = null;
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
if ((provider === 'openai' || provider === 'muse') && data.data && data.data[0]?.b64_json) {
|
|
190
|
+
buffer = Buffer.from(data.data[0].b64_json, 'base64');
|
|
191
|
+
} else if (provider === 'gemini' && data.predictions && data.predictions[0]?.bytesBase64Encoded) {
|
|
192
|
+
buffer = Buffer.from(data.predictions[0].bytesBase64Encoded, 'base64');
|
|
193
|
+
} else if (data.url || (data.data && data.data[0]?.url)) {
|
|
194
|
+
const mediaUrl = data.url || data.data[0].url;
|
|
195
|
+
const mediaResp = await fetch(mediaUrl);
|
|
196
|
+
const ab = await mediaResp.arrayBuffer();
|
|
197
|
+
buffer = Buffer.from(ab);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (!buffer || !validateMagicNumbers(buffer)) {
|
|
201
|
+
if (mediaType === 'image') {
|
|
202
|
+
return { fallbackToPollinations: true, message: `Invalid buffer from ${provider}. Falling back to Pollinations.ai.` };
|
|
203
|
+
}
|
|
204
|
+
throw new Error(`Failed to extract valid media buffer from ${provider} API response.`);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return {
|
|
208
|
+
success: true,
|
|
209
|
+
buffer,
|
|
210
|
+
provider,
|
|
211
|
+
model,
|
|
212
|
+
costUsd: estimatedCost,
|
|
213
|
+
equivalentTokens: estimatedTokens
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export const generateMediaViaApi = {
|
|
218
|
+
schema: {
|
|
219
|
+
name: 'generate_media_via_api',
|
|
220
|
+
description: 'Mode D / Auto-Router: Generate validated images, audio TTS, or video animations. Supports automatic multi-provider handoff (Gemini Veo/Imagen, DALL-E 3, Qwen Wan) with interactive user approval and free fallback.',
|
|
221
|
+
parameters: {
|
|
222
|
+
type: 'object',
|
|
223
|
+
properties: {
|
|
224
|
+
mediaType: { type: 'string', enum: ['image', 'audio_tts', 'video_animation'] },
|
|
225
|
+
prompt: { type: 'string' },
|
|
226
|
+
outputPath: { type: 'string' },
|
|
227
|
+
width: { type: 'number' },
|
|
228
|
+
height: { type: 'number' },
|
|
229
|
+
model: { type: 'string' },
|
|
230
|
+
voice: { type: 'string' },
|
|
231
|
+
targetProvider: { type: 'string', enum: ['auto', 'gemini', 'openai', 'qwen', 'pollinations'], description: 'Optional provider routing for specialized models.' },
|
|
232
|
+
targetModel: { type: 'string', description: 'Optional exact model name (e.g. veo-2.0-generate-001, imagen-3.0-generate-002, dall-e-3).' },
|
|
233
|
+
durationSeconds: { type: 'number', description: 'Duration in seconds for video animations (default 5).' }
|
|
234
|
+
},
|
|
235
|
+
required: ['mediaType', 'prompt', 'outputPath']
|
|
236
|
+
}
|
|
237
|
+
},
|
|
238
|
+
|
|
239
|
+
execute: async (args, sandbox) => {
|
|
240
|
+
try {
|
|
241
|
+
const { mediaType, prompt, width, height, model, voice, targetProvider, targetModel, durationSeconds } = args;
|
|
242
|
+
let outputPath = args.outputPath.replace(/^~\//, os.homedir() + '/');
|
|
243
|
+
outputPath = path.resolve(outputPath);
|
|
244
|
+
|
|
245
|
+
if (sandbox && sandbox.isPathAllowed && !sandbox.isPathAllowed(outputPath)) {
|
|
246
|
+
return { success: false, error: `Path outside allowed workspace: ${outputPath}` };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const outputDir = path.dirname(outputPath);
|
|
250
|
+
if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
|
|
251
|
+
if (!fs.existsSync(CACHE_DIR)) fs.mkdirSync(CACHE_DIR, { recursive: true });
|
|
252
|
+
|
|
253
|
+
// Phase 5 AGI Upgrade: Caching Layer
|
|
254
|
+
const promptHash = crypto.createHash('sha256').update(`${mediaType}_${prompt}_${model || targetModel}_${voice || targetProvider}`).digest('hex');
|
|
255
|
+
const cachedFile = path.join(CACHE_DIR, promptHash);
|
|
256
|
+
if (fs.existsSync(cachedFile)) {
|
|
257
|
+
fs.copyFileSync(cachedFile, outputPath);
|
|
258
|
+
return { success: true, message: `Cache Hit: Loaded instantly from local AI cache. Saved to ${outputPath}`, mode: 'D / Router (Cached)' };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const config = loadConfig();
|
|
262
|
+
const tokenTracker = new TokenTracker();
|
|
263
|
+
|
|
264
|
+
// Attempt specialized AGI Auto-Routing first
|
|
265
|
+
const routeResult = await routeMultimediaRequest(args, config, sandbox, tokenTracker);
|
|
266
|
+
if (routeResult) {
|
|
267
|
+
if (routeResult.fallbackToPollinations !== true) {
|
|
268
|
+
if (!routeResult.buffer && routeResult.success) {
|
|
269
|
+
// Handled fallback message (e.g. Mode A recommendation)
|
|
270
|
+
return routeResult;
|
|
271
|
+
}
|
|
272
|
+
if (routeResult.buffer) {
|
|
273
|
+
fs.writeFileSync(cachedFile, routeResult.buffer);
|
|
274
|
+
fs.writeFileSync(outputPath, routeResult.buffer);
|
|
275
|
+
return {
|
|
276
|
+
success: true,
|
|
277
|
+
message: `Media generated and validated via ${routeResult.provider.toUpperCase()} (${routeResult.model}). Cost: $${routeResult.costUsd.toFixed(2)} (~${routeResult.equivalentTokens} Equivalent Tokens). Saved to ${outputPath}`,
|
|
278
|
+
sizeBytes: routeResult.buffer.length,
|
|
279
|
+
mode: `Auto-Switch (${routeResult.provider.toUpperCase()})`
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
if (routeResult.error) return routeResult;
|
|
283
|
+
}
|
|
284
|
+
// If routeResult.fallbackToPollinations is true, we proceed right into Pollinations below!
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Default / Fallback: Pollinations.ai Mode D
|
|
288
|
+
let targetUrl = '';
|
|
289
|
+
let fetchOptions = {};
|
|
290
|
+
|
|
291
|
+
if (mediaType === 'image') {
|
|
292
|
+
const imgWidth = width || 1024;
|
|
293
|
+
const imgHeight = height || 1024;
|
|
294
|
+
const imgModel = model || 'flux';
|
|
295
|
+
targetUrl = `https://image.pollinations.ai/prompt/${encodeURIComponent(prompt)}?width=${imgWidth}&height=${imgHeight}&model=${imgModel}&nologo=true&seed=${Date.now()}`;
|
|
296
|
+
} else if (mediaType === 'audio_tts') {
|
|
297
|
+
targetUrl = `https://api.pollinations.ai/tts?text=${encodeURIComponent(prompt)}&voice=${voice || 'nova'}`;
|
|
298
|
+
} else {
|
|
299
|
+
// Fallback across Sovereign 5-Stage Hierarchy when video_animation/music is routed to Pollinations
|
|
300
|
+
return {
|
|
301
|
+
success: true,
|
|
302
|
+
mode: 'Fallback (Stage 2 / Stage 4 / Stage 5)',
|
|
303
|
+
message: `Pollinations.ai (Stage 3) does not natively generate video animations or instrumental music directly. Stage 2 Fallback: Please invoke 'check_system_specs' right now to verify if local hardware (RAM >= 8GB) can run local models via 'manage_local_ai_dependencies'. If local hardware is insufficient or declined, transition to Stage 4 (web_search + web_fetch for stock video/music assets) or Stage 5 (execute_procedural_media Mode A for HTML5 Canvas/Python animation or WAV audio).`
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Phase 5 AGI Upgrade: Auto-Retry Loop (3 retries, exponential backoff)
|
|
308
|
+
let buffer = null;
|
|
309
|
+
let attempts = 0;
|
|
310
|
+
let lastError = '';
|
|
311
|
+
|
|
312
|
+
while (attempts < 3) {
|
|
313
|
+
attempts++;
|
|
314
|
+
try {
|
|
315
|
+
const response = await fetch(targetUrl, fetchOptions);
|
|
316
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
317
|
+
|
|
318
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
319
|
+
buffer = Buffer.from(arrayBuffer);
|
|
320
|
+
|
|
321
|
+
// Phase 5 AGI Upgrade: Magic Number Verification
|
|
322
|
+
if (!validateMagicNumbers(buffer)) {
|
|
323
|
+
throw new Error(`Invalid Magic Numbers (Corrupted/Unsupported format returned). Length: ${buffer.length}`);
|
|
324
|
+
}
|
|
325
|
+
break; // Success
|
|
326
|
+
} catch (e) {
|
|
327
|
+
lastError = e.message;
|
|
328
|
+
if (attempts < 3) {
|
|
329
|
+
await new Promise(res => setTimeout(res, attempts * 2000)); // Exponential backoff 2s, 4s
|
|
330
|
+
}
|
|
331
|
+
}
|
|
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
|
+
}
|
|
357
|
+
}
|
|
358
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { exec } from 'child_process';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
|
|
4
|
+
export const gitExec = {
|
|
5
|
+
schema: {
|
|
6
|
+
name: 'gitOp',
|
|
7
|
+
description: 'Execute a git command securely. Features autonomous conflict detection and HitL interception for destructive commands.',
|
|
8
|
+
parameters: {
|
|
9
|
+
type: 'object',
|
|
10
|
+
properties: {
|
|
11
|
+
command: { type: 'string', description: 'Git subcommand (e.g., "status", "commit -m init")' },
|
|
12
|
+
cwd: { type: 'string' }
|
|
13
|
+
},
|
|
14
|
+
required: ['command']
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
async execute(args) {
|
|
18
|
+
const cwd = (args.cwd || process.cwd()).replace(/^~\//, os.homedir() + '/');
|
|
19
|
+
let cmdString = args.command;
|
|
20
|
+
|
|
21
|
+
// Phase 5 AGI Upgrade: Boundary Conditions
|
|
22
|
+
if (cmdString.includes('-i') || cmdString.includes('interactive')) {
|
|
23
|
+
return { success: false, error: 'Interactive workflows (e.g., rebase -i) are strictly forbidden in AGI automation. Use precise non-interactive commands.' };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
if (cmdString.includes('push -f') || cmdString.includes('push --force') || cmdString.includes('branch -D')) {
|
|
27
|
+
return { success: false, error: '[HITL_APPROVAL_REQUIRED] Destructive Git action detected. You must ask the user for explicit permission before running this.' };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const command = `git ${cmdString}`;
|
|
31
|
+
|
|
32
|
+
return new Promise((resolve) => {
|
|
33
|
+
exec(command, { cwd, maxBuffer: 5 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
34
|
+
const fullOutput = (stdout || '') + '\n' + (stderr || '');
|
|
35
|
+
|
|
36
|
+
// Phase 5 AGI Upgrade: Autonomous Conflict Detection
|
|
37
|
+
if (fullOutput.includes('CONFLICT (content): Merge conflict')) {
|
|
38
|
+
resolve({
|
|
39
|
+
success: false,
|
|
40
|
+
error: `[AUTONOMOUS CONFLICT DETECTED]\nGit merge conflict occurred. DO NOT PANIC.\n1. Use fs.read to read the conflicted files.\n2. Analyze the <<<<<<< HEAD markers.\n3. Use fs.edit to surgically resolve the conflict.\n4. Run git add and git commit.`,
|
|
41
|
+
output: fullOutput
|
|
42
|
+
});
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (error) {
|
|
47
|
+
resolve({ success: false, output: stdout, error: stderr || error.message, exitCode: error.code });
|
|
48
|
+
} else {
|
|
49
|
+
resolve({ success: true, output: stdout || stderr, exitCode: 0 });
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
};
|