nyxora 26.6.23 → 26.6.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -49
- package/dist/packages/core/src/agent/cronManager.js +6 -3
- package/dist/packages/core/src/agent/llmProvider.js +263 -0
- package/dist/packages/core/src/agent/osAgent.js +277 -0
- package/dist/packages/core/src/agent/reasoning.js +153 -433
- package/dist/packages/core/src/agent/web3Agent.js +284 -0
- package/dist/packages/core/src/config/marketConfigManager.js +43 -0
- package/dist/packages/core/src/gateway/cli.js +1 -1
- package/dist/packages/core/src/gateway/doctor.js +32 -4
- package/dist/packages/core/src/gateway/server.js +87 -91
- package/dist/packages/core/src/gateway/setup.js +19 -7
- package/dist/packages/core/src/gateway/telegram.js +40 -52
- package/dist/packages/core/src/gateway/tracker.js +44 -1
- package/dist/packages/core/src/plugin/PluginManager.js +39 -0
- package/dist/packages/core/src/plugin/registry.js +81 -0
- package/dist/packages/core/src/plugin/registry.test.js +38 -0
- package/dist/packages/core/src/plugin/types.js +2 -0
- package/dist/packages/core/src/system/plugins/GoogleWorkspacePlugin.js +34 -0
- package/dist/packages/core/src/system/plugins/SystemCorePlugin.js +38 -0
- package/dist/packages/core/src/system/plugins/SystemPluginInstallerPlugin.js +85 -0
- package/dist/packages/core/src/system/plugins/SystemSocialPlugin.js +23 -0
- package/dist/packages/core/src/system/plugins/SystemWebPlugin.js +38 -0
- package/dist/packages/core/src/system/plugins/SystemWorkspacePlugin.js +43 -0
- package/dist/packages/core/src/system/skills/searchWeb.js +26 -3
- package/dist/packages/core/src/system/skills/summarizeText.js +3 -3
- package/dist/packages/core/src/utils/historySanitizer.js +36 -0
- package/dist/packages/core/src/utils/skillManager.js +11 -2
- package/dist/packages/core/src/web3/Web3DefiPlugin.js +28 -0
- package/dist/packages/core/src/web3/aggregator/defiRouter.js +14 -12
- package/dist/packages/core/src/web3/aggregator/providerHealthService.js +47 -0
- package/dist/packages/core/src/web3/aggregator/providerRegistry.js +118 -0
- package/dist/packages/core/src/web3/aggregator/providers/ArbitrumBridgeProvider.js +62 -0
- package/dist/packages/core/src/web3/aggregator/providers/KyberSwapProvider.js +87 -0
- package/dist/packages/core/src/web3/aggregator/providers/LifiProvider.js +80 -0
- package/dist/packages/core/src/web3/aggregator/providers/OneInchProvider.js +85 -0
- package/dist/packages/core/src/web3/aggregator/providers/OpBridgeProvider.js +72 -0
- package/dist/packages/core/src/web3/aggregator/providers/OpenOceanProvider.js +32 -0
- package/dist/packages/core/src/web3/aggregator/providers/RelayProvider.js +90 -0
- package/dist/packages/core/src/web3/aggregator/providers/ZeroXProvider.js +80 -0
- package/dist/packages/core/src/web3/aggregator/quoteValidator.js +36 -0
- package/dist/packages/core/src/web3/aggregator/routeScorer.js +31 -0
- package/dist/packages/core/src/web3/aggregator/routeSelector.js +79 -0
- package/dist/packages/core/src/web3/aggregator/types.js +2 -0
- package/dist/packages/core/src/web3/plugins/Web3DefiPlugin.js +68 -0
- package/dist/packages/core/src/web3/plugins/Web3SecurityPlugin.js +34 -0
- package/dist/packages/core/src/web3/plugins/Web3WalletPlugin.js +51 -0
- package/dist/packages/core/src/web3/skills/bridgeToken.js +6 -4
- package/dist/packages/core/src/web3/skills/checkPortfolio.js +7 -6
- package/dist/packages/core/src/web3/skills/checkRegistryStatus.js +5 -5
- package/dist/packages/core/src/web3/skills/checkSecurity.js +1 -1
- package/dist/packages/core/src/web3/skills/getPrice.js +8 -3
- package/dist/packages/core/src/web3/skills/getTxHistory.js +2 -2
- package/dist/packages/core/src/web3/skills/installDefiProvider.js +76 -0
- package/dist/packages/core/src/web3/skills/marketAnalysis.js +8 -3
- package/dist/packages/core/src/web3/skills/nativeOpBridge.js +4 -3
- package/dist/packages/core/src/web3/skills/provideLiquidity.js +1 -1
- package/dist/packages/core/src/web3/skills/swapToken.js +5 -5
- package/dist/packages/core/src/web3/utils/marketEngine.js +32 -27
- package/dist/packages/core/src/web3/utils/vaultClient.js +2 -2
- package/dist/packages/policy/src/server.js +30 -14
- package/package.json +17 -8
- package/packages/core/package.json +3 -6
- package/packages/core/src/agent/cronManager.ts +6 -4
- package/packages/core/src/agent/llmProvider.ts +291 -0
- package/packages/core/src/agent/osAgent.ts +319 -0
- package/packages/core/src/agent/reasoning.ts +183 -531
- package/packages/core/src/agent/web3Agent.ts +323 -0
- package/packages/core/src/config/marketConfigManager.ts +39 -0
- package/packages/core/src/config/parser.ts +1 -0
- package/packages/core/src/gateway/cli.ts +1 -1
- package/packages/core/src/gateway/doctor.ts +32 -4
- package/packages/core/src/gateway/server.ts +94 -98
- package/packages/core/src/gateway/setup.ts +18 -7
- package/packages/core/src/gateway/telegram.ts +43 -54
- package/packages/core/src/gateway/tracker.ts +10 -1
- package/packages/core/src/plugin/PluginManager.ts +42 -0
- package/packages/core/src/plugin/registry.test.ts +46 -0
- package/packages/core/src/plugin/registry.ts +46 -0
- package/packages/core/src/plugin/types.ts +13 -0
- package/packages/core/src/system/plugins/GoogleWorkspacePlugin.ts +45 -0
- package/packages/core/src/system/plugins/SystemCorePlugin.ts +38 -0
- package/packages/core/src/system/plugins/SystemPluginInstallerPlugin.ts +88 -0
- package/packages/core/src/system/plugins/SystemSocialPlugin.ts +23 -0
- package/packages/core/src/system/plugins/SystemWebPlugin.ts +38 -0
- package/packages/core/src/system/plugins/SystemWorkspacePlugin.ts +43 -0
- package/packages/core/src/system/skills/searchWeb.ts +27 -3
- package/packages/core/src/system/skills/summarizeText.ts +4 -4
- package/packages/core/src/utils/historySanitizer.ts +38 -0
- package/packages/core/src/utils/skillManager.ts +11 -2
- package/packages/core/src/web3/aggregator/defiRouter.ts +18 -14
- package/packages/core/src/web3/aggregator/providerHealthService.ts +51 -0
- package/packages/core/src/web3/aggregator/providerRegistry.ts +90 -0
- package/packages/core/src/web3/aggregator/providers/ArbitrumBridgeProvider.ts +64 -0
- package/packages/core/src/web3/aggregator/providers/KyberSwapProvider.ts +88 -0
- package/packages/core/src/web3/aggregator/providers/LifiProvider.ts +81 -0
- package/packages/core/src/web3/aggregator/providers/OneInchProvider.ts +89 -0
- package/packages/core/src/web3/aggregator/providers/OpBridgeProvider.ts +76 -0
- package/packages/core/src/web3/aggregator/providers/OpenOceanProvider.ts +34 -0
- package/packages/core/src/web3/aggregator/providers/RelayProvider.ts +94 -0
- package/packages/core/src/web3/aggregator/providers/ZeroXProvider.ts +80 -0
- package/packages/core/src/web3/aggregator/quoteValidator.ts +42 -0
- package/packages/core/src/web3/aggregator/routeScorer.ts +34 -0
- package/packages/core/src/web3/aggregator/routeSelector.ts +95 -0
- package/packages/core/src/web3/aggregator/types.ts +98 -0
- package/packages/core/src/web3/plugins/Web3DefiPlugin.ts +76 -0
- package/packages/core/src/web3/plugins/Web3SecurityPlugin.ts +34 -0
- package/packages/core/src/web3/plugins/Web3WalletPlugin.ts +51 -0
- package/packages/core/src/web3/skills/bridgeToken.ts +6 -4
- package/packages/core/src/web3/skills/checkPortfolio.ts +7 -6
- package/packages/core/src/web3/skills/checkRegistryStatus.ts +5 -6
- package/packages/core/src/web3/skills/checkSecurity.ts +1 -1
- package/packages/core/src/web3/skills/getPrice.ts +10 -3
- package/packages/core/src/web3/skills/getTxHistory.ts +2 -2
- package/packages/core/src/web3/skills/installDefiProvider.ts +83 -0
- package/packages/core/src/web3/skills/marketAnalysis.ts +10 -3
- package/packages/core/src/web3/skills/provideLiquidity.ts +1 -1
- package/packages/core/src/web3/skills/swapToken.ts +5 -5
- package/packages/core/src/web3/utils/marketEngine.ts +44 -38
- package/packages/core/src/web3/utils/vaultClient.ts +2 -2
- package/packages/dashboard/dist/assets/index-BW-OzhTX.js +16 -0
- package/packages/dashboard/dist/index.html +1 -1
- package/packages/policy/package.json +2 -3
- package/packages/policy/src/server.ts +33 -13
- package/packages/core/src/gateway/test.ts +0 -16
- package/packages/core/src/test_security.ts +0 -45
- package/packages/core/src/web3/aggregator/aggregatorMainnet.ts +0 -293
- package/packages/core/src/web3/aggregator/aggregatorTestnet.ts +0 -146
- package/packages/core/src/web3/skills/nativeOpBridge.ts +0 -83
- package/packages/dashboard/dist/assets/index-CmWZofn_.js +0 -16
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
|
|
5
5
|
[](#)
|
|
6
|
-
[](https://base.org/)
|
|
7
7
|
[](#)
|
|
8
8
|
[](https://opensource.org/licenses/MIT)
|
|
9
9
|
[](#️-advanced-security-threat-model)
|
|
@@ -21,9 +21,9 @@ It operates under a **Zero-Trust, Defense-in-Depth Cryptographically Bound Human
|
|
|
21
21
|
## 🔥 Key Features
|
|
22
22
|
|
|
23
23
|
### Advanced Security Architecture
|
|
24
|
-
* **🛡️ On-Chain AI Kill-Switch**: Nyxora is governed by
|
|
24
|
+
* **🛡️ On-Chain AI Kill-Switch**: Nyxora is governed by a Base 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 Base Architecture](https://nyxoraai.github.io/Nyxora/security/smart-contract)
|
|
25
25
|
* **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).
|
|
26
|
-
* **DeFi Configuration BYOK & UI Masking**: All aggregator and
|
|
26
|
+
* **DeFi & Market Configuration BYOK & UI Masking**: All aggregator, provider, and oracle API keys are strictly isolated via a Bring Your Own Keys (BYOK) architecture into heavily guarded `~/.nyxora/defi_keys.yaml` and `~/.nyxora/market_keys.yaml` files. The local web Dashboard masks these injected secrets using `***********` and `IS_SET` censorship, completely neutralizing malicious browser extensions from exfiltrating your keys.
|
|
27
27
|
* **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.
|
|
28
28
|
* **Native Asset Parameter Tampering Protection**: The internal cryptographic HMAC signature rigorously binds `toAddress`, `txData`, and `valueWei`, rendering the system mathematically immune to Native Token (ETH/BNB) destination or amount hijacking via Indirect Prompt Injections.
|
|
29
29
|
* **Human-in-the-Loop Memory Approval**: AI-extracted permanent behavioral rules are strictly quarantined in a `pending` state until explicitly authorized by the user via the Dashboard, neutralizing Persistent Memory Poisoning vectors.
|
|
@@ -35,10 +35,10 @@ It operates under a **Zero-Trust, Defense-in-Depth Cryptographically Bound Human
|
|
|
35
35
|
### 🌐 Web3 Skills (On-Chain)
|
|
36
36
|
* **Security Scanner**: Nyxora can scan smart contracts via GoPlus Labs to detect Honeypots, Hidden Taxes, and malicious proxy upgrades before you buy.
|
|
37
37
|
* **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.
|
|
38
|
-
* **
|
|
38
|
+
* **Extensible 8-Engine Meta-Aggregator & Anti-MEV**: The core engine interfaces with a powerful, extensible Meta-Aggregator (**1inch, 0x, LI.FI, Relay, OpenOcean, KyberSwap, ArbitrumBridge, and OpBridge**) via a dynamic Provider Registry to route tokens cross-chain, ensuring absolute maximum liquidity depth.
|
|
39
39
|
* **Adaptive Auto Slippage Protection**: Nyxora enforces a dynamic and adaptive **'auto' slippage** by default to leverage dynamic MEV-protection from these industry-standard 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"*).
|
|
40
40
|
|
|
41
|
-
* **Dual-Routing Market Intelligence Engine**: Real-time asset tracking utilizing a sophisticated API Waterfall. Symbol queries are routed to CoinGecko/
|
|
41
|
+
* **Dual-Routing Market Intelligence & Smart Fallback Engine**: Real-time asset tracking utilizing a sophisticated API Waterfall. Symbol queries are routed to CoinGecko/CoinMarketCap Pro endpoints (if BYOK is configured) or gracefully fall back to public endpoints. Contract Addresses seamlessly trigger DexScreener for live on-chain liquidity metrics across all networks, guaranteeing robust discovery even for unlisted memecoins.
|
|
42
42
|
* **Asynchronous Watchdog Agents**: Seamlessly spawn detached background instances for long-running monitoring tasks (e.g., *"Notify me when $ETH drops below $2500"*), leaving your primary chat session free for other operations.
|
|
43
43
|
* **"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.
|
|
44
44
|
* **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.
|
|
@@ -95,58 +95,27 @@ To dive deeper into the technical details of our Zero-Knowledge security archite
|
|
|
95
95
|
|
|
96
96
|
---
|
|
97
97
|
|
|
98
|
-
##
|
|
98
|
+
## 🚀 Quick Start & Installation
|
|
99
99
|
|
|
100
|
-
### Global Installation
|
|
101
|
-
|
|
100
|
+
### Option 1: Global Installation (Recommended)
|
|
101
|
+
Nyxora can be installed globally via NPM, allowing you to use the `nyxora` CLI command from anywhere on your machine.
|
|
102
102
|
|
|
103
|
-
The fastest way to install Nyxora is via our automated installation script:
|
|
104
|
-
|
|
105
|
-
**For Linux & macOS (Bash):**
|
|
106
103
|
```bash
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
**For Windows (PowerShell):**
|
|
111
|
-
```powershell
|
|
112
|
-
iwr https://nyxoraai.github.io/Nyxora/install.ps1 -useb | iex
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
Alternatively, you can install it manually on any operating system using NPM:
|
|
104
|
+
# Install globally
|
|
105
|
+
npm install -g nyxora
|
|
116
106
|
|
|
117
|
-
|
|
118
|
-
npm install -g nyxora@latest
|
|
119
|
-
```
|
|
120
|
-
|
|
121
|
-
### 2. Run the Interactive Setup Wizard (API Keys, Wallet, Telegram)
|
|
122
|
-
```bash
|
|
107
|
+
# Run the interactive setup wizard (API Keys, Wallet, Telegram)
|
|
123
108
|
nyxora setup
|
|
124
|
-
```
|
|
125
109
|
|
|
126
|
-
|
|
127
|
-
```bash
|
|
110
|
+
# Start the background daemon
|
|
128
111
|
nyxora start
|
|
129
|
-
```
|
|
130
112
|
|
|
131
|
-
|
|
132
|
-
```bash
|
|
113
|
+
# Open the interactive UI dashboard
|
|
133
114
|
nyxora dashboard
|
|
134
115
|
```
|
|
135
116
|
|
|
136
|
-
###
|
|
137
|
-
|
|
138
|
-
nyxora clear --force
|
|
139
|
-
```
|
|
140
|
-
|
|
141
|
-
### Utility: Clean Uninstallation
|
|
142
|
-
To completely remove Nyxora, wipe the AI's local memory, and securely delete your Private Key from the OS Keyring before uninstalling the NPM package:
|
|
143
|
-
```bash
|
|
144
|
-
nyxora uninstall
|
|
145
|
-
```
|
|
146
|
-
> **⚠️ IMPORTANT:** Whenever you re-run `nyxora setup` or manually edit the config files, you **must restart the daemon** by running `nyxora restart` for the changes to take effect.
|
|
147
|
-
|
|
148
|
-
### Local Development (From Source)
|
|
149
|
-
If you wish to modify the code or run from source, you can use the Monorepo architecture.
|
|
117
|
+
### Option 2: Local Development (Source Code)
|
|
118
|
+
Nyxora operates on a Monorepo architecture. To run it locally from the source code, modify its behaviors, or contribute to the repository, follow these steps:
|
|
150
119
|
|
|
151
120
|
```bash
|
|
152
121
|
git clone https://github.com/nyxoraAI/Nyxora.git
|
|
@@ -158,14 +127,16 @@ npm install
|
|
|
158
127
|
# 2. Build the Dashboard UI
|
|
159
128
|
npm run build
|
|
160
129
|
|
|
161
|
-
# 3. Interactive Setup Wizard
|
|
130
|
+
# 3. Interactive Setup Wizard
|
|
162
131
|
npm run setup
|
|
163
132
|
|
|
164
133
|
# 4. Start the Application
|
|
165
134
|
npm start
|
|
166
135
|
```
|
|
136
|
+
|
|
167
137
|
*(If you are actively developing and modifying the source code, use `npm run dev` to enable hot-reloading for the frontend and backend).*
|
|
168
|
-
|
|
138
|
+
|
|
139
|
+
> **⚠️ IMPORTANT:** Whenever you re-run `nyxora setup` or manually edit the config files, you **must restart the server** for the changes to take effect.
|
|
169
140
|
|
|
170
141
|
---
|
|
171
142
|
|
|
@@ -188,7 +159,7 @@ For complete technical deep-dives into our Cryptographic Architecture, please vi
|
|
|
188
159
|
**❤️ Support the Project**
|
|
189
160
|
|
|
190
161
|
Building and maintaining a highly secure, zero-trust architecture takes significant time and resources. If you love what we are building, you can help us keep Nyxora open, secure, and constantly evolving by sending a coffee our way:
|
|
191
|
-
- **EVM :** `
|
|
162
|
+
- **EVM :** `0xF5726f0F185d6304f30c9BAE95c477471E29F14f`
|
|
192
163
|
|
|
193
164
|
---
|
|
194
165
|
**License:** MIT License
|
|
@@ -37,7 +37,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
37
37
|
};
|
|
38
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
39
|
exports.cronManager = void 0;
|
|
40
|
-
const
|
|
40
|
+
const croner_1 = require("croner");
|
|
41
41
|
const parser_1 = require("../config/parser");
|
|
42
42
|
const telegram_1 = require("../gateway/telegram");
|
|
43
43
|
const crypto_1 = require("crypto");
|
|
@@ -47,10 +47,13 @@ class CronManager {
|
|
|
47
47
|
addJob(expression, prompt) {
|
|
48
48
|
const id = (0, crypto_1.randomUUID)();
|
|
49
49
|
// Validate expression
|
|
50
|
-
|
|
50
|
+
try {
|
|
51
|
+
new croner_1.Cron(expression);
|
|
52
|
+
}
|
|
53
|
+
catch (e) {
|
|
51
54
|
throw new Error(`Invalid cron expression: ${expression}`);
|
|
52
55
|
}
|
|
53
|
-
const task =
|
|
56
|
+
const task = new croner_1.Cron(expression, async () => {
|
|
54
57
|
console.log(picocolors_1.default.cyan(`[Cron] Executing job ${id}: "${prompt}"`));
|
|
55
58
|
try {
|
|
56
59
|
// Dynamically import processUserInput to avoid circular dependencies
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GeminiAdapter = exports.AnthropicAdapter = exports.OpenAIAdapter = void 0;
|
|
4
|
+
class OpenAIAdapter {
|
|
5
|
+
client;
|
|
6
|
+
constructor(client) {
|
|
7
|
+
this.client = client;
|
|
8
|
+
}
|
|
9
|
+
async chat(request) {
|
|
10
|
+
const response = await this.client.chat.completions.create(request);
|
|
11
|
+
return {
|
|
12
|
+
message: {
|
|
13
|
+
content: response.choices[0].message.content,
|
|
14
|
+
tool_calls: response.choices[0].message.tool_calls
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
exports.OpenAIAdapter = OpenAIAdapter;
|
|
20
|
+
class AnthropicAdapter {
|
|
21
|
+
client;
|
|
22
|
+
constructor(client) {
|
|
23
|
+
this.client = client;
|
|
24
|
+
}
|
|
25
|
+
async chat(request) {
|
|
26
|
+
let systemPrompt = '';
|
|
27
|
+
const anthropicMessages = [];
|
|
28
|
+
for (const m of request.messages) {
|
|
29
|
+
if (m.role === 'system') {
|
|
30
|
+
systemPrompt = m.content;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (m.role === 'user') {
|
|
34
|
+
anthropicMessages.push({ role: 'user', content: m.content });
|
|
35
|
+
}
|
|
36
|
+
else if (m.role === 'assistant') {
|
|
37
|
+
const blocks = [];
|
|
38
|
+
if (m.content)
|
|
39
|
+
blocks.push({ type: 'text', text: m.content });
|
|
40
|
+
if (m.tool_calls) {
|
|
41
|
+
m.tool_calls.forEach((tc) => {
|
|
42
|
+
try {
|
|
43
|
+
blocks.push({
|
|
44
|
+
type: 'tool_use',
|
|
45
|
+
id: tc.id,
|
|
46
|
+
name: tc.function.name,
|
|
47
|
+
input: JSON.parse(tc.function.arguments)
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
catch (e) { }
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
anthropicMessages.push({ role: 'assistant', content: blocks.length > 0 ? blocks : m.content });
|
|
54
|
+
}
|
|
55
|
+
else if (m.role === 'tool') {
|
|
56
|
+
anthropicMessages.push({
|
|
57
|
+
role: 'user',
|
|
58
|
+
content: [
|
|
59
|
+
{
|
|
60
|
+
type: 'tool_result',
|
|
61
|
+
tool_use_id: m.tool_call_id,
|
|
62
|
+
content: m.content
|
|
63
|
+
}
|
|
64
|
+
]
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// Merge consecutive roles (Anthropic strictly requires alternating user/assistant)
|
|
69
|
+
const mergedAnthropic = [];
|
|
70
|
+
for (const m of anthropicMessages) {
|
|
71
|
+
const last = mergedAnthropic[mergedAnthropic.length - 1];
|
|
72
|
+
if (last && last.role === m.role) {
|
|
73
|
+
if (Array.isArray(last.content) && Array.isArray(m.content)) {
|
|
74
|
+
last.content.push(...m.content);
|
|
75
|
+
}
|
|
76
|
+
else if (typeof last.content === 'string' && typeof m.content === 'string') {
|
|
77
|
+
last.content += '\n\n' + m.content;
|
|
78
|
+
}
|
|
79
|
+
else if (Array.isArray(last.content) && typeof m.content === 'string') {
|
|
80
|
+
last.content.push({ type: 'text', text: m.content });
|
|
81
|
+
}
|
|
82
|
+
else if (typeof last.content === 'string' && Array.isArray(m.content)) {
|
|
83
|
+
last.content = [{ type: 'text', text: last.content }, ...m.content];
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
mergedAnthropic.push(m);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
let anthropicTools = undefined;
|
|
91
|
+
if (request.tools) {
|
|
92
|
+
anthropicTools = request.tools.map(t => ({
|
|
93
|
+
name: t.function.name,
|
|
94
|
+
description: t.function.description,
|
|
95
|
+
input_schema: t.function.parameters
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
const response = await this.client.messages.create({
|
|
99
|
+
model: request.model,
|
|
100
|
+
system: systemPrompt,
|
|
101
|
+
messages: mergedAnthropic,
|
|
102
|
+
tools: anthropicTools,
|
|
103
|
+
temperature: request.temperature,
|
|
104
|
+
max_tokens: request.max_tokens || 4096
|
|
105
|
+
});
|
|
106
|
+
let contentStr = null;
|
|
107
|
+
let toolCalls = [];
|
|
108
|
+
for (const block of response.content) {
|
|
109
|
+
if (block.type === 'text') {
|
|
110
|
+
contentStr = (contentStr || '') + block.text;
|
|
111
|
+
}
|
|
112
|
+
else if (block.type === 'tool_use') {
|
|
113
|
+
toolCalls.push({
|
|
114
|
+
id: block.id,
|
|
115
|
+
type: 'function',
|
|
116
|
+
function: {
|
|
117
|
+
name: block.name,
|
|
118
|
+
arguments: JSON.stringify(block.input)
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
message: {
|
|
125
|
+
content: contentStr,
|
|
126
|
+
tool_calls: toolCalls.length > 0 ? toolCalls : undefined
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
exports.AnthropicAdapter = AnthropicAdapter;
|
|
132
|
+
class GeminiAdapter {
|
|
133
|
+
apiKey;
|
|
134
|
+
constructor(apiKey) {
|
|
135
|
+
this.apiKey = apiKey;
|
|
136
|
+
}
|
|
137
|
+
async chat(request) {
|
|
138
|
+
let systemInstruction = '';
|
|
139
|
+
const contents = [];
|
|
140
|
+
for (const m of request.messages) {
|
|
141
|
+
if (m.role === 'system') {
|
|
142
|
+
systemInstruction = m.content;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (m.role === 'user') {
|
|
146
|
+
contents.push({ role: 'user', parts: [{ text: m.content }] });
|
|
147
|
+
}
|
|
148
|
+
else if (m.role === 'assistant') {
|
|
149
|
+
const parts = [];
|
|
150
|
+
if (m.content)
|
|
151
|
+
parts.push({ text: m.content });
|
|
152
|
+
if (m.tool_calls) {
|
|
153
|
+
m.tool_calls.forEach((tc) => {
|
|
154
|
+
try {
|
|
155
|
+
parts.push({
|
|
156
|
+
functionCall: {
|
|
157
|
+
name: tc.function.name,
|
|
158
|
+
args: JSON.parse(tc.function.arguments)
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
catch (e) { }
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
contents.push({ role: 'model', parts: parts });
|
|
166
|
+
}
|
|
167
|
+
else if (m.role === 'tool') {
|
|
168
|
+
contents.push({
|
|
169
|
+
role: 'user',
|
|
170
|
+
parts: [{
|
|
171
|
+
functionResponse: {
|
|
172
|
+
name: m.name || 'unknown_tool',
|
|
173
|
+
response: { result: m.content }
|
|
174
|
+
}
|
|
175
|
+
}]
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// Merge adjacent messages of the same role
|
|
180
|
+
const mergedContents = [];
|
|
181
|
+
for (const m of contents) {
|
|
182
|
+
const last = mergedContents[mergedContents.length - 1];
|
|
183
|
+
if (last && last.role === m.role) {
|
|
184
|
+
last.parts.push(...m.parts);
|
|
185
|
+
}
|
|
186
|
+
else {
|
|
187
|
+
mergedContents.push(m);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
let tools = undefined;
|
|
191
|
+
if (request.tools && request.tools.length > 0) {
|
|
192
|
+
tools = [{
|
|
193
|
+
functionDeclarations: request.tools.map(t => ({
|
|
194
|
+
name: t.function.name,
|
|
195
|
+
description: t.function.description,
|
|
196
|
+
parameters: t.function.parameters
|
|
197
|
+
}))
|
|
198
|
+
}];
|
|
199
|
+
}
|
|
200
|
+
const payload = {
|
|
201
|
+
contents: mergedContents,
|
|
202
|
+
generationConfig: {
|
|
203
|
+
temperature: request.temperature || 0.7,
|
|
204
|
+
},
|
|
205
|
+
safetySettings: [
|
|
206
|
+
{ category: 'HARM_CATEGORY_DANGEROUS_CONTENT', threshold: 'BLOCK_NONE' },
|
|
207
|
+
{ category: 'HARM_CATEGORY_HARASSMENT', threshold: 'BLOCK_NONE' },
|
|
208
|
+
{ category: 'HARM_CATEGORY_HATE_SPEECH', threshold: 'BLOCK_NONE' },
|
|
209
|
+
{ category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', threshold: 'BLOCK_NONE' }
|
|
210
|
+
]
|
|
211
|
+
};
|
|
212
|
+
if (systemInstruction) {
|
|
213
|
+
payload.systemInstruction = { parts: [{ text: systemInstruction }] };
|
|
214
|
+
}
|
|
215
|
+
if (tools) {
|
|
216
|
+
payload.tools = tools;
|
|
217
|
+
}
|
|
218
|
+
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${request.model}:generateContent?key=${this.apiKey}`, {
|
|
219
|
+
method: 'POST',
|
|
220
|
+
headers: {
|
|
221
|
+
'Content-Type': 'application/json'
|
|
222
|
+
},
|
|
223
|
+
body: JSON.stringify(payload)
|
|
224
|
+
});
|
|
225
|
+
if (!response.ok) {
|
|
226
|
+
const errText = await response.text();
|
|
227
|
+
throw new Error(`Gemini API Error: ${response.status} ${response.statusText} - ${errText}`);
|
|
228
|
+
}
|
|
229
|
+
const data = await response.json();
|
|
230
|
+
let contentStr = null;
|
|
231
|
+
let toolCalls = [];
|
|
232
|
+
if (data.candidates && data.candidates.length > 0) {
|
|
233
|
+
const candidate = data.candidates[0];
|
|
234
|
+
if (candidate.finishReason && candidate.finishReason !== 'STOP') {
|
|
235
|
+
console.warn(`[LLM] Gemini API returned finishReason: ${candidate.finishReason}`);
|
|
236
|
+
}
|
|
237
|
+
if (candidate.content && candidate.content.parts) {
|
|
238
|
+
for (const part of candidate.content.parts) {
|
|
239
|
+
if (part.text) {
|
|
240
|
+
contentStr = (contentStr || '') + part.text;
|
|
241
|
+
}
|
|
242
|
+
else if (part.functionCall) {
|
|
243
|
+
toolCalls.push({
|
|
244
|
+
id: `call_${Math.random().toString(36).substring(7)}`,
|
|
245
|
+
type: 'function',
|
|
246
|
+
function: {
|
|
247
|
+
name: part.functionCall.name,
|
|
248
|
+
arguments: JSON.stringify(part.functionCall.args || {})
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return {
|
|
256
|
+
message: {
|
|
257
|
+
content: contentStr,
|
|
258
|
+
tool_calls: toolCalls.length > 0 ? toolCalls : undefined
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
exports.GeminiAdapter = GeminiAdapter;
|