nyxora 26.6.10-2 → 26.6.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/README.md +10 -2
  2. package/dist/launcher.js +3 -0
  3. package/dist/packages/core/src/agent/limitOrderManager.js +19 -73
  4. package/dist/packages/core/src/agent/reasoning.js +92 -43
  5. package/dist/packages/core/src/config/defiConfigManager.js +36 -0
  6. package/dist/packages/core/src/config/parser.js +2 -2
  7. package/dist/packages/core/src/gateway/cli.js +15 -2
  8. package/dist/packages/core/src/gateway/server.js +131 -24
  9. package/dist/packages/core/src/gateway/setup.js +162 -64
  10. package/dist/packages/core/src/gateway/telegram.js +51 -27
  11. package/dist/packages/core/src/memory/logger.js +82 -0
  12. package/dist/packages/core/src/system/skills/analyzeDocument.js +82 -2
  13. package/dist/packages/core/src/system/skills/audioTranscribe.js +45 -0
  14. package/dist/packages/core/src/system/skills/browseWeb.js +58 -18
  15. package/dist/packages/core/src/system/skills/editFile.js +57 -0
  16. package/dist/packages/core/src/system/skills/executeShell.js +29 -0
  17. package/dist/packages/core/src/system/skills/generateExcel.js +7 -38
  18. package/dist/packages/core/src/system/skills/gitManager.js +91 -0
  19. package/dist/packages/core/src/system/skills/notionWorkspace.js +80 -0
  20. package/dist/packages/core/src/system/skills/readFile.js +47 -3
  21. package/dist/packages/core/src/system/skills/summarizeText.js +53 -0
  22. package/dist/packages/core/src/system/skills/xManager.js +78 -0
  23. package/dist/packages/core/src/test-all-routers.js +10 -3
  24. package/dist/packages/core/src/test-router.js +14 -13
  25. package/dist/packages/core/src/test_security.js +43 -0
  26. package/dist/packages/core/src/utils/formatter.js +46 -10
  27. package/dist/packages/core/src/utils/httpClient.js +88 -0
  28. package/dist/packages/core/src/utils/userWhitelistManager.js +66 -11
  29. package/dist/packages/core/src/web3/aggregator/aggregatorMainnet.js +258 -0
  30. package/dist/packages/core/src/web3/aggregator/aggregatorTestnet.js +110 -0
  31. package/dist/packages/core/src/web3/aggregator/defiRouter.js +38 -0
  32. package/dist/packages/core/src/web3/config.js +18 -105
  33. package/dist/packages/core/src/web3/eventListener.js +102 -0
  34. package/dist/packages/core/src/web3/skills/autonomousDefi.js +191 -0
  35. package/dist/packages/core/src/web3/skills/bridgeToken.js +62 -278
  36. package/dist/packages/core/src/web3/skills/checkPortfolio.js +2 -2
  37. package/dist/packages/core/src/web3/skills/checkRegistryStatus.js +1 -1
  38. package/dist/packages/core/src/web3/skills/checkSecurity.js +2 -5
  39. package/dist/packages/core/src/web3/skills/createLimitOrder.js +48 -0
  40. package/dist/packages/core/src/web3/skills/customTx.js +28 -90
  41. package/dist/packages/core/src/web3/skills/executeDefi.js +156 -0
  42. package/dist/packages/core/src/web3/skills/getPrice.js +11 -12
  43. package/dist/packages/core/src/web3/skills/getTxHistory.js +3 -4
  44. package/dist/packages/core/src/web3/skills/limitOrder.js +106 -0
  45. package/dist/packages/core/src/web3/skills/marketAnalysis.js +16 -25
  46. package/dist/packages/core/src/web3/skills/mintNft.js +15 -29
  47. package/dist/packages/core/src/web3/skills/provideLiquidity.js +20 -3
  48. package/dist/packages/core/src/web3/skills/revokeApprovals.js +15 -69
  49. package/dist/packages/core/src/web3/skills/swapToken.js +38 -280
  50. package/dist/packages/core/src/web3/skills/transfer.js +20 -35
  51. package/dist/packages/core/src/web3/utils/chains.js +17 -0
  52. package/dist/packages/core/src/web3/utils/marketEngine.js +88 -0
  53. package/dist/packages/core/src/web3/utils/portfolioNormalizer.js +73 -0
  54. package/dist/packages/core/src/web3/utils/protocolRegistry.js +46 -0
  55. package/dist/packages/core/src/web3/utils/rpcEngine.js +132 -0
  56. package/dist/packages/core/src/web3/utils/tokens.js +45 -15
  57. package/dist/packages/core/src/web3/utils/vaultClient.js +69 -0
  58. package/dist/packages/core/src/web3/utils/zerionTracker.js +59 -0
  59. package/dist/packages/policy/src/server.js +31 -4
  60. package/dist/packages/signer/src/server.js +23 -18
  61. package/dist/tsconfig.tsbuildinfo +1 -0
  62. package/launcher.ts +153 -0
  63. package/package.json +39 -4
  64. package/packages/core/package.json +8 -3
  65. package/packages/core/src/__tests__/reasoning.test.ts +81 -0
  66. package/packages/core/src/__tests__/tokens.test.ts +55 -0
  67. package/packages/core/src/__tests__/web3.test.ts +50 -0
  68. package/packages/core/src/agent/reasoning.d.ts.map +1 -0
  69. package/packages/core/src/agent/reasoning.ts +105 -47
  70. package/packages/core/src/agent/transactionManager.ts +1 -1
  71. package/packages/core/src/config/defiConfigManager.ts +40 -0
  72. package/packages/core/src/config/parser.d.ts.map +1 -0
  73. package/packages/core/src/config/parser.ts +10 -3
  74. package/packages/core/src/gateway/cli.d.ts.map +1 -0
  75. package/packages/core/src/gateway/cli.ts +12 -2
  76. package/packages/core/src/gateway/server.ts +127 -22
  77. package/packages/core/src/gateway/setup.ts +167 -66
  78. package/packages/core/src/gateway/telegram.ts +48 -28
  79. package/packages/core/src/memory/logger.d.ts.map +1 -0
  80. package/packages/core/src/memory/logger.ts +113 -0
  81. package/packages/core/src/system/skills/analyzeDocument.ts +55 -2
  82. package/packages/core/src/system/skills/audioTranscribe.ts +42 -0
  83. package/packages/core/src/system/skills/browseWeb.ts +69 -19
  84. package/packages/core/src/system/skills/editFile.ts +56 -0
  85. package/packages/core/src/system/skills/executeShell.ts +35 -0
  86. package/packages/core/src/system/skills/generateExcel.ts +7 -5
  87. package/packages/core/src/system/skills/gitManager.ts +84 -0
  88. package/packages/core/src/system/skills/notionWorkspace.ts +78 -0
  89. package/packages/core/src/system/skills/readFile.ts +54 -3
  90. package/packages/core/src/system/skills/summarizeText.ts +54 -0
  91. package/packages/core/src/system/skills/xManager.ts +76 -0
  92. package/packages/core/src/test-all-routers.ts +59 -0
  93. package/packages/core/src/test-router.ts +49 -0
  94. package/packages/core/src/test_security.ts +45 -0
  95. package/packages/core/src/utils/formatter.ts +38 -10
  96. package/packages/core/src/utils/httpClient.ts +108 -0
  97. package/packages/core/src/utils/userWhitelistManager.ts +79 -13
  98. package/packages/core/src/web3/aggregator/aggregatorMainnet.ts +290 -0
  99. package/packages/core/src/web3/aggregator/aggregatorTestnet.ts +130 -0
  100. package/packages/core/src/web3/aggregator/defiRouter.ts +38 -0
  101. package/packages/core/src/web3/config.d.ts.map +1 -0
  102. package/packages/core/src/web3/config.ts +4 -101
  103. package/packages/core/src/web3/eventListener.ts +103 -0
  104. package/packages/core/src/web3/skills/bridgeToken.ts +72 -266
  105. package/packages/core/src/web3/skills/checkPortfolio.ts +2 -2
  106. package/packages/core/src/web3/skills/checkRegistryStatus.ts +1 -1
  107. package/packages/core/src/web3/skills/checkSecurity.ts +3 -6
  108. package/packages/core/src/web3/skills/createLimitOrder.ts +56 -0
  109. package/packages/core/src/web3/skills/customTx.ts +35 -103
  110. package/packages/core/src/web3/skills/executeDefi.ts +168 -0
  111. package/packages/core/src/web3/skills/getBalance.d.ts.map +1 -0
  112. package/packages/core/src/web3/skills/getPrice.ts +13 -12
  113. package/packages/core/src/web3/skills/getTxHistory.ts +3 -4
  114. package/packages/core/src/web3/skills/marketAnalysis.ts +15 -25
  115. package/packages/core/src/web3/skills/mintNft.ts +17 -33
  116. package/packages/core/src/web3/skills/provideLiquidity.ts +22 -3
  117. package/packages/core/src/web3/skills/revokeApprovals.ts +17 -35
  118. package/packages/core/src/web3/skills/swapToken.ts +53 -271
  119. package/packages/core/src/web3/skills/transfer.ts +20 -38
  120. package/packages/core/src/web3/utils/chains.ts +17 -0
  121. package/packages/core/src/web3/utils/marketEngine.ts +90 -0
  122. package/packages/core/src/web3/utils/portfolioNormalizer.ts +97 -0
  123. package/packages/core/src/web3/utils/rpcEngine.ts +120 -0
  124. package/packages/core/src/web3/utils/tokens.ts +43 -15
  125. package/packages/core/src/web3/utils/vaultClient.ts +63 -0
  126. package/packages/core/src/web3/utils/zerionTracker.ts +77 -0
  127. package/packages/dashboard/dist/assets/index-BhKhEfi_.js +13 -0
  128. package/packages/dashboard/dist/assets/index-DnQrbB4c.css +1 -0
  129. package/packages/dashboard/dist/index.html +2 -2
  130. package/packages/dashboard/package.json +3 -3
  131. package/packages/mcp-server/package.json +1 -1
  132. package/packages/mcp-server/src/server.ts +8 -10
  133. package/packages/policy/package.json +1 -1
  134. package/packages/policy/src/server.ts +33 -5
  135. package/packages/signer/package.json +1 -1
  136. package/packages/signer/src/server.ts +24 -20
  137. package/.dockerignore +0 -21
  138. package/CHANGELOG.md +0 -288
  139. package/SECURITY.md +0 -105
  140. package/funding.json +0 -5
  141. package/packages/core/src/agent/limitOrderManager.ts +0 -193
  142. package/packages/core/src/web3/skills/createWallet.ts +0 -32
  143. package/packages/dashboard/README.md +0 -73
  144. package/packages/dashboard/dist/assets/index-BSk4CLkG.css +0 -1
  145. package/packages/dashboard/dist/assets/index-W77_dgcr.js +0 -361
  146. package/packages/dashboard/index.html +0 -13
  147. package/packages/dashboard/tsconfig.app.json +0 -25
  148. package/packages/dashboard/tsconfig.json +0 -7
  149. package/packages/dashboard/tsconfig.node.json +0 -24
  150. package/packages/dashboard/vite.config.ts +0 -7
  151. package/packages/mcp-server/dist/server.js +0 -111
  152. package/packages/mcp-server/tsconfig.json +0 -15
  153. package/packages/registry-contract/artifacts/@openzeppelin/contracts/access/Ownable.sol/Ownable.dbg.json +0 -4
  154. package/packages/registry-contract/artifacts/@openzeppelin/contracts/access/Ownable.sol/Ownable.json +0 -85
  155. package/packages/registry-contract/artifacts/@openzeppelin/contracts/utils/Context.sol/Context.dbg.json +0 -4
  156. package/packages/registry-contract/artifacts/@openzeppelin/contracts/utils/Context.sol/Context.json +0 -10
  157. package/packages/registry-contract/artifacts/@openzeppelin/contracts/utils/Pausable.sol/Pausable.dbg.json +0 -4
  158. package/packages/registry-contract/artifacts/@openzeppelin/contracts/utils/Pausable.sol/Pausable.json +0 -60
  159. package/packages/registry-contract/artifacts/build-info/1a74d547ba64d2f3b7adbff726f3d048.json +0 -1
  160. package/packages/registry-contract/artifacts/contracts/NyxoraAgentRegistry.sol/NyxoraAgentRegistry.dbg.json +0 -4
  161. package/packages/registry-contract/artifacts/contracts/NyxoraAgentRegistry.sol/NyxoraAgentRegistry.json +0 -316
  162. package/packages/registry-contract/cache/solidity-files-cache.json +0 -156
  163. package/packages/registry-contract/contracts/NyxoraAgentRegistry.sol +0 -93
  164. package/packages/registry-contract/hardhat.config.ts +0 -32
  165. package/packages/registry-contract/ignition/deployments/chain-421614/artifacts/RegistryModule#NyxoraAgentRegistry.dbg.json +0 -4
  166. package/packages/registry-contract/ignition/deployments/chain-421614/artifacts/RegistryModule#NyxoraAgentRegistry.json +0 -316
  167. package/packages/registry-contract/ignition/deployments/chain-421614/build-info/1a74d547ba64d2f3b7adbff726f3d048.json +0 -12064
  168. package/packages/registry-contract/ignition/deployments/chain-421614/deployed_addresses.json +0 -3
  169. package/packages/registry-contract/ignition/deployments/chain-421614/journal.jsonl +0 -8
  170. package/packages/registry-contract/ignition/modules/Registry.ts +0 -9
  171. package/packages/registry-contract/package.json +0 -23
  172. package/packages/registry-contract/typechain-types/@openzeppelin/contracts/access/Ownable.ts +0 -153
  173. package/packages/registry-contract/typechain-types/@openzeppelin/contracts/access/index.ts +0 -4
  174. package/packages/registry-contract/typechain-types/@openzeppelin/contracts/index.ts +0 -7
  175. package/packages/registry-contract/typechain-types/@openzeppelin/contracts/utils/Pausable.ts +0 -150
  176. package/packages/registry-contract/typechain-types/@openzeppelin/contracts/utils/index.ts +0 -4
  177. package/packages/registry-contract/typechain-types/@openzeppelin/index.ts +0 -5
  178. package/packages/registry-contract/typechain-types/common.ts +0 -131
  179. package/packages/registry-contract/typechain-types/contracts/NyxoraAgentRegistry.ts +0 -416
  180. package/packages/registry-contract/typechain-types/contracts/index.ts +0 -4
  181. package/packages/registry-contract/typechain-types/factories/@openzeppelin/contracts/access/Ownable__factory.ts +0 -96
  182. package/packages/registry-contract/typechain-types/factories/@openzeppelin/contracts/access/index.ts +0 -4
  183. package/packages/registry-contract/typechain-types/factories/@openzeppelin/contracts/index.ts +0 -5
  184. package/packages/registry-contract/typechain-types/factories/@openzeppelin/contracts/utils/Pausable__factory.ts +0 -71
  185. package/packages/registry-contract/typechain-types/factories/@openzeppelin/contracts/utils/index.ts +0 -4
  186. package/packages/registry-contract/typechain-types/factories/@openzeppelin/index.ts +0 -4
  187. package/packages/registry-contract/typechain-types/factories/contracts/NyxoraAgentRegistry__factory.ts +0 -378
  188. package/packages/registry-contract/typechain-types/factories/contracts/index.ts +0 -4
  189. package/packages/registry-contract/typechain-types/factories/index.ts +0 -5
  190. package/packages/registry-contract/typechain-types/hardhat.d.ts +0 -99
  191. package/packages/registry-contract/typechain-types/index.ts +0 -14
  192. package/tsconfig.json +0 -19
package/README.md CHANGED
@@ -22,6 +22,7 @@ It operates under an institutional-grade **Cryptographically Bound Human-in-the-
22
22
  ### Advanced Security Architecture
23
23
  * **🛡️ On-Chain AI Kill-Switch**: Nyxora is governed by an Arbitrum Smart Contract (`NyxoraAgentRegistry`). Users have absolute cryptographic power to instantly paralyze the AI's on-chain execution if compromised, solving the Web3 AI safety dilemma. [Read more about our Arbitrum Architecture ->](https://nyxoraai.github.io/Nyxora/security/smart-contract)
24
24
  * **3-Tier IPC Architecture**: Nyxora is split into isolated processes: **Core** (LLM Runtime), **Policy Engine** (Guardrails on port 3001), and **Signer Vault** (Isolated Key Manager on Unix Sockets).
25
+ * **DeFi Configuration BYOK & UI Masking**: All aggregator and provider API keys are strictly isolated via a Bring Your Own Keys (BYOK) architecture into a heavily guarded `~/.nyxora/defi_keys.yaml` file. The local web Dashboard masks these injected secrets using `***********` and `IS_SET` censorship, completely neutralizing malicious browser extensions from exfiltrating your keys.
25
26
  * **Approval Replay Protection (Nonce Guard)**: Transactions requested by the AI are drafted as hashes and signed with a randomized 16-byte Nonce. The `/api/transactions/:id/approve` endpoint strictly enforces Nonce matching to completely eliminate double-spending and Replay Attacks.
26
27
  * **Immutable Policy Guardrails**: Transaction limits (e.g. `max_usd_per_tx`) are strictly enforced by the Policy Engine. The LLM has zero write-access to bypass these rules.
27
28
  * **Plugin Sandbox VM**: Execute community-built external skills securely inside an airtight Node.js `vm` chamber with zero access to your file system or terminal processes.
@@ -30,8 +31,9 @@ It operates under an institutional-grade **Cryptographically Bound Human-in-the-
30
31
  ### 🌐 Web3 Skills (On-Chain)
31
32
  * **Security Scanner**: Nyxora can scan smart contracts via GoPlus Labs to detect Honeypots, Hidden Taxes, and malicious proxy upgrades before you buy.
32
33
  * **Advanced DeFi Optimization**: Autonomously supply assets to Aave V3, deposit into Beefy/Yearn Auto-Compounder Vaults, manage Uniswap V3 Liquidity (LP), and instantly revoke infinite approvals to secure your wallet. Features intelligent Transaction Chaining to auto-approve allowances prior to execution.
33
- * **Anti-MEV Slippage Protection**: Hardened routing engine with dynamic Slippage Tolerance (default 0.5%) for Relay and Li.Fi. You can manually adjust slippage via the UI or dynamically override it using natural language (e.g., "Swap 1 ETH to PEPE with 10% slippage").
34
- * **Automated Take Profit (TP) & Cut Loss (CL)**: The trader's holy grail. Set natural language rules (e.g., "Sell my PEPE if price drops below $0.001"). Nyxora runs a background cron monitor and executes the swap while you sleep.
34
+ * **6-Engine Meta-Aggregator & Anti-MEV**: The core engine interfaces with a powerful 6-Engine Meta-Aggregator (**1inch, 0x, LI.FI, Relay, OpenOcean, and KyberSwap**) to route tokens cross-chain, ensuring absolute maximum liquidity depth.
35
+ * **Adaptive Auto Slippage Protection**: Nyxora enforces a dynamic and adaptive **'auto' slippage** by default to leverage dynamic MEV-protection from these enterprise aggregators. However, the user retains absolute control to override this dynamically—either globally via the Dashboard Settings or on a per-transaction basis through NLP chat commands (e.g., *"Swap 1 ETH to PEPE with 10% slippage"*).
36
+
35
37
  * **Cross-Chain Hybrid Market Scanner**: Real-time asset tracking combining CoinGecko global data with DexScreener on-chain metrics across Ethereum, Base, Solana, BSC, and more.
36
38
  * **"Lean Degen" Auto-Whitelist**: Automatically intercepts Contract Addresses (CAs) whenever you check balances or swap tokens, saving them to your localized `user_whitelist.json` for future tracking.
37
39
  * **Dynamic Portfolio Engine**: Merges standard tokens, your custom Degen CAs, and CoinGecko's daily trending list into a single hyper-fast Multicall scan to deliver a clean, spam-free PnL portfolio report in under 1 second.
@@ -72,6 +74,12 @@ The following diagram illustrates Nyxora's **3-Tier Monorepo Architecture**, sho
72
74
  2. **🛡️ Policy Engine (The Guard)**: The security guard that verifies the Brain's plans. If the AI attempts to send funds exceeding your set limits, this engine automatically blocks it.
73
75
  3. **🔒 Signer Vault (The Safe)**: The offline vault where your Private Keys **and highly sensitive 3rd-party tokens (e.g., Google Workspace OAuth)** are securely locked natively in your OS Keyring (GNOME Keyring / macOS Keychain / Windows Credential Manager). It only signs transactions after they pass all rigorous security checks.
74
76
 
77
+ ### Web3 Separation of Concerns (Zero-Trust Routing)
78
+ Within the AI Brain, the Web3 codebase is strictly divided to prevent the LLM from hallucinating or maliciously manipulating low-level routing paths:
79
+ - **`aggregator/`**: The core routing engine (1inch, 0x, KyberSwap, etc.) immune to prompt injection. The AI cannot modify execution rules here.
80
+ - **`skills/`**: The execution muscles. Pure functions and tools explicitly exposed to the AI for usage.
81
+ - **`utils/`**: The nervous system managing blockchain configurations, supported tokens, and the RPC Engine.
82
+
75
83
  *(Note: Despite the multi-layered security process appearing lengthy, the internal system validation and cryptographic signing occurs in **milliseconds**, ensuring zero latency bottlenecks).*
76
84
 
77
85
  ---
package/dist/launcher.js CHANGED
@@ -9,6 +9,9 @@ const child_process_1 = require("child_process");
9
9
  const crypto_1 = __importDefault(require("crypto"));
10
10
  const fs_1 = __importDefault(require("fs"));
11
11
  const path_1 = __importDefault(require("path"));
12
+ const dns_1 = __importDefault(require("dns"));
13
+ // Fix Node 18+ native fetch randomly failing on dual-stack VPS (IPv6 issues)
14
+ dns_1.default.setDefaultResultOrder('ipv4first');
12
15
  const INTERNAL_AUTH_TOKEN = crypto_1.default.randomBytes(64).toString('hex');
13
16
  console.log(`[Launcher] Generated Internal Auth Token: ${INTERNAL_AUTH_TOKEN.substring(0, 8)}...`);
14
17
  const nyxoraDir = path_1.default.join(process.env.HOME || process.env.USERPROFILE || '', '.nyxora');
@@ -8,10 +8,7 @@ const fs_1 = __importDefault(require("fs"));
8
8
  const parser_1 = require("../config/parser");
9
9
  const paths_1 = require("../config/paths");
10
10
  const config_1 = require("../web3/config");
11
- const tokens_1 = require("../web3/utils/tokens");
12
- const swapToken_1 = require("../web3/skills/swapToken");
13
11
  const transactionManager_1 = require("./transactionManager");
14
- const reasoning_1 = require("./reasoning");
15
12
  class LimitOrderManager {
16
13
  filePath;
17
14
  orders = [];
@@ -40,12 +37,17 @@ class LimitOrderManager {
40
37
  }
41
38
  createOrder(chainName, fromToken, toToken, amountStr, targetPriceUsd, condition) {
42
39
  const id = `order_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`;
43
- const order = {
44
- id, chainName, fromToken, toToken, amountStr, targetPriceUsd, condition, status: 'pending', createdAt: Date.now()
40
+ const txDetails = {
41
+ id,
42
+ fromToken,
43
+ toToken,
44
+ amountStr,
45
+ targetPriceUsd,
46
+ condition
45
47
  };
46
- this.orders.push(order);
47
- this.saveOrders();
48
- return `Limit order created successfully. ID: ${id}. The system will monitor ${fromToken} price on ${chainName} and execute the swap to ${toToken} when price is ${condition} $${targetPriceUsd}.`;
48
+ // Instead of saving directly, we push it to txManager to trigger the Approval Gate UX
49
+ transactionManager_1.txManager.createPendingTransaction('limit_order', chainName, txDetails);
50
+ return `Prepared limit order: Sell ${amountStr} ${fromToken} for ${toToken} when price is ${condition} $${targetPriceUsd}. I have pushed this to the Transaction Manager. Please wait for user approval on the Dashboard/Telegram. Do not say it's created yet.`;
49
51
  }
50
52
  listOrders() {
51
53
  const pending = this.orders.filter(o => o.status === 'pending');
@@ -58,6 +60,8 @@ class LimitOrderManager {
58
60
  return report;
59
61
  }
60
62
  cancelOrder(id) {
63
+ // Note: To truly cancel a 1inch limit order, we need to call 1inch API to cancel the hash.
64
+ // For now, we mark it cancelled locally.
61
65
  const order = this.orders.find(o => o.id === id);
62
66
  if (!order)
63
67
  return `Order ${id} not found.`;
@@ -65,74 +69,16 @@ class LimitOrderManager {
65
69
  return `Order ${id} cannot be cancelled because it is ${order.status}.`;
66
70
  order.status = 'cancelled';
67
71
  this.saveOrders();
68
- return `Order ${id} cancelled successfully.`;
72
+ return `Order ${id} cancelled successfully locally.`;
69
73
  }
74
+ // Polling logic removed as per Phase 2 Migration to 1inch Off-Chain Protocol
70
75
  startMonitor() {
71
- if (this.monitorInterval)
72
- clearInterval(this.monitorInterval);
73
- // Monitor every 60 seconds
74
- this.monitorInterval = setInterval(() => this.checkOrders(), 60000);
75
- console.log('[LimitOrderManager] Order monitoring started (interval: 60s)');
76
+ console.log('[LimitOrderManager] Local polling disabled. Delegating to 1inch Limit Order Protocol.');
76
77
  }
77
- async checkOrders() {
78
- const pending = this.orders.filter(o => o.status === 'pending');
79
- if (pending.length === 0)
80
- return;
81
- for (const order of pending) {
82
- try {
83
- let tokenAddress = (0, tokens_1.resolveToken)(order.fromToken, order.chainName);
84
- if (tokenAddress === "0x0000000000000000000000000000000000000000") {
85
- tokenAddress = (0, tokens_1.resolveToken)("W" + order.fromToken, order.chainName);
86
- }
87
- const res = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${tokenAddress}`);
88
- if (!res.ok)
89
- continue;
90
- const data = await res.json();
91
- if (!data.pairs || data.pairs.length === 0)
92
- continue;
93
- let pair = data.pairs.find((p) => p.chainId === order.chainName) || data.pairs[0];
94
- const currentPrice = parseFloat(pair.priceUsd);
95
- let shouldExecute = false;
96
- if (order.condition === 'above' && currentPrice >= order.targetPriceUsd)
97
- shouldExecute = true;
98
- if (order.condition === 'below' && currentPrice <= order.targetPriceUsd)
99
- shouldExecute = true;
100
- if (shouldExecute) {
101
- console.log(`[LimitOrderManager] Condition met for order ${order.id}. Current price $${currentPrice} is ${order.condition} $${order.targetPriceUsd}. Executing...`);
102
- // 1. Prepare Swap
103
- const prepareResult = await (0, swapToken_1.prepareSwapToken)(order.chainName, order.fromToken, order.toToken, order.amountStr, 'auto');
104
- // 2. Extract Tx ID
105
- const txMatch = prepareResult.match(/Transaction ID: ([\w-]+)\./);
106
- if (!txMatch) {
107
- order.status = 'failed';
108
- this.saveOrders();
109
- (0, reasoning_1.processUserInput)(`Limit order ${order.id} execution failed during preparation. Output: ${prepareResult}`, 'system').catch(() => { });
110
- continue;
111
- }
112
- const txId = txMatch[1];
113
- const tx = transactionManager_1.txManager.getTransaction(txId);
114
- if (!tx)
115
- throw new Error("Transaction not found in manager");
116
- // 3. Execute Swap automatically (bypass policy with autoApprove: true)
117
- const executeResult = await (0, swapToken_1.executeSwap)(order.chainName, tx.details, true);
118
- if (executeResult.includes('executed') || executeResult.includes('successful')) {
119
- transactionManager_1.txManager.updateStatus(txId, 'executed', executeResult);
120
- order.status = 'executed';
121
- this.saveOrders();
122
- (0, reasoning_1.processUserInput)(`Limit order ${order.id} just EXECUTED automatically! Price hit $${currentPrice}. Swap result: ${executeResult}. Please notify the user immediately!`, 'system').catch(() => { });
123
- }
124
- else {
125
- transactionManager_1.txManager.updateStatus(txId, 'failed', executeResult);
126
- order.status = 'failed';
127
- this.saveOrders();
128
- (0, reasoning_1.processUserInput)(`Limit order ${order.id} FAILED to execute. Price hit $${currentPrice} but execution failed: ${executeResult}. Please notify the user.`, 'system').catch(() => { });
129
- }
130
- }
131
- }
132
- catch (error) {
133
- console.error(`[LimitOrderManager] Error checking order ${order.id}:`, error.message);
134
- }
135
- }
78
+ // We can add a method to save the 1inch hash after the user approves it
79
+ recordApprovedOrder(orderMetadata) {
80
+ this.orders.push(orderMetadata);
81
+ this.saveOrders();
136
82
  }
137
83
  }
138
84
  exports.LimitOrderManager = LimitOrderManager;
@@ -20,7 +20,6 @@ const bridgeToken_1 = require("../web3/skills/bridgeToken");
20
20
  const skillManager_1 = require("../utils/skillManager");
21
21
  const mintNft_1 = require("../web3/skills/mintNft");
22
22
  const customTx_1 = require("../web3/skills/customTx");
23
- const createWallet_1 = require("../web3/skills/createWallet");
24
23
  const checkSecurity_1 = require("../web3/skills/checkSecurity");
25
24
  const marketAnalysis_1 = require("../web3/skills/marketAnalysis");
26
25
  const checkPortfolio_1 = require("../web3/skills/checkPortfolio");
@@ -32,7 +31,7 @@ const defiLending_1 = require("../web3/skills/defiLending");
32
31
  const yieldVault_1 = require("../web3/skills/yieldVault");
33
32
  const provideLiquidity_1 = require("../web3/skills/provideLiquidity");
34
33
  const getTxHistory_1 = require("../web3/skills/getTxHistory");
35
- const limitOrderManager_1 = require("./limitOrderManager");
34
+ const createLimitOrder_1 = require("../web3/skills/createLimitOrder");
36
35
  const updateProfile_1 = require("./updateProfile");
37
36
  const updateSecurityPolicy_1 = require("../system/skills/updateSecurityPolicy");
38
37
  const analyzeDocument_1 = require("../system/skills/analyzeDocument");
@@ -43,6 +42,12 @@ const executeShell_1 = require("../system/skills/executeShell");
43
42
  const browseWeb_1 = require("../system/skills/browseWeb");
44
43
  const searchWeb_1 = require("../system/skills/searchWeb");
45
44
  const installSkill_1 = require("../system/skills/installSkill");
45
+ const editFile_1 = require("../system/skills/editFile");
46
+ const gitManager_1 = require("../system/skills/gitManager");
47
+ const xManager_1 = require("../system/skills/xManager");
48
+ const notionWorkspace_1 = require("../system/skills/notionWorkspace");
49
+ const audioTranscribe_1 = require("../system/skills/audioTranscribe");
50
+ const summarizeText_1 = require("../system/skills/summarizeText");
46
51
  const googleWorkspace_1 = require("../system/skills/googleWorkspace");
47
52
  const pluginManager_1 = require("../system/pluginManager");
48
53
  const paths_1 = require("../config/paths");
@@ -118,21 +123,35 @@ async function executeWithRetry(requestBuilder, maxRetries = 3) {
118
123
  function getSystemPrompt() {
119
124
  const config = (0, parser_1.loadConfig)();
120
125
  const currentDateTime = new Date().toLocaleString('en-US', { timeZoneName: 'short' });
121
- let basePrompt = `You are an autonomous Web3 agent operating on EVM chains.
126
+ let basePrompt = `[CORE DIRECTIVES]
127
+ You are an autonomous Web3 agent operating on EVM chains.
122
128
  You are equipped with a native wallet.
123
129
  The current real-world date and time is: ${currentDateTime}. Use this for any time-related questions.
130
+ Default Chain: ${config.agent.default_chain}
124
131
 
132
+ CRITICAL: You MUST use a Chain of Thought approach for every response. You must enclose your internal reasoning steps within <think>...</think> XML tags BEFORE taking any action or providing a final response. This allows you to plan your tool usage, recall the rules, and avoid hallucinations.
133
+ IMPORTANT: The <think> block is strictly for your internal hidden monologue. NEVER put your final answer, conversational text, or questions to the user inside the <think> block. The actual response that the user will see MUST be written OUTSIDE and AFTER the </think> tag.
134
+
135
+ [EXECUTION WORKFLOW]
125
136
  CRITICAL RULE 1: NEVER expose internal JSON tool calls to the user. Always parse them and explain the outcome naturally.
126
- CRITICAL RULE 2: STRICT LANGUAGE MATCHING. You MUST strictly reply in the exact same language as the user's LATEST prompt. If the user's latest prompt is in English, you MUST reply entirely in English, completely ignoring the language of previous messages. If their latest prompt is in Indonesian, reply in Indonesian.
127
- CRITICAL RULE 3: FORMATTING & CONCISENESS.
128
- - Your responses MUST be concise and to the point. Do not add unnecessary fluff or overly long explanations unless explicitly asked.
129
- - When displaying numbers or monetary values, separate thousands with commas (e.g., $1,000,000) for readability.
130
- - When displaying a list of assets, tokens, portfolio, or transaction history, YOU MUST USE MARKDOWN TABLES. Do not use bullet points for financial data.
131
- CRITICAL RULE 4: When the user asks to check "my balance", "saldo saya", or anything about their own wallet generally, ALWAYS use the check_portfolio tool to show all assets on the chain that have a USD value greater than 0. LEAVE THE ADDRESS PARAMETER EMPTY. Do NOT use get_balance unless the user explicitly asks for the balance of ONE specific token.
132
- CRITICAL RULE 5: If the user doesn't specify a chain, default to: ${config.agent.default_chain}. If the user mentions a specific chain (e.g., "on BNB", "di Base"), you MUST override the default and execute the tool on that specific chain. For transactions that require two chains (like bridge_token), if the user only provides the destination chain, you MUST automatically use ${config.agent.default_chain} as the source chain (fromChainName) without asking for clarification.
133
- CRITICAL RULE 6: If you use the default chain because the user forgot to specify one, you MUST politely confirm which chain you checked in your response (e.g., "I checked your balance on the ${config.agent.default_chain} network..."). Do not issue scary warnings.
134
- CRITICAL RULE 7: TOOL PRIORITIZATION. When the user asks about crypto prices, market analysis, token security, or blockchain data, YOU MUST prioritize using the dedicated Web3 skills (e.g., get_price, analyze_market, check_security) FIRST. Only if those tools fail or cannot provide the requested information, you may fallback to using search_web.
135
- CRITICAL RULE 8: EXACTNESS AND SAFETY IN TRANSACTIONS. Never guess or hallucinate token symbols, network chains, or amounts for Web3 transactions. If the user's intent is ambiguous, you MUST politely ask for clarification instead of attempting a potentially risky transaction. Before confirming any swap or bridge, reiterate the exact tokens, chains, and amounts.`;
137
+ CRITICAL RULE 2: STRICT LANGUAGE MATCHING. You MUST strictly reply in the exact same language as the user's LATEST prompt.
138
+ CRITICAL RULE 3: FORMATTING & CONCISENESS. Provide concise analytical summaries of data rather than just dumping raw markdown tables. Be analytical but brief. Use commas for thousands.
139
+ CRITICAL RULE 4: TOOL PRIORITIZATION. Web3 tasks must use Web3 Skills exclusively. OS Skills (search, browse) are fallbacks only. Use get_my_address to show wallet address, and check_portfolio to show balances.
140
+ CRITICAL RULE 5: DEFAULT CHAIN HANDLING. Default to: ${config.agent.default_chain} unless specified. If overridden, confirm the chain politely. For 2-chain txs (bridge), default source to ${config.agent.default_chain}.
141
+ CRITICAL RULE 8: CONDITIONAL PARALLEL EXECUTION. Parallel tool execution is ONLY allowed if there are zero data dependencies between them.
142
+ CRITICAL RULE 10: PLANNING & RISK DISCLOSURE. For high-level instructions (e.g. "Get yield"), formulate a plan and briefly disclose major risks (smart contract risk, impermanent loss) before asking for approval.
143
+ CRITICAL RULE 11: ADAPTIVE RESPONSE RULE. You must process Web3 data (portfolio, price) and provide a concise, to-the-point analysis based on the context. Do not use useless filler greetings/closings. Provide deep analysis only if the data requires it to protect the user's portfolio.
144
+ CRITICAL RULE 13: WALLET CONTEXT CACHING. Portfolio data in chat history is potentially stale. Do not use cached data for transactional planning; refresh the balance via tools first.
145
+ CRITICAL RULE 14: TRANSACTION EXECUTION. For ALL state-changing transactions (swap, bridge, transfer, stake), do NOT ask for verbal confirmation. Execute the tool IMMEDIATELY. The tool itself will trigger a secure popup in the user's dashboard UI for final approval.
146
+ CRITICAL RULE 17: MINIMIZE UNNECESSARY TOOL CALLS. Do not call tools if the answer exists in recent verified context and freshness is not strictly required. Use history to save latency.
147
+
148
+ [ANTI-HALLUCINATION PROTOCOL]
149
+ CRITICAL RULE 6: NETWORK SAFETY VALIDATION. If a request implies cross-chain or mainnet/testnet mixing, or the token symbol is ambiguous (USDC vs USDC.e), YOU MUST NOT GUESS. Ask for confirmation.
150
+ CRITICAL RULE 7: TOOL CONFIDENCE & HALUCINATION PREVENTION. NEVER fabricate blockchain data. If a tool fails or data is missing, state it explicitly. Do not estimate balances, prices, APY, or gas.
151
+ CRITICAL RULE 9: DEFI CONFIGURATION FALLBACK. If a tool fails due to Rate Limits, Unauthorized, or Missing API Keys, instruct the user to visit the "DeFi Configuration 🔑" menu in the dashboard.
152
+ CRITICAL RULE 12: SMART SLIPPAGE AWARENESS. For low-liquidity assets, warn the user that default slippage might not be enough. NEVER invent specific slippage percentage numbers.
153
+ CRITICAL RULE 16: CAPABILITY HONESTY. NEVER claim a capability not available through installed tools. If asked for an unsupported action, state honestly that the skill is missing.
154
+ CRITICAL RULE 19: MARKET CONFIDENCE SCORE. When analyzing market data, token security, or preparing trades, you MUST explicitly declare a 'Confidence Score (0-100%)' INSIDE your <think> block. If your score is below 40%, you must firmly WARN the user and advise against the trade in your final response.`;
136
155
  // Read IDENTITY.md for core AI persona
137
156
  try {
138
157
  const identityMdPath = (0, paths_1.getPath)('IDENTITY.md');
@@ -179,6 +198,23 @@ CRITICAL RULE 8: EXACTNESS AND SAFETY IN TRANSACTIONS. Never guess or hallucinat
179
198
  catch (error) {
180
199
  // Ignore db errors if not initialized
181
200
  }
201
+ // V3: Inject Personalized Risk Profile
202
+ try {
203
+ const profile = exports.logger.getUserProfile();
204
+ if (profile) {
205
+ basePrompt += `\n\n--- [USER_PERSONA] RISK PROFILE & PREFERENCES ---\n`;
206
+ basePrompt += `Risk Level: ${profile.risk_level}\n`;
207
+ basePrompt += `Max Slippage Tolerance: ${profile.max_slippage}%\n`;
208
+ basePrompt += `Avoid Memecoins: ${profile.avoid_memecoins ? 'YES' : 'NO'}\n`;
209
+ if (profile.custom_rules) {
210
+ basePrompt += `Custom Rules: ${profile.custom_rules}\n`;
211
+ }
212
+ basePrompt += `CRITICAL: You MUST adhere to these risk parameters when advising the user or executing tools. If a requested action violates these parameters (e.g., buying a high-risk memecoin when 'Avoid Memecoins' is YES), you MUST warn the user and refuse execution unless they explicitly override.\n`;
213
+ }
214
+ }
215
+ catch (e) {
216
+ // Ignore if db not ready
217
+ }
182
218
  return basePrompt;
183
219
  }
184
220
  async function processUserInput(input, role = 'user', onProgress, sessionId) {
@@ -214,9 +250,9 @@ async function processUserInput(input, role = 'user', onProgress, sessionId) {
214
250
  const hasGoogleKeyword = /email|gmail|calendar|sheet|doc|form|event/i.test(lowerInput);
215
251
  let tools = [];
216
252
  if ((0, skillManager_1.isSkillActive)('web3')) {
217
- tools.push(getBalance_1.getBalanceToolDefinition, transfer_1.transferToolDefinition, getPrice_1.getPriceToolDefinition, swapToken_1.swapTokenToolDefinition, bridgeToken_1.bridgeTokenToolDefinition, mintNft_1.mintNftToolDefinition, customTx_1.customTxToolDefinition, createWallet_1.createWalletToolDefinition, checkSecurity_1.checkSecurityToolDefinition, marketAnalysis_1.marketAnalysisToolDefinition, checkPortfolio_1.checkPortfolioToolDefinition, checkAddress_1.checkAddressToolDefinition, getMyAddress_1.getMyAddressToolDefinition, manageCustomTokens_1.manageCustomTokensDefinition, limitOrderManager_1.createLimitOrderToolDefinition, limitOrderManager_1.listLimitOrdersToolDefinition, limitOrderManager_1.cancelLimitOrderToolDefinition, revokeApprovals_1.revokeApprovalToolDefinition, defiLending_1.aaveSupplyToolDefinition, yieldVault_1.vaultDepositToolDefinition, provideLiquidity_1.provideLiquidityToolDefinition, getTxHistory_1.getTxHistoryToolDefinition);
253
+ tools.push(getBalance_1.getBalanceToolDefinition, transfer_1.transferToolDefinition, getPrice_1.getPriceToolDefinition, swapToken_1.swapTokenToolDefinition, bridgeToken_1.bridgeTokenToolDefinition, mintNft_1.mintNftToolDefinition, customTx_1.customTxToolDefinition, checkSecurity_1.checkSecurityToolDefinition, marketAnalysis_1.marketAnalysisToolDefinition, checkPortfolio_1.checkPortfolioToolDefinition, checkAddress_1.checkAddressToolDefinition, getMyAddress_1.getMyAddressToolDefinition, manageCustomTokens_1.manageCustomTokensDefinition, revokeApprovals_1.revokeApprovalToolDefinition, defiLending_1.aaveSupplyToolDefinition, yieldVault_1.vaultDepositToolDefinition, provideLiquidity_1.provideLiquidityToolDefinition, getTxHistory_1.getTxHistoryToolDefinition, createLimitOrder_1.createLimitOrderToolDefinition);
218
254
  }
219
- const SYSTEM_TOOLS = [updateProfile_1.updateProfileToolDefinition, updateSecurityPolicy_1.updateSecurityPolicyToolDefinition, analyzeDocument_1.analyzeDocumentToolDefinition, readFile_1.readLocalFileToolDefinition, writeFile_1.writeLocalFileToolDefinition, generateExcel_1.generateExcelToolDefinition, executeShell_1.runTerminalCommandToolDefinition, browseWeb_1.browseWebsiteToolDefinition, searchWeb_1.searchWebToolDefinition, installSkill_1.installExternalSkillToolDefinition];
255
+ const SYSTEM_TOOLS = [updateProfile_1.updateProfileToolDefinition, updateSecurityPolicy_1.updateSecurityPolicyToolDefinition, analyzeDocument_1.analyzeDocumentToolDefinition, readFile_1.readLocalFileToolDefinition, writeFile_1.writeLocalFileToolDefinition, generateExcel_1.generateExcelToolDefinition, executeShell_1.runTerminalCommandToolDefinition, browseWeb_1.browseWebsiteToolDefinition, searchWeb_1.searchWebToolDefinition, installSkill_1.installExternalSkillToolDefinition, editFile_1.editLocalFileToolDefinition, gitManager_1.gitManagerToolDefinition, xManager_1.xManagerToolDefinition, notionWorkspace_1.notionWorkspaceToolDefinition, audioTranscribe_1.audioTranscribeToolDefinition, summarizeText_1.summarizeTextToolDefinition];
220
256
  const GOOGLE_TOOLS = [googleWorkspace_1.readGmailInboxToolDefinition, googleWorkspace_1.listCalendarEventsToolDefinition, googleWorkspace_1.appendRowToSheetsToolDefinition, googleWorkspace_1.readGoogleDocsToolDefinition, googleWorkspace_1.readGoogleFormResponsesToolDefinition];
221
257
  let activeTools = [];
222
258
  if (hasGoogleKeyword && !hasWeb3Keyword) {
@@ -250,6 +286,10 @@ async function processUserInput(input, role = 'user', onProgress, sessionId) {
250
286
  tool_calls: responseMessage.tool_calls,
251
287
  }, sessionId);
252
288
  if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {
289
+ let canFastReturnAll = true;
290
+ let accumulatedResults = [];
291
+ // Disabled fastReturnTools to enforce Web3 Reasoning (V3 feature)
292
+ const fastReturnTools = [];
253
293
  for (const _toolCall of responseMessage.tool_calls) {
254
294
  const toolCall = _toolCall;
255
295
  let result = "";
@@ -303,7 +343,7 @@ async function processUserInput(input, role = 'user', onProgress, sessionId) {
303
343
  result = `[Security Blocked] Runtime Permission Denied: Web3 bridging (transfer) is disabled. Update config.yaml to allow.`;
304
344
  break;
305
345
  }
306
- result = await (0, bridgeToken_1.prepareBridgeToken)(args.fromChainName, args.toChainName, args.fromToken, args.toToken, args.amountStr, args.mode, args.providerName);
346
+ result = await (0, bridgeToken_1.prepareBridgeToken)(args.fromChain, args.toChain, args.tokenSymbol, args.amountStr, args.mode, args.providerName);
307
347
  break;
308
348
  }
309
349
  case 'mint_nft': {
@@ -318,10 +358,6 @@ async function processUserInput(input, role = 'user', onProgress, sessionId) {
318
358
  result = await (0, customTx_1.prepareCustomTx)(args.chainName, args.toAddress, args.dataHex, args.valueEth, args.gasLimitStr);
319
359
  break;
320
360
  }
321
- case 'create_wallet': {
322
- result = await (0, createWallet_1.createWallet)();
323
- break;
324
- }
325
361
  case 'check_token_security': {
326
362
  result = await (0, checkSecurity_1.checkTokenSecurity)(args.chainName, args.contractAddress);
327
363
  break;
@@ -367,19 +403,7 @@ async function processUserInput(input, role = 'user', onProgress, sessionId) {
367
403
  break;
368
404
  }
369
405
  case 'create_limit_order': {
370
- if (config.permissions?.web3?.allow_swap === false) {
371
- result = `[Security Blocked] Runtime Permission Denied: Limit orders require swap permissions. Update config.yaml to allow.`;
372
- break;
373
- }
374
- result = limitOrderManager_1.limitOrderManager.createOrder(args.chainName, args.fromToken, args.toToken, args.amountStr, args.targetPriceUsd, args.condition);
375
- break;
376
- }
377
- case 'list_limit_orders': {
378
- result = limitOrderManager_1.limitOrderManager.listOrders();
379
- break;
380
- }
381
- case 'cancel_limit_order': {
382
- result = limitOrderManager_1.limitOrderManager.cancelOrder(args.id);
406
+ result = await (0, createLimitOrder_1.createLimitOrder)(args.tokenSymbol, args.tokenAddress, args.triggerCondition, args.triggerPriceUsd, args.action, args.amountUsd, args.slippageTolerance);
383
407
  break;
384
408
  }
385
409
  case 'update_profile': {
@@ -395,7 +419,31 @@ async function processUserInput(input, role = 'user', onProgress, sessionId) {
395
419
  break;
396
420
  }
397
421
  case 'read_local_file': {
398
- result = (0, readFile_1.readLocalFile)(args.filePath);
422
+ result = (0, readFile_1.readLocalFile)(args.filePath, args.startLine, args.endLine);
423
+ break;
424
+ }
425
+ case 'edit_local_file': {
426
+ result = (0, editFile_1.editLocalFile)(args.filePath, args.searchString, args.replacementString);
427
+ break;
428
+ }
429
+ case 'execute_git_command': {
430
+ result = await (0, gitManager_1.executeGitCommand)(args.action, args.commitMessage);
431
+ break;
432
+ }
433
+ case 'manage_twitter': {
434
+ result = await (0, xManager_1.manageTwitter)(args.action, args.content, args.username);
435
+ break;
436
+ }
437
+ case 'manage_notion': {
438
+ result = await (0, notionWorkspace_1.manageNotion)(args.action, args.pageId, args.text);
439
+ break;
440
+ }
441
+ case 'transcribe_audio': {
442
+ result = await (0, audioTranscribe_1.transcribeAudio)(args.filePath);
443
+ break;
444
+ }
445
+ case 'summarize_text': {
446
+ result = await (0, summarizeText_1.summarizeText)(args.text, args.focus);
399
447
  break;
400
448
  }
401
449
  case 'write_local_file': {
@@ -482,17 +530,18 @@ async function processUserInput(input, role = 'user', onProgress, sessionId) {
482
530
  name: toolName,
483
531
  content: result,
484
532
  }, sessionId);
485
- // V2 Optimization (Expanded in v1.7.4): Zero-LLM Fast Return for data-heavy and read-only tools
486
- // If the tool already returns perfectly formatted markdown, skip the second LLM call to save 5-10s latency and tokens!
487
- const fastReturnTools = [
488
- 'check_portfolio', 'check_address', 'get_price', 'get_my_address',
489
- 'analyze_market', 'check_token_security', 'search_web', 'read_gmail_inbox', 'list_calendar_events'
490
- ];
491
- if (fastReturnTools.includes(toolName)) {
492
- exports.logger.addEntry({ role: 'assistant', content: result }, sessionId);
493
- return result;
533
+ accumulatedResults.push(result);
534
+ if (!fastReturnTools.includes(toolName)) {
535
+ canFastReturnAll = false;
494
536
  }
495
537
  }
538
+ // V2 Optimization (Expanded in v1.7.4): Zero-LLM Fast Return for data-heavy and read-only tools
539
+ // If all tools already return perfectly formatted markdown, skip the second LLM call to save 5-10s latency!
540
+ if (canFastReturnAll && accumulatedResults.length > 0) {
541
+ const finalContent = accumulatedResults.join('\n\n---\n\n');
542
+ exports.logger.addEntry({ role: 'assistant', content: finalContent }, sessionId);
543
+ return finalContent;
544
+ }
496
545
  // Second call to get the final answer after tool execution
497
546
  const secondMessages = [
498
547
  { role: 'system', content: getSystemPrompt() },
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.loadDefiKeys = loadDefiKeys;
7
+ exports.saveDefiKeys = saveDefiKeys;
8
+ const fs_1 = __importDefault(require("fs"));
9
+ const yaml_1 = __importDefault(require("yaml"));
10
+ const paths_1 = require("./paths");
11
+ function loadDefiKeys() {
12
+ const configPath = (0, paths_1.getPath)('defi_keys.yaml');
13
+ try {
14
+ if (!fs_1.default.existsSync(configPath)) {
15
+ return {};
16
+ }
17
+ const file = fs_1.default.readFileSync(configPath, 'utf8');
18
+ return yaml_1.default.parse(file) || {};
19
+ }
20
+ catch (e) {
21
+ console.error('[DefiConfig] Failed to load defi_keys.yaml', e);
22
+ return {};
23
+ }
24
+ }
25
+ function saveDefiKeys(newKeys) {
26
+ const configPath = (0, paths_1.getPath)('defi_keys.yaml');
27
+ try {
28
+ const currentKeys = loadDefiKeys();
29
+ const merged = { ...currentKeys, ...newKeys };
30
+ const yamlStr = yaml_1.default.stringify(merged);
31
+ fs_1.default.writeFileSync(configPath, yamlStr, 'utf8');
32
+ }
33
+ catch (e) {
34
+ console.error('[DefiConfig] Failed to save defi_keys.yaml', e);
35
+ }
36
+ }
@@ -52,7 +52,7 @@ function loadConfig() {
52
52
  }
53
53
  }
54
54
  return {
55
- agent: parsed.agent || { name: 'Nyxora-Default', description: 'Your Personal Web3 Assistant.', default_chain: 'base', default_router: 'auto', default_slippage: 0.5 },
55
+ agent: parsed.agent || { name: 'Nyxora-Default', description: 'Your Personal Web3 Assistant.', default_chain: 'base', default_router: 'auto', default_slippage: 'auto' },
56
56
  llm: parsed.llm || {
57
57
  provider: 'openai',
58
58
  model: 'gpt-4o-mini',
@@ -88,7 +88,7 @@ function loadConfig() {
88
88
  description: "Your Personal Web3 Assistant.",
89
89
  default_chain: "ethereum",
90
90
  default_router: "auto",
91
- default_slippage: 0.5
91
+ default_slippage: "auto"
92
92
  },
93
93
  llm: {
94
94
  provider: 'openai',
@@ -102,7 +102,10 @@ async function main() {
102
102
  'xai': 'xai_key',
103
103
  'deepseek': 'deepseek_key',
104
104
  'tavily': 'tavily_key',
105
- 'brave': 'brave_key'
105
+ 'brave': 'brave_key',
106
+ 'twitter': 'twitter_key',
107
+ 'notion': 'notion_key',
108
+ 'github': 'github_key'
106
109
  };
107
110
  const mappedKey = keyMap[provider.toLowerCase()] || `${provider.toLowerCase()}_key`;
108
111
  await (0, parser_1.saveApiKeys)({ [mappedKey]: key });
@@ -129,9 +132,19 @@ async function main() {
129
132
  await entry.setPassword(pk);
130
133
  console.log(picocolors_1.default.green('✅ Wallet updated securely in OS Native Vault.'));
131
134
  console.log(picocolors_1.default.yellow('⚠️ Please restart your Nyxora agent for the new wallet to take effect.\n'));
135
+ // 2. Clear vault.key
136
+ try {
137
+ const vaultPath = path_1.default.join(os_1.default.homedir(), '.nyxora', 'auth', 'vault.key');
138
+ if (fs_1.default.existsSync(vaultPath))
139
+ fs_1.default.unlinkSync(vaultPath);
140
+ }
141
+ catch (e) { }
132
142
  }
133
143
  catch (e) {
134
- const vaultPath = path_1.default.join(os_1.default.homedir(), '.nyxora', 'vault.key');
144
+ const vaultDir = path_1.default.join(os_1.default.homedir(), '.nyxora', 'auth');
145
+ if (!fs_1.default.existsSync(vaultDir))
146
+ fs_1.default.mkdirSync(vaultDir, { recursive: true });
147
+ const vaultPath = path_1.default.join(vaultDir, 'vault.key');
135
148
  fs_1.default.writeFileSync(vaultPath, `PRIVATE_KEY=${pk}\n`, { mode: 0o600 });
136
149
  console.log(picocolors_1.default.green('✅ Wallet updated securely in fallback vault.key.'));
137
150
  console.log(picocolors_1.default.yellow('⚠️ Please restart your Nyxora agent for the new wallet to take effect.\n'));