nyxora 26.7.2 → 26.7.3
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/CHANGELOG.md +95 -47
- package/README.md +23 -19
- package/bin/nyxora.mjs +4 -6
- package/dist/launcher.js +44 -8
- package/dist/packages/core/src/agent/bridgeWatcher.js +3 -2
- package/dist/packages/core/src/agent/cronManager.js +2 -2
- package/dist/packages/core/src/agent/llmProvider.js +242 -0
- package/dist/packages/core/src/agent/nyxDaemon.js +97 -0
- package/dist/packages/core/src/agent/osAgent.js +203 -29
- package/dist/packages/core/src/agent/reasoning.js +353 -60
- package/dist/packages/core/src/agent/reasoningScratchpad.js +47 -0
- package/dist/packages/core/src/agent/transactionManager.js +36 -31
- package/dist/packages/core/src/agent/web3Agent.js +263 -37
- package/dist/packages/core/src/cognitive/cognitiveManager.js +63 -10
- package/dist/packages/core/src/config/parser.js +10 -4
- package/dist/packages/core/src/gateway/chat.js +56 -13
- package/dist/packages/core/src/gateway/cli.js +3 -0
- package/dist/packages/core/src/gateway/discordAdapter.js +81 -0
- package/dist/packages/core/src/gateway/server.js +58 -9
- package/dist/packages/core/src/gateway/setup-ml.js +64 -0
- package/dist/packages/core/src/gateway/setup.js +39 -3
- package/dist/packages/core/src/gateway/telegram.js +120 -24
- package/dist/packages/core/src/memory/episodic.js +47 -3
- package/dist/packages/core/src/memory/logger.js +120 -2
- package/dist/packages/core/src/memory/promotionEngine.js +18 -5
- package/dist/packages/core/src/system/agentskills.js +10 -0
- package/dist/packages/core/src/system/plugins/GoogleWorkspacePlugin.js +1 -1
- package/dist/packages/core/src/system/plugins/SystemCorePlugin.js +1 -1
- package/dist/packages/core/src/system/plugins/SystemExternalPlugin.js +1 -1
- package/dist/packages/core/src/system/plugins/SystemPluginInstallerPlugin.js +1 -1
- package/dist/packages/core/src/system/plugins/SystemSocialPlugin.js +1 -1
- package/dist/packages/core/src/system/plugins/SystemWebPlugin.js +1 -1
- package/dist/packages/core/src/system/plugins/SystemWorkspacePlugin.js +3 -3
- package/dist/packages/core/src/system/plugins/createSkill.js +1 -1
- package/dist/packages/core/src/system/skillExtractor.js +16 -5
- package/dist/packages/core/src/system/skills/forgetMemory.js +6 -4
- package/dist/packages/core/src/system/skills/scheduleTask.js +7 -2
- package/dist/packages/core/src/test_mainnet.js +45 -0
- package/dist/packages/core/src/utils/contextSummarizer.js +82 -0
- package/dist/packages/core/src/utils/skillManager.js +1 -1
- package/dist/packages/core/src/utils/streamSimulator.js +85 -0
- package/dist/packages/core/src/web3/aggregator/providers/ArbitrumBridgeProvider.js +28 -11
- package/dist/packages/core/src/web3/aggregator/providers/OpBridgeProvider.js +41 -27
- package/dist/packages/core/src/web3/aggregator/providers/TestnetSwapProvider.js +65 -0
- package/dist/packages/core/src/web3/aggregator/routeSelector.js +7 -1
- package/dist/packages/core/src/web3/plugins/Web3DefiPlugin.js +1 -1
- package/dist/packages/core/src/web3/plugins/Web3MarketPlugin.js +5 -125
- package/dist/packages/core/src/web3/plugins/Web3SecurityPlugin.js +1 -1
- package/dist/packages/core/src/web3/plugins/Web3WalletPlugin.js +1 -1
- package/dist/packages/core/src/web3/skills/bridgeToken.js +19 -4
- package/dist/packages/core/src/web3/skills/checkAddress.js +2 -0
- package/dist/packages/core/src/web3/skills/checkPortfolio.js +22 -2
- package/dist/packages/core/src/web3/skills/checkSecurity.js +2 -0
- package/dist/packages/core/src/web3/skills/confirmPendingTx.js +1 -1
- package/dist/packages/core/src/web3/skills/createLimitOrder.js +15 -1
- package/dist/packages/core/src/web3/skills/customTx.js +3 -0
- package/dist/packages/core/src/web3/skills/defiLending.js +2 -0
- package/dist/packages/core/src/web3/skills/getBalance.js +2 -0
- package/dist/packages/core/src/web3/skills/getPrice.js +134 -27
- package/dist/packages/core/src/web3/skills/getTxHistory.js +2 -0
- package/dist/packages/core/src/web3/skills/marketAnalysis.js +28 -191
- package/dist/packages/core/src/web3/skills/mintNft.js +3 -0
- package/dist/packages/core/src/web3/skills/provideLiquidity.js +16 -12
- package/dist/packages/core/src/web3/skills/revokeApprovals.js +2 -0
- package/dist/packages/core/src/web3/skills/swapToken.js +20 -2
- package/dist/packages/core/src/web3/skills/transfer.js +2 -0
- package/dist/packages/core/src/web3/skills/yieldVault.js +2 -0
- package/dist/packages/core/src/web3/utils/chains.js +19 -0
- package/dist/packages/core/src/web3/utils/marketEngine.js +26 -33
- package/dist/packages/signer/src/NyxoraSigner.js +181 -0
- package/dist/packages/signer/src/index.js +17 -0
- package/dist/packages/signer/src/server.js +25 -161
- package/launcher.ts +38 -9
- package/package.json +6 -2
- package/packages/core/package.json +21 -10
- package/packages/core/src/agent/bridgeWatcher.ts +3 -2
- package/packages/core/src/agent/cronManager.ts +2 -2
- package/packages/core/src/agent/llmProvider.ts +219 -0
- package/packages/core/src/agent/nyxDaemon.ts +104 -0
- package/packages/core/src/agent/osAgent.ts +230 -32
- package/packages/core/src/agent/reasoning.ts +376 -64
- package/packages/core/src/agent/reasoningScratchpad.ts +45 -0
- package/packages/core/src/agent/transactionManager.ts +36 -28
- package/packages/core/src/agent/web3Agent.ts +291 -40
- package/packages/core/src/cognitive/cognitiveManager.ts +65 -10
- package/packages/core/src/cognitive/prompts/web3/market-analysis.md +24 -0
- package/packages/core/src/cognitive/prompts/web3/portfolio-review.md +29 -0
- package/packages/core/src/cognitive/prompts/web3/risk-assessment.md +28 -0
- package/packages/core/src/cognitive/prompts/web3/trade-planning.md +30 -0
- package/packages/core/src/config/parser.ts +15 -4
- package/packages/core/src/gateway/chat.ts +57 -15
- package/packages/core/src/gateway/cli.ts +4 -0
- package/packages/core/src/gateway/discordAdapter.ts +87 -0
- package/packages/core/src/gateway/server.ts +66 -10
- package/packages/core/src/gateway/setup-ml.ts +68 -0
- package/packages/core/src/gateway/setup.ts +41 -3
- package/packages/core/src/gateway/telegram.ts +138 -27
- package/packages/core/src/memory/episodic.ts +64 -3
- package/packages/core/src/memory/logger.ts +142 -2
- package/packages/core/src/memory/promotionEngine.ts +19 -5
- package/packages/core/src/system/agentskills.ts +10 -0
- package/packages/core/src/system/plugins/GoogleWorkspacePlugin.ts +1 -1
- package/packages/core/src/system/plugins/SystemCorePlugin.ts +1 -1
- package/packages/core/src/system/plugins/SystemExternalPlugin.ts +1 -1
- package/packages/core/src/system/plugins/SystemPluginInstallerPlugin.ts +1 -1
- package/packages/core/src/system/plugins/SystemSocialPlugin.ts +1 -1
- package/packages/core/src/system/plugins/SystemWebPlugin.ts +1 -1
- package/packages/core/src/system/plugins/SystemWorkspacePlugin.ts +3 -3
- package/packages/core/src/system/plugins/createSkill.ts +1 -1
- package/packages/core/src/system/skillExtractor.ts +16 -5
- package/packages/core/src/system/skills/forgetMemory.ts +7 -4
- package/packages/core/src/system/skills/scheduleTask.ts +7 -2
- package/packages/core/src/utils/contextSummarizer.ts +100 -0
- package/packages/core/src/utils/skillManager.ts +1 -1
- package/packages/core/src/utils/streamSimulator.ts +88 -0
- package/packages/core/src/web3/aggregator/providers/ArbitrumBridgeProvider.ts +30 -11
- package/packages/core/src/web3/aggregator/providers/OpBridgeProvider.ts +43 -29
- package/packages/core/src/web3/aggregator/routeSelector.ts +6 -1
- package/packages/core/src/web3/plugins/Web3DefiPlugin.ts +1 -1
- package/packages/core/src/web3/plugins/Web3MarketPlugin.ts +6 -125
- package/packages/core/src/web3/plugins/Web3SecurityPlugin.ts +1 -1
- package/packages/core/src/web3/plugins/Web3WalletPlugin.ts +1 -1
- package/packages/core/src/web3/skills/bridgeToken.ts +21 -7
- package/packages/core/src/web3/skills/checkAddress.ts +2 -0
- package/packages/core/src/web3/skills/checkPortfolio.ts +23 -2
- package/packages/core/src/web3/skills/checkSecurity.ts +2 -0
- package/packages/core/src/web3/skills/confirmPendingTx.ts +1 -1
- package/packages/core/src/web3/skills/createLimitOrder.ts +17 -2
- package/packages/core/src/web3/skills/customTx.ts +3 -0
- package/packages/core/src/web3/skills/defiLending.ts +2 -0
- package/packages/core/src/web3/skills/getBalance.ts +2 -0
- package/packages/core/src/web3/skills/getPrice.ts +134 -30
- package/packages/core/src/web3/skills/getTxHistory.ts +2 -0
- package/packages/core/src/web3/skills/marketAnalysis.ts +45 -188
- package/packages/core/src/web3/skills/mintNft.ts +3 -0
- package/packages/core/src/web3/skills/provideLiquidity.ts +16 -10
- package/packages/core/src/web3/skills/revokeApprovals.ts +2 -0
- package/packages/core/src/web3/skills/swapToken.ts +20 -3
- package/packages/core/src/web3/skills/transfer.ts +2 -0
- package/packages/core/src/web3/skills/yieldVault.ts +2 -0
- package/packages/core/src/web3/utils/chains.ts +12 -0
- package/packages/core/src/web3/utils/marketEngine.ts +27 -33
- package/packages/dashboard/dist/assets/index-BTfp141V.js +18 -0
- package/packages/dashboard/dist/assets/index-DK2sTU47.css +1 -0
- package/packages/dashboard/dist/index.html +2 -2
- package/packages/dashboard/package.json +10 -10
- package/packages/mcp-server/dist/server.js +5 -1
- package/packages/mcp-server/package.json +6 -6
- package/packages/mcp-server/src/server.ts +11 -7
- package/packages/policy/package.json +3 -3
- package/packages/signer/package.json +16 -6
- package/packages/signer/src/NyxoraSigner.ts +161 -0
- package/packages/signer/src/index.ts +1 -0
- package/packages/signer/src/server.ts +25 -135
- package/dist/packages/core/src/agent/honchoDaemon.js +0 -91
- package/dist/packages/core/src/cognitive/prompts/autonomous/binance-trading-integration.md +0 -54
- package/dist/packages/core/src/gateway/test.js +0 -15
- package/dist/packages/core/src/web3/Web3DefiPlugin.js +0 -28
- package/dist/packages/core/src/web3/aggregator/aggregatorMainnet.js +0 -260
- package/dist/packages/core/src/web3/aggregator/aggregatorTestnet.js +0 -119
- package/dist/packages/core/src/web3/skills/nativeOpBridge.js +0 -71
- package/packages/core/src/agent/honchoDaemon.ts +0 -96
- package/packages/core/src/cognitive/prompts/autonomous/binance-trading-integration.md +0 -41
- package/packages/core/src/plugin/registry.test.ts +0 -46
- package/packages/core/src/utils/formatter.test.ts +0 -41
- package/packages/dashboard/dist/assets/index-CSoNa5cx.css +0 -1
- package/packages/dashboard/dist/assets/index-DbRWEoSr.js +0 -16
|
@@ -5,12 +5,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.logger = void 0;
|
|
7
7
|
exports.processOsIntent = processOsIntent;
|
|
8
|
+
exports.processOsIntentStream = processOsIntentStream;
|
|
9
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
10
|
const parser_1 = require("../config/parser");
|
|
9
11
|
const logger_1 = require("../memory/logger");
|
|
10
12
|
const tracker_1 = require("../gateway/tracker");
|
|
11
13
|
const episodic_1 = require("../memory/episodic");
|
|
12
14
|
const skillManager_1 = require("../utils/skillManager");
|
|
13
15
|
const cognitiveManager_1 = require("../cognitive/cognitiveManager");
|
|
16
|
+
const reasoningScratchpad_1 = require("./reasoningScratchpad");
|
|
17
|
+
const contextSummarizer_1 = require("../utils/contextSummarizer");
|
|
14
18
|
const EXECUTION_DISCIPLINE = `
|
|
15
19
|
<tool_persistence>
|
|
16
20
|
Use tools whenever they can increase the accuracy, completeness, or factual correctness of your response.
|
|
@@ -36,10 +40,11 @@ NEVER fabricate, hallucinate, or forge tool outputs.
|
|
|
36
40
|
</task_completion>
|
|
37
41
|
`;
|
|
38
42
|
const registry_1 = require("../plugin/registry");
|
|
43
|
+
const paths_1 = require("../config/paths");
|
|
39
44
|
const picocolors_1 = __importDefault(require("picocolors"));
|
|
40
45
|
exports.logger = new logger_1.Logger();
|
|
41
46
|
const llmUtils_1 = require("../utils/llmUtils");
|
|
42
|
-
function getSystemPrompt(context = 'os', userInput = '') {
|
|
47
|
+
async function getSystemPrompt(context = 'os', userInput = '') {
|
|
43
48
|
const config = (0, parser_1.loadConfig)();
|
|
44
49
|
const currentDateTime = new Date().toLocaleString('en-US');
|
|
45
50
|
let basePrompt = `You are Nyxora's OS Agent (System & Automation Specialist).
|
|
@@ -49,7 +54,7 @@ Reason internally. Never reveal private reasoning. Provide only concise conclusi
|
|
|
49
54
|
|
|
50
55
|
[OS EXECUTION WORKFLOW]
|
|
51
56
|
CRITICAL RULE 1: NEVER expose internal JSON tool calls. Explain the outcome naturally.
|
|
52
|
-
CRITICAL RULE 2: STRICT LANGUAGE MATCHING. Reply in the exact same language as the user's LATEST prompt.
|
|
57
|
+
CRITICAL RULE 2: STRICT LANGUAGE MATCHING. Reply in the exact same language as the user's LATEST prompt, UNLESS the Episodic Memories or Cognitive Skills specify a strict language preference.
|
|
53
58
|
CRITICAL RULE 3: FILE SYSTEM SAFETY. You are STRICTLY FORBIDDEN from modifying config.yaml, rpc_key.yaml, or policy.yaml using terminal commands like sed or echo.
|
|
54
59
|
CRITICAL RULE 4: CRON JOBS VS LIMIT ORDERS. Do NOT use schedule_task for price-based trading triggers. Use schedule_task for time-based recurring tasks.
|
|
55
60
|
CRITICAL RULE 5: TOOL CONFIDENCE. NEVER fabricate file contents or command outputs.
|
|
@@ -61,46 +66,83 @@ ${EXECUTION_DISCIPLINE}
|
|
|
61
66
|
if (activeSOP) {
|
|
62
67
|
basePrompt += `\n\n[ACTIVE COGNITIVE SKILLS]\n${activeSOP}\n`;
|
|
63
68
|
}
|
|
64
|
-
// Inject Episodic Memories
|
|
69
|
+
// Inject Episodic Memories via Python RAG
|
|
65
70
|
try {
|
|
66
|
-
const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
`;
|
|
71
|
+
const ragRes = await fetch('http://localhost:8000/memory/rag', {
|
|
72
|
+
method: 'POST',
|
|
73
|
+
headers: { 'Content-Type': 'application/json' },
|
|
74
|
+
body: JSON.stringify({ query: userInput, top_k: 5 })
|
|
75
|
+
});
|
|
76
|
+
if (ragRes.ok) {
|
|
77
|
+
const ragData = await ragRes.json();
|
|
78
|
+
if (ragData.memories && ragData.memories.length > 0) {
|
|
79
|
+
basePrompt += `\n\n--- EPISODIC MEMORIES (SMART SUGGESTIONS) ---\n`;
|
|
80
|
+
ragData.memories.forEach((mem) => {
|
|
81
|
+
basePrompt += `- ${mem}\n`;
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
catch (e) {
|
|
87
|
+
// Fallback or ignore if Python ML engine is down
|
|
88
|
+
}
|
|
89
|
+
// Inject User Information & Personas from user.md
|
|
90
|
+
try {
|
|
91
|
+
const userMdPath = (0, paths_1.getPath)('user.md');
|
|
92
|
+
if (fs_1.default.existsSync(userMdPath)) {
|
|
93
|
+
const userInstructions = fs_1.default.readFileSync(userMdPath, 'utf8');
|
|
94
|
+
basePrompt += `\n\n--- USER INFORMATION & PREFERENCES ---\n${userInstructions}\n`;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
// Ignore error
|
|
99
|
+
}
|
|
100
|
+
// HIGHEST PRIORITY: Inject observed user communication style (NyxDaemon)
|
|
101
|
+
try {
|
|
102
|
+
const strongPersonas = episodic_1.episodicDB.getStrongPersonas(0.5);
|
|
103
|
+
if (strongPersonas.length > 0) {
|
|
104
|
+
basePrompt += `\n\n--- ⚡ OVERRIDE: USER COMMUNICATION STYLE (HIGHEST PRIORITY — OVERRIDES ALL RULES ABOVE) ---\n`;
|
|
105
|
+
basePrompt += `CRITICAL: These are CONFIRMED user preferences observed across multiple conversations. You MUST apply them IMMEDIATELY and CONSISTENTLY, overriding any default tone or style instructions above.\n\n`;
|
|
106
|
+
strongPersonas.forEach(p => {
|
|
107
|
+
const label = p.category ? `[${p.category.toUpperCase()}]` : '[PREFERENCE]';
|
|
108
|
+
basePrompt += `${label} ${p.trait}\n`;
|
|
75
109
|
});
|
|
76
110
|
}
|
|
77
111
|
}
|
|
78
|
-
catch {
|
|
112
|
+
catch (e) {
|
|
113
|
+
// Ignore
|
|
114
|
+
}
|
|
79
115
|
return basePrompt;
|
|
80
116
|
}
|
|
81
117
|
async function processOsIntent(input, role = 'user', onProgress, sessionId) {
|
|
82
118
|
const config = (0, parser_1.loadConfig)();
|
|
83
119
|
// Add input to memory
|
|
84
120
|
exports.logger.addEntry({ role, content: input }, sessionId);
|
|
85
|
-
const history = exports.logger.getHistory(sessionId);
|
|
86
|
-
// Format messages for OpenAI
|
|
87
121
|
let activeTools = [...registry_1.pluginManager.getAllToolDefinitions()];
|
|
88
122
|
activeTools = activeTools.filter(t => (0, skillManager_1.isSkillActive)(t.function.name));
|
|
123
|
+
// P1: Init reasoning scratchpad for this request
|
|
124
|
+
const scratchpad = new reasoningScratchpad_1.ReasoningScratchpad();
|
|
125
|
+
// P3: Build system prompt ONCE per request — not per turn
|
|
126
|
+
const cachedSystemPrompt = await getSystemPrompt('os', input);
|
|
89
127
|
const { sanitizeHistoryForLLM } = require('../utils/historySanitizer');
|
|
90
|
-
const sanitizedHistory = sanitizeHistoryForLLM(history, activeTools, config.llm.provider);
|
|
91
|
-
let messages = [
|
|
92
|
-
{ role: 'system', content: getSystemPrompt('os', input) },
|
|
93
|
-
...sanitizedHistory
|
|
94
|
-
];
|
|
95
128
|
try {
|
|
96
129
|
let turnCount = 0;
|
|
97
130
|
const MAX_TURNS = 10;
|
|
131
|
+
let consecutiveToolErrors = 0;
|
|
98
132
|
while (turnCount < MAX_TURNS) {
|
|
99
133
|
turnCount++;
|
|
100
134
|
const currentHistory = exports.logger.getHistory(sessionId);
|
|
101
|
-
|
|
135
|
+
// P6: Compress history if conversation is too long
|
|
136
|
+
const historyToUse = (0, contextSummarizer_1.needsCompression)(currentHistory)
|
|
137
|
+
? await (0, contextSummarizer_1.compressHistory)(currentHistory)
|
|
138
|
+
: currentHistory;
|
|
139
|
+
const sanitizedHistory = sanitizeHistoryForLLM(historyToUse, activeTools, config.llm.provider);
|
|
140
|
+
// P1: Inject scratchpad into system prompt for turns > 1
|
|
141
|
+
const sysPrompt = turnCount === 1
|
|
142
|
+
? cachedSystemPrompt
|
|
143
|
+
: cachedSystemPrompt + scratchpad.getInjection();
|
|
102
144
|
const messages = [
|
|
103
|
-
{ role: 'system', content:
|
|
145
|
+
{ role: 'system', content: sysPrompt },
|
|
104
146
|
...sanitizedHistory
|
|
105
147
|
];
|
|
106
148
|
const response = await (0, llmUtils_1.executeWithRetry)(async (client) => {
|
|
@@ -119,16 +161,15 @@ async function processOsIntent(input, role = 'user', onProgress, sessionId) {
|
|
|
119
161
|
tracker_1.Tracker.addTokens(response.usage.total_tokens, config.llm.provider);
|
|
120
162
|
}
|
|
121
163
|
tracker_1.Tracker.addEvent('llm.response', { provider: config.llm.provider, tool_calls: responseMessage.tool_calls?.length || 0 });
|
|
164
|
+
// P1: Capture <think> blocks for scratchpad, get clean content
|
|
165
|
+
const cleanedContent = scratchpad.capture(responseMessage.content || '', turnCount);
|
|
122
166
|
exports.logger.addEntry({
|
|
123
167
|
role: 'assistant',
|
|
124
|
-
content:
|
|
168
|
+
content: cleanedContent || '',
|
|
125
169
|
tool_calls: responseMessage.tool_calls,
|
|
126
170
|
}, sessionId);
|
|
127
171
|
if (!responseMessage.tool_calls || responseMessage.tool_calls.length === 0) {
|
|
128
|
-
|
|
129
|
-
finalContent = finalContent.replace(/<(think|thought|thinking|reasoning|analysis|reflection)>[\s\S]*?<\/\1>\n?/gi, '');
|
|
130
|
-
finalContent = finalContent.trim();
|
|
131
|
-
return finalContent;
|
|
172
|
+
return cleanedContent || 'No response generated.';
|
|
132
173
|
}
|
|
133
174
|
let canFastReturnAll = true;
|
|
134
175
|
let accumulatedResults = [];
|
|
@@ -205,8 +246,26 @@ async function processOsIntent(input, role = 'user', onProgress, sessionId) {
|
|
|
205
246
|
canFastReturnAll = false;
|
|
206
247
|
}
|
|
207
248
|
}
|
|
208
|
-
//
|
|
209
|
-
|
|
249
|
+
// P4: Self-reflection — if ALL tools failed, inject reflection before next turn
|
|
250
|
+
const allFailed = accumulatedResults.length > 0 && accumulatedResults.every(r => r.startsWith('Error') || r.includes('[System Error]') || r.includes('[Security Blocked]'));
|
|
251
|
+
if (allFailed) {
|
|
252
|
+
consecutiveToolErrors++;
|
|
253
|
+
const reflection = `[SELF-REFLECTION] All ${accumulatedResults.length} tool call(s) failed (attempt ${consecutiveToolErrors}). ` +
|
|
254
|
+
`Errors: ${accumulatedResults.join(' | ')}. ` +
|
|
255
|
+
`Analyze WHY each failed. Options: (1) retry with corrected params, (2) use alternative tool, (3) inform user clearly. ` +
|
|
256
|
+
`Do NOT repeat the exact same failed call.`;
|
|
257
|
+
exports.logger.addEntry({ role: 'system', content: reflection }, sessionId);
|
|
258
|
+
console.log(picocolors_1.default.magenta(`[Self-Reflection] Turn ${turnCount}: all tools failed, injecting reflection.`));
|
|
259
|
+
if (consecutiveToolErrors >= 2) {
|
|
260
|
+
const errorSummary = `⚠️ Unable to complete this request after multiple attempts.\n${accumulatedResults.join('\n')}`;
|
|
261
|
+
exports.logger.addEntry({ role: 'assistant', content: errorSummary }, sessionId);
|
|
262
|
+
return errorSummary;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
consecutiveToolErrors = 0;
|
|
267
|
+
}
|
|
268
|
+
// V2 Optimization: Zero-LLM Fast Return for transaction tools
|
|
210
269
|
if (canFastReturnAll && accumulatedResults.length > 0) {
|
|
211
270
|
const finalContent = accumulatedResults.join('\n\n---\n\n');
|
|
212
271
|
exports.logger.addEntry({ role: 'assistant', content: finalContent }, sessionId);
|
|
@@ -229,3 +288,118 @@ async function processOsIntent(input, role = 'user', onProgress, sessionId) {
|
|
|
229
288
|
return errorMsg;
|
|
230
289
|
}
|
|
231
290
|
}
|
|
291
|
+
async function processOsIntentStream(input, onChunk, onProgress, sessionId) {
|
|
292
|
+
const config = (0, parser_1.loadConfig)();
|
|
293
|
+
exports.logger.addEntry({ role: 'user', content: input }, sessionId);
|
|
294
|
+
const pluginTools = registry_1.pluginManager.getAllToolDefinitions();
|
|
295
|
+
let activeTools = [...pluginTools].filter(t => (0, skillManager_1.isSkillActive)(t.function.name));
|
|
296
|
+
const { sanitizeHistoryForLLM } = require('../utils/historySanitizer');
|
|
297
|
+
try {
|
|
298
|
+
let turnCount = 0;
|
|
299
|
+
const MAX_TURNS = 10;
|
|
300
|
+
let fullResponse = '';
|
|
301
|
+
while (turnCount < MAX_TURNS) {
|
|
302
|
+
turnCount++;
|
|
303
|
+
const currentHistory = exports.logger.getHistory(sessionId);
|
|
304
|
+
const sanitizedHistory = sanitizeHistoryForLLM(currentHistory, activeTools, config.llm.provider);
|
|
305
|
+
const messages = [
|
|
306
|
+
{ role: 'system', content: await getSystemPrompt('os', input) },
|
|
307
|
+
...sanitizedHistory
|
|
308
|
+
];
|
|
309
|
+
let streamedContent = '';
|
|
310
|
+
const response = await (0, llmUtils_1.executeWithRetry)(async (client) => {
|
|
311
|
+
return await client.stream({ model: config.llm.model, temperature: config.llm.temperature, messages, tools: activeTools }, (chunk) => {
|
|
312
|
+
streamedContent += chunk;
|
|
313
|
+
onChunk(chunk);
|
|
314
|
+
});
|
|
315
|
+
});
|
|
316
|
+
const responseMessage = response.message;
|
|
317
|
+
if (turnCount === 1)
|
|
318
|
+
tracker_1.Tracker.addMessage();
|
|
319
|
+
if (response.usage?.total_tokens)
|
|
320
|
+
tracker_1.Tracker.addTokens(response.usage.total_tokens, config.llm.provider);
|
|
321
|
+
tracker_1.Tracker.addEvent('llm.response', { provider: config.llm.provider, tool_calls: responseMessage.tool_calls?.length || 0 });
|
|
322
|
+
exports.logger.addEntry({
|
|
323
|
+
role: 'assistant',
|
|
324
|
+
content: responseMessage.content || '',
|
|
325
|
+
tool_calls: responseMessage.tool_calls,
|
|
326
|
+
}, sessionId);
|
|
327
|
+
if (!responseMessage.tool_calls || responseMessage.tool_calls.length === 0) {
|
|
328
|
+
let finalContent = responseMessage.content || 'No response generated.';
|
|
329
|
+
finalContent = finalContent.replace(/<(think|thought|thinking|reasoning|analysis|reflection)[\s\S]*?<\/\1>\n?/gi, '').trim();
|
|
330
|
+
fullResponse = finalContent;
|
|
331
|
+
break;
|
|
332
|
+
}
|
|
333
|
+
// Tool calls detected — pause stream visually and execute tools
|
|
334
|
+
const fastReturnTools = ['transfer_token', 'transfer_native', 'swap_token', 'bridge_token', 'mint_nft', 'custom_tx', 'revoke_approval', 'supply_aave', 'deposit_yield_vault', 'provide_liquidity_v3'];
|
|
335
|
+
let canFastReturnAll = true;
|
|
336
|
+
const accumulatedResults = [];
|
|
337
|
+
for (const _toolCall of responseMessage.tool_calls) {
|
|
338
|
+
const toolCall = _toolCall;
|
|
339
|
+
const toolName = toolCall.function.name;
|
|
340
|
+
let result = '';
|
|
341
|
+
let args = {};
|
|
342
|
+
console.log(picocolors_1.default.yellow(`[⚡ Tool Execution] AI is calling ${toolName}...`));
|
|
343
|
+
if (onProgress)
|
|
344
|
+
onProgress(`_⚡ Running tool: ${toolName}..._`);
|
|
345
|
+
try {
|
|
346
|
+
let argStr = toolCall.function.arguments;
|
|
347
|
+
if (argStr && !argStr.trim().endsWith('}'))
|
|
348
|
+
argStr += '}';
|
|
349
|
+
args = JSON.parse(argStr);
|
|
350
|
+
}
|
|
351
|
+
catch (parseError) {
|
|
352
|
+
result = `[System Error] Arguments for ${toolName} must be valid JSON. Error: ${parseError.message}`;
|
|
353
|
+
exports.logger.addEntry({ role: 'tool', tool_call_id: toolCall.id, content: result }, sessionId);
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
if (!(0, skillManager_1.isSkillActive)(toolName)) {
|
|
357
|
+
result = `[System Error] Access denied: Skill '${toolName}' is currently disabled.`;
|
|
358
|
+
exports.logger.addEntry({ role: 'tool', tool_call_id: toolCall.id, content: result }, sessionId);
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
try {
|
|
362
|
+
const pluginResult = await registry_1.pluginManager.executeTool(toolName, args, { sessionId });
|
|
363
|
+
result = pluginResult !== null ? pluginResult : `Error: Tool ${toolName} is not implemented.`;
|
|
364
|
+
if (result.includes('[Security Blocked]') || result.startsWith('Error:')) {
|
|
365
|
+
console.log(picocolors_1.default.red(`[❌ Failed] Tool ${toolName} returned an error or was blocked.`));
|
|
366
|
+
}
|
|
367
|
+
else {
|
|
368
|
+
console.log(picocolors_1.default.green(`[✅ Success] Tool ${toolName} executed successfully.`));
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
catch (toolError) {
|
|
372
|
+
result = `Error executing ${toolName}: ${toolError.message}`;
|
|
373
|
+
console.error(picocolors_1.default.red(`[❌ Error Crash] Execution of ${toolName} failed: ${toolError.message}`));
|
|
374
|
+
}
|
|
375
|
+
exports.logger.addEntry({ role: 'tool', tool_call_id: toolCall.id, name: toolName, content: result }, sessionId);
|
|
376
|
+
accumulatedResults.push(result);
|
|
377
|
+
if (!fastReturnTools.includes(toolName))
|
|
378
|
+
canFastReturnAll = false;
|
|
379
|
+
}
|
|
380
|
+
if (canFastReturnAll && accumulatedResults.length > 0) {
|
|
381
|
+
const finalContent = accumulatedResults.join('\n\n---\n\n');
|
|
382
|
+
exports.logger.addEntry({ role: 'assistant', content: finalContent }, sessionId);
|
|
383
|
+
onChunk(finalContent);
|
|
384
|
+
fullResponse = finalContent;
|
|
385
|
+
break;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
if (!fullResponse) {
|
|
389
|
+
const maxTurnMsg = '⚠️ Reached maximum interaction limit (10 turns). Please be more specific.';
|
|
390
|
+
exports.logger.addEntry({ role: 'assistant', content: maxTurnMsg }, sessionId);
|
|
391
|
+
fullResponse = maxTurnMsg;
|
|
392
|
+
}
|
|
393
|
+
return fullResponse;
|
|
394
|
+
}
|
|
395
|
+
catch (error) {
|
|
396
|
+
console.error('LLM Stream Error:', error);
|
|
397
|
+
const status = error?.status || error?.response?.status;
|
|
398
|
+
let errorMsg = '⚠️ All models are temporarily rate-limited. Please try again in a few minutes.';
|
|
399
|
+
if (status === 400 || (error.message && error.message.toLowerCase().includes('invalid'))) {
|
|
400
|
+
errorMsg = '⚠️ Failed to parse instruction. Please describe your command more specifically.';
|
|
401
|
+
}
|
|
402
|
+
exports.logger.addEntry({ role: 'assistant', content: errorMsg }, sessionId);
|
|
403
|
+
return errorMsg;
|
|
404
|
+
}
|
|
405
|
+
}
|