-
Notifications
You must be signed in to change notification settings - Fork 3.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Add Akash Network plugin with autonomous deployment capabilities #2111
feat: Add Akash Network plugin with autonomous deployment capabilities #2111
Conversation
All conflicts fixed. |
Added also the full new .env.example |
📝 WalkthroughWalkthroughThe pull request introduces the Akash Network Plugin for the Eliza platform, adding comprehensive functionality for managing cloud deployments and interactions with the Akash decentralized cloud network. The changes include configuration management, wallet handling, deployment actions, provider queries, and robust error handling across multiple files and components. Changes
Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
@coderabbitai review |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 14
♻️ Duplicate comments (1)
packages/plugin-akash/src/actions/createDeployment.ts (1)
610-610
:⚠️ Potential issueAvoid disabling certificate validation
Setting
rejectUnauthorized: false
at lines 610 and 748 disables SSL certificate validation, exposing the application to security risks.Also applies to: 748-748
🧹 Nitpick comments (23)
packages/plugin-akash/src/actions/getProvidersList.ts (1)
73-74
: Validate API response structureAfter parsing the JSON response, ensure
data
conforms to the expectedProviderInfo[]
structure before returning it to prevent potential runtime errors.packages/plugin-akash/src/actions/estimateGas.ts (1)
217-221
: Add error handling for gas simulationWrap the
client.simulate
call in a try-catch block to handle potential exceptions, ensuring the application can gracefully handle simulation failures.packages/plugin-akash/src/environment.ts (1)
169-199
: Clean up commented-out codeRemove the commented code from lines 169 to 199 to maintain code clarity and reduce clutter.
packages/plugin-akash/src/actions/getProviderInfo.ts (1)
293-302
: Refine error detection for invalid provider addressesChecking for "invalid address" in the error message may not capture all cases of address validation errors. Consider using a more precise method to detect invalid provider addresses, such as inspecting error codes or using specific exceptions.
packages/plugin-akash/src/actions/getManifest.ts (1)
44-90
: Simplify SDL file loading logicThe
loadSDLFromFile
function attempts multiple paths to locate the SDL file, which can be error-prone and hard to maintain. Simplify the path resolution logic and provide clearer error messages if the file is not found.packages/plugin-akash/src/actions/createCertificate.ts (2)
308-326
: Validate existing certificates before reuseThe code checks for the existence of a certificate file but doesn't validate its content. The existing certificate might be invalid or corrupted. Implement validation of the certificate content before deciding to reuse it.
353-369
: Implement retry logic for certificate broadcastingWhen broadcasting the certificate, transient network issues may cause failures. Incorporate retry logic to enhance reliability and ensure the certificate is broadcast successfully.
packages/plugin-akash/src/actions/getDeploymentApi.ts (2)
260-261
: Use asynchronous file operations to avoid blocking.Switch from
fs.writeFileSync
andfs.readFileSync
to their asynchronous versions to prevent blocking the event loop.Update
saveDeploymentInfo
andloadDeploymentInfo
:- fs.writeFileSync(filePath, JSON.stringify(deploymentInfo, null, 2), 'utf8'); + await fs.promises.writeFile(filePath, JSON.stringify(deploymentInfo, null, 2), 'utf8');- const data = fs.readFileSync(filePath, 'utf8'); + const data = await fs.promises.readFile(filePath, 'utf8');Ensure the functions are marked as
async
.Also applies to: 284-285
276-276
: Remove redundant 'fs' import inside the function.The
fs
module is already imported at the top; no need to require it again inloadDeploymentInfo
.Apply this diff:
- const fs = require('fs');
packages/plugin-akash/src/actions/closeDeployment.ts (1)
191-203
: Optimize deployment closure by processing in parallel.In
closeAllDeployments
, deployments are closed sequentially. Improve efficiency by closing them in parallel.Modify the loop to use
Promise.all
:- for (const deployment of activeDeployments) { - try { - await closeSingleDeployment(runtime, deployment.dseq); - results.success.push(deployment.dseq); - } catch (error) { - results.failed.push(deployment.dseq); - } - } + await Promise.all(activeDeployments.map(async (deployment) => { + try { + await closeSingleDeployment(runtime, deployment.dseq); + results.success.push(deployment.dseq); + } catch (error) { + results.failed.push(deployment.dseq); + } + }));packages/plugin-akash/src/actions/getDeploymentStatus.ts (1)
93-95
: Enhance regex pattern for extracting DSEQ.The current regex may not capture all formats. Expand it to be more flexible.
Update the regex:
- const dseqMatch = params.text.match(/(?:DSEQ|dseq)\s*(\d+)/i); + const dseqMatch = params.text.match(/(?:DSEQ|dseq)\s*[:=]?\s*(\d+)/i);This allows formats like
DSEQ:123456
ordseq=123456
.packages/plugin-akash/src/actions/createDeployment.ts (1)
342-342
: Remove unnecessarycontinue
statementsThe
continue;
statements at lines 342, 352, 445, and 480 are redundant as they are at the end of their respective loop iterations. Removing them will simplify the code.Apply these diffs:
At line 342:
- continue;
At line 352:
- continue;
At line 445:
- continue;
At line 480:
- continue;
Also applies to: 352-352, 445-445, 480-480
🧰 Tools
🪛 Biome (1.9.4)
[error] 342-342: Unnecessary continue statement
Unsafe fix: Delete the unnecessary continue statement
(lint/correctness/noUnnecessaryContinue)
packages/plugin-akash/jest.config.js (1)
1-31
: Consider consolidating testing frameworksBoth Vitest and Jest configurations are present. Maintaining both may lead to redundancy. Consider using a single testing framework for consistency.
packages/plugin-akash/.eslintrc.js (1)
28-28
: Consider more specific ignore patternsThe current ignore patterns might be too broad. Consider using more specific patterns like
'dist/**/*'
and excluding test files explicitly.- ignorePatterns: ['dist/', 'node_modules/', '*.js', '*.mjs', '*.cjs'], + ignorePatterns: ['dist/**/*', 'node_modules/**/*', '!.eslintrc.js', '!jest.config.js'],packages/plugin-akash/src/error/error.ts (1)
109-126
: Enhance withRetry with abort signal and error filteringConsider adding abort signal support and the ability to filter which errors should trigger retries.
export async function withRetry<T>( fn: () => Promise<T>, maxRetries: number = 3, - delay: number = 1000 + delay: number = 1000, + options?: { + signal?: AbortSignal; + shouldRetry?: (error: Error) => boolean; + } ): Promise<T> { let lastError: Error | undefined; for (let i = 0; i < maxRetries; i++) { + if (options?.signal?.aborted) { + throw new Error('Operation aborted'); + } try { return await fn(); } catch (error) { lastError = error as Error; + if (options?.shouldRetry && !options.shouldRetry(lastError)) { + throw lastError; + } if (i < maxRetries - 1) { await new Promise(resolve => setTimeout(resolve, delay * Math.pow(2, i))); } } } throw lastError; }packages/plugin-akash/src/utils/paths.ts (3)
8-45
: Add maximum depth limit to directory traversal.The while loop could potentially traverse up to the root directory. Consider adding a maximum depth limit to prevent excessive traversal.
export const getPluginRoot = (importMetaUrl: string) => { + const MAX_DEPTH = 10; + let depth = 0; const currentFileUrl = importMetaUrl; const currentFilePath = fileURLToPath(currentFileUrl); const currentDir = path.dirname(currentFilePath); let dir = currentDir; - while (dir && path.basename(dir) !== 'plugin-akash' && dir !== '/') { + while (dir && path.basename(dir) !== 'plugin-akash' && dir !== '/' && depth < MAX_DEPTH) { dir = path.dirname(dir); + depth++; } - if (!dir || dir === '/') { + if (!dir || dir === '/' || depth >= MAX_DEPTH) { elizaLogger.error("Could not find plugin-akash directory", { currentFilePath, currentDir, - searchPath: dir + searchPath: dir, + depth }); throw new Error("Could not find plugin-akash directory"); }
64-75
: Add directory existence check.The function assumes the
.certificates
directory exists. Consider adding a check and creating the directory if needed.export const getCertificatePath = (importMetaUrl: string) => { const srcPath = getSrcPath(importMetaUrl); - const certPath = path.join(srcPath, '.certificates', 'cert.json'); + const certDir = path.join(srcPath, '.certificates'); + if (!existsSync(certDir)) { + fs.mkdirSync(certDir, { recursive: true }); + } + const certPath = path.join(certDir, 'cert.json'); return certPath; };
77-112
: Enable warning log for missing SDL file.The warning log for missing SDL file is commented out. This could help users identify configuration issues.
if (!existsSync(sdlPath)) { - // elizaLogger.warn("SDL file not found at expected path", { - // sdlPath, - // exists: false - // }); + elizaLogger.warn("SDL file not found at expected path", { + sdlPath, + exists: false + }); }packages/plugin-akash/readme.md (2)
58-60
: Add language specifications to code blocksThe code blocks should specify their language for better syntax highlighting and documentation clarity.
-``` +```bash src/sdl/example.sdl.yml-
+
bash
src/.certificates/Also applies to: 64-66
🧰 Tools
🪛 Markdownlint (0.37.0)
58-58: null
Fenced code blocks should have a language specified(MD040, fenced-code-language)
108-114
: Add consistent punctuation in error codes listEach error description should end with a period for consistency.
-VALIDATION_SDL_FAILED`: SDL validation errors -WALLET_NOT_INITIALIZED`: Wallet setup issues -DEPLOYMENT_CREATION_FAILED`: Deployment failures -API_REQUEST_FAILED`: Network/API issues -MANIFEST_PARSING_FAILED`: Manifest generation errors -PROVIDER_FILTER_ERROR`: Provider filtering issues +VALIDATION_SDL_FAILED`: SDL validation errors. +WALLET_NOT_INITIALIZED`: Wallet setup issues. +DEPLOYMENT_CREATION_FAILED`: Deployment failures. +API_REQUEST_FAILED`: Network/API issues. +MANIFEST_PARSING_FAILED`: Manifest generation errors. +PROVIDER_FILTER_ERROR`: Provider filtering issues.🧰 Tools
🪛 LanguageTool
[uncategorized] ~108-~108: Loose punctuation mark.
Context: ... error codes: -VALIDATION_SDL_FAILED
: SDL validation errors - `WALLET_NOT_INI...(UNLIKELY_OPENING_PUNCTUATION)
.env.example (3)
492-493
: Add security warning for sensitive valuesThe
AKASH_MNEMONIC
andAKASH_WALLET_ADDRESS
are sensitive values. Add a warning comment about their secure handling.-AKASH_MNEMONIC= -AKASH_WALLET_ADDRESS= +# WARNING: Keep these values secure and never commit them to version control +AKASH_MNEMONIC= # Your 12-word mnemonic phrase +AKASH_WALLET_ADDRESS= # Your Akash wallet address
496-499
: Clarify default value commentsThe default values comment could be clearer about the units and formatting.
-# Default values # 1 CPU = 1000 1GB = 1000000000 1GB = 1000000000 +# Default resource values: +# CPU: 1000 millicores (1 core) +# Memory: 1000000000 bytes (1 GB) +# Storage: 1000000000 bytes (1 GB)
509-511
: Fix typo in commentThere's a typo in the deployment status comment.
-# you can pass the dseq using AKASH_DEP_DSEQ 19729929 is an example of a dseq we test while build. +# You can pass the dseq using AKASH_DEP_DSEQ. 19729929 is an example of a dseq we test during build.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
packages/plugin-akash/assets/akash.jpg
is excluded by!**/*.jpg
📒 Files selected for processing (30)
.env.example
(1 hunks)agent/package.json
(1 hunks)agent/src/index.ts
(2 hunks)packages/plugin-akash/.eslintrc.js
(1 hunks)packages/plugin-akash/.npmignore
(1 hunks)packages/plugin-akash/eslint.config.mjs
(1 hunks)packages/plugin-akash/jest.config.js
(1 hunks)packages/plugin-akash/package.json
(1 hunks)packages/plugin-akash/readme.md
(1 hunks)packages/plugin-akash/src/actions/closeDeployment.ts
(1 hunks)packages/plugin-akash/src/actions/createCertificate.ts
(1 hunks)packages/plugin-akash/src/actions/createDeployment.ts
(1 hunks)packages/plugin-akash/src/actions/estimateGas.ts
(1 hunks)packages/plugin-akash/src/actions/getDeploymentApi.ts
(1 hunks)packages/plugin-akash/src/actions/getDeploymentStatus.ts
(1 hunks)packages/plugin-akash/src/actions/getGPUPricing.ts
(1 hunks)packages/plugin-akash/src/actions/getManifest.ts
(1 hunks)packages/plugin-akash/src/actions/getProviderInfo.ts
(1 hunks)packages/plugin-akash/src/actions/getProvidersList.ts
(1 hunks)packages/plugin-akash/src/environment.ts
(1 hunks)packages/plugin-akash/src/error/error.ts
(1 hunks)packages/plugin-akash/src/index.ts
(1 hunks)packages/plugin-akash/src/providers/wallet.ts
(1 hunks)packages/plugin-akash/src/runtime_inspect.ts
(1 hunks)packages/plugin-akash/src/sdl/example.sdl.yml
(1 hunks)packages/plugin-akash/src/types.ts
(1 hunks)packages/plugin-akash/src/utils/paths.ts
(1 hunks)packages/plugin-akash/tsconfig.json
(1 hunks)packages/plugin-akash/tsup.config.ts
(1 hunks)packages/plugin-akash/vitest.config.ts
(1 hunks)
✅ Files skipped from review due to trivial changes (4)
- packages/plugin-akash/.npmignore
- packages/plugin-akash/eslint.config.mjs
- packages/plugin-akash/tsup.config.ts
- packages/plugin-akash/package.json
🧰 Additional context used
🪛 LanguageTool
packages/plugin-akash/readme.md
[uncategorized] ~108-~108: Loose punctuation mark.
Context: ... error codes: - VALIDATION_SDL_FAILED
: SDL validation errors - `WALLET_NOT_INI...
(UNLIKELY_OPENING_PUNCTUATION)
🪛 Markdownlint (0.37.0)
packages/plugin-akash/readme.md
58-58: null
Fenced code blocks should have a language specified
(MD040, fenced-code-language)
64-64: null
Fenced code blocks should have a language specified
(MD040, fenced-code-language)
8-8: null
Link fragments should be valid
(MD051, link-fragments)
🪛 Biome (1.9.4)
packages/plugin-akash/src/actions/getGPUPricing.ts
[error] 67-67: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.
See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.
(lint/suspicious/noGlobalIsNan)
[error] 72-72: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.
See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.
(lint/suspicious/noGlobalIsNan)
[error] 77-77: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.
See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.
(lint/suspicious/noGlobalIsNan)
packages/plugin-akash/src/actions/createDeployment.ts
[error] 342-342: Unnecessary continue statement
Unsafe fix: Delete the unnecessary continue statement
(lint/correctness/noUnnecessaryContinue)
[error] 352-352: Unnecessary continue statement
Unsafe fix: Delete the unnecessary continue statement
(lint/correctness/noUnnecessaryContinue)
[error] 445-445: Unnecessary continue statement
Unsafe fix: Delete the unnecessary continue statement
(lint/correctness/noUnnecessaryContinue)
[error] 480-480: Unnecessary continue statement
Unsafe fix: Delete the unnecessary continue statement
(lint/correctness/noUnnecessaryContinue)
🔇 Additional comments (9)
packages/plugin-akash/tsconfig.json (1)
1-2
: LGTM! Good practice extending the base configuration.Extending the root tsconfig ensures consistency across packages.
packages/plugin-akash/src/providers/wallet.ts (1)
57-71
:⚠️ Potential issueAvoid storing sensitive wallet data in memory
Storing the
wallet
object, which contains private keys, in memory may pose a security risk. It is advisable to store only non-sensitive information likeaddress
andclient
, and manage thewallet
instance within the provider without persisting it.Apply this diff to prevent storing sensitive data:
const state: AkashWalletState = { - wallet, client, address, };
Likely invalid or redundant comment.
packages/plugin-akash/src/types.ts (1)
1-167
: Type definitions are well-structured and comprehensiveThe type declarations provide a clear and robust structure for the Akash plugin, enhancing type safety and maintainability.
packages/plugin-akash/vitest.config.ts (1)
1-27
: Configuration looks goodThe Vitest configuration is properly set up for the testing environment.
packages/plugin-akash/src/utils/paths.ts (1)
47-62
: LGTM!The function correctly resolves the src path using the plugin root.
agent/src/index.ts (1)
736-739
: LGTM!The Akash plugin is correctly conditioned on the presence of required environment variables.
packages/plugin-akash/src/sdl/example.sdl.yml (2)
14-20
: Consider resource limits for production use.The current resource allocation (0.5 CPU, 512Mi memory/storage) might be insufficient for production workloads.
Consider adjusting based on your application's requirements.
23-26
: Verify pricing configuration.The pricing amount of 20000 uakt should be verified against current market rates.
Run this script to check current market rates:
✅ Verification successful
Example pricing configuration verified against documentation
The amount of 20000 uakt matches the default fees documented in the plugin's configuration, making it a valid reference implementation.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check current market rates for similar deployments rg -A 5 'amount:\s*20000' | grep -B 5 'denom:\s*uakt'Length of output: 55
Script:
#!/bin/bash # Find all SDL and YAML files with pricing configurations echo "=== Looking for SDL files with pricing configs ===" fd -e yml -e yaml | xargs rg -l 'pricing:|denom:|amount:' echo -e "\n=== Searching for pricing documentation ===" rg -l -g '*.md' -i 'pricing|amount|denom|uakt' echo -e "\n=== Looking for specific amount patterns ===" rg -A 3 -B 3 'denom:\s*uakt'Length of output: 3492
Script:
#!/bin/bash # Check plugin documentation for pricing guidance echo "=== Checking Akash plugin documentation ===" cat packages/plugin-akash/readme.md echo -e "\n=== Checking for pricing comments in the example file ===" cat packages/plugin-akash/src/sdl/example.sdl.ymlLength of output: 5120
agent/package.json (1)
87-87
: LGTM!The Akash plugin dependency is correctly added with workspace versioning.
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
…lugin-01 feat: Add Akash Network plugin with autonomous deployment capabilities
Akash Network Plugin for Eliza Framework
Overview
This plugin enables the Eliza Framework to autonomously interact with the Akash Network, providing automated deployment and management capabilities for decentralized cloud computing resources.
Features
The plugin provides a comprehensive set of actions that allow Eliza to:
Deployment Management
CREATE_DEPLOYMENT
)CLOSE_DEPLOYMENT
)GET_DEPLOYMENT_STATUS
)GET_DEPLOYMENT_API
)Provider Interaction
GET_PROVIDER_INFO
)GET_PROVIDERS_LIST
)GET_GPU_PRICING
)Resource Management
GET_MANIFEST
)ESTIMATE_GAS
)CREATE_CERTIFICATE
)Key Actions
sdl
,sdlFile
,deposit
dseq
,owner
provider
dseq
,owner
cpu
,memory
,storage
sdl
,sdlFile
filter: { active, hasGPU, region }
address
operation
,params
dseq
,owner
Benefits
Technical Details
Impact
This plugin significantly enhances Eliza's capabilities by enabling autonomous cloud resource management on the Akash Network, making it a powerful tool for decentralized cloud computing operations.