hedgequantx 2.7.21 → 2.7.22
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/package.json +1 -1
- package/src/app.js +12 -2
- package/src/menus/dashboard.js +2 -2
- package/src/pages/ai-agents-ui.js +185 -0
- package/src/pages/ai-agents.js +185 -300
- package/src/services/cliproxy.js +199 -0
package/package.json
CHANGED
package/src/app.js
CHANGED
|
@@ -126,7 +126,16 @@ const banner = async () => {
|
|
|
126
126
|
|
|
127
127
|
const tagline = isMobile ? `HQX v${version}` : `Prop Futures Algo Trading v${version}`;
|
|
128
128
|
console.log(chalk.cyan('║') + chalk.white(centerText(tagline, innerWidth)) + chalk.cyan('║'));
|
|
129
|
-
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Display banner with closed bottom (standalone)
|
|
133
|
+
*/
|
|
134
|
+
const bannerClosed = async () => {
|
|
135
|
+
await banner();
|
|
136
|
+
const termWidth = process.stdout.columns || 100;
|
|
137
|
+
const boxWidth = termWidth < 60 ? Math.max(termWidth - 2, 40) : Math.max(getLogoWidth(), 98);
|
|
138
|
+
console.log(chalk.cyan('╚' + '═'.repeat(boxWidth - 2) + '╝'));
|
|
130
139
|
};
|
|
131
140
|
|
|
132
141
|
const getFullLogo = () => [
|
|
@@ -187,7 +196,8 @@ const run = async () => {
|
|
|
187
196
|
const totalContentWidth = numCols * colWidth;
|
|
188
197
|
const leftMargin = Math.max(2, Math.floor((innerWidth - totalContentWidth) / 2));
|
|
189
198
|
|
|
190
|
-
|
|
199
|
+
// Continue from banner (connected rectangle)
|
|
200
|
+
console.log(chalk.cyan('╠' + '═'.repeat(innerWidth) + '╣'));
|
|
191
201
|
console.log(chalk.cyan('║') + chalk.white.bold(centerText('SELECT PROPFIRM', innerWidth)) + chalk.cyan('║'));
|
|
192
202
|
console.log(chalk.cyan('╠' + '═'.repeat(innerWidth) + '╣'));
|
|
193
203
|
|
package/src/menus/dashboard.js
CHANGED
|
@@ -30,8 +30,8 @@ const dashboardMenu = async (service) => {
|
|
|
30
30
|
return chalk.cyan('║') + content + ' '.repeat(Math.max(0, padding)) + chalk.cyan('║');
|
|
31
31
|
};
|
|
32
32
|
|
|
33
|
-
//
|
|
34
|
-
console.log(chalk.cyan('
|
|
33
|
+
// Continue from banner (connected rectangle)
|
|
34
|
+
console.log(chalk.cyan('╠' + '═'.repeat(W) + '╣'));
|
|
35
35
|
console.log(makeLine(chalk.yellow.bold('Welcome, HQX Trader!'), 'center'));
|
|
36
36
|
console.log(chalk.cyan('╠' + '═'.repeat(W) + '╣'));
|
|
37
37
|
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AI Agents UI Components
|
|
3
|
+
*
|
|
4
|
+
* UI drawing functions for the AI Agents configuration page.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
const chalk = require('chalk');
|
|
8
|
+
const { centerText, visibleLength } = require('../ui');
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Draw a 2-column row
|
|
12
|
+
* @param {string} leftText - Left column text
|
|
13
|
+
* @param {string} rightText - Right column text
|
|
14
|
+
* @param {number} W - Inner width
|
|
15
|
+
*/
|
|
16
|
+
const draw2ColRow = (leftText, rightText, W) => {
|
|
17
|
+
const col1Width = Math.floor(W / 2);
|
|
18
|
+
const col2Width = W - col1Width;
|
|
19
|
+
const leftLen = visibleLength(leftText);
|
|
20
|
+
const leftPad = col1Width - leftLen;
|
|
21
|
+
const leftPadL = Math.floor(leftPad / 2);
|
|
22
|
+
const rightLen = visibleLength(rightText || '');
|
|
23
|
+
const rightPad = col2Width - rightLen;
|
|
24
|
+
const rightPadL = Math.floor(rightPad / 2);
|
|
25
|
+
console.log(
|
|
26
|
+
chalk.cyan('║') +
|
|
27
|
+
' '.repeat(leftPadL) + leftText + ' '.repeat(leftPad - leftPadL) +
|
|
28
|
+
' '.repeat(rightPadL) + (rightText || '') + ' '.repeat(rightPad - rightPadL) +
|
|
29
|
+
chalk.cyan('║')
|
|
30
|
+
);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Draw 2-column table with title and back option
|
|
35
|
+
* @param {string} title - Table title
|
|
36
|
+
* @param {Function} titleColor - Chalk color function
|
|
37
|
+
* @param {Array} items - Items to display
|
|
38
|
+
* @param {string} backText - Back button text
|
|
39
|
+
* @param {number} W - Inner width
|
|
40
|
+
*/
|
|
41
|
+
const draw2ColTable = (title, titleColor, items, backText, W) => {
|
|
42
|
+
console.log(chalk.cyan('╔' + '═'.repeat(W) + '╗'));
|
|
43
|
+
console.log(chalk.cyan('║') + titleColor(centerText(title, W)) + chalk.cyan('║'));
|
|
44
|
+
console.log(chalk.cyan('╠' + '═'.repeat(W) + '╣'));
|
|
45
|
+
|
|
46
|
+
const rows = Math.ceil(items.length / 2);
|
|
47
|
+
for (let row = 0; row < rows; row++) {
|
|
48
|
+
const left = items[row];
|
|
49
|
+
const right = items[row + rows];
|
|
50
|
+
draw2ColRow(left || '', right || '', W);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
console.log(chalk.cyan('╠' + '─'.repeat(W) + '╣'));
|
|
54
|
+
console.log(chalk.cyan('║') + chalk.red(centerText(backText, W)) + chalk.cyan('║'));
|
|
55
|
+
console.log(chalk.cyan('╚' + '═'.repeat(W) + '╝'));
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Draw providers table
|
|
60
|
+
* @param {Array} providers - List of AI providers
|
|
61
|
+
* @param {Object} config - Current config
|
|
62
|
+
* @param {number} boxWidth - Box width
|
|
63
|
+
*/
|
|
64
|
+
const drawProvidersTable = (providers, config, boxWidth) => {
|
|
65
|
+
const W = boxWidth - 2;
|
|
66
|
+
const items = providers.map((p, i) => {
|
|
67
|
+
const status = config.providers[p.id]?.active ? chalk.green(' ●') : '';
|
|
68
|
+
return chalk.cyan(`[${i + 1}]`) + ' ' + chalk[p.color](p.name) + status;
|
|
69
|
+
});
|
|
70
|
+
draw2ColTable('AI AGENTS CONFIGURATION', chalk.yellow.bold, items, '[B] Back to Menu', W);
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Draw models table
|
|
75
|
+
* @param {Object} provider - Provider object
|
|
76
|
+
* @param {Array} models - List of models
|
|
77
|
+
* @param {number} boxWidth - Box width
|
|
78
|
+
*/
|
|
79
|
+
const drawModelsTable = (provider, models, boxWidth) => {
|
|
80
|
+
const W = boxWidth - 2;
|
|
81
|
+
const items = models.map((m, i) => chalk.cyan(`[${i + 1}]`) + ' ' + chalk.white(m.name));
|
|
82
|
+
draw2ColTable(`${provider.name.toUpperCase()} - MODELS`, chalk[provider.color].bold, items, '[B] Back', W);
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Draw provider configuration window
|
|
87
|
+
* @param {Object} provider - Provider object
|
|
88
|
+
* @param {Object} config - Current config
|
|
89
|
+
* @param {number} boxWidth - Box width
|
|
90
|
+
*/
|
|
91
|
+
const drawProviderWindow = (provider, config, boxWidth) => {
|
|
92
|
+
const W = boxWidth - 2;
|
|
93
|
+
const col1Width = Math.floor(W / 2);
|
|
94
|
+
const col2Width = W - col1Width;
|
|
95
|
+
const providerConfig = config.providers[provider.id] || {};
|
|
96
|
+
|
|
97
|
+
// Header
|
|
98
|
+
console.log(chalk.cyan('╔' + '═'.repeat(W) + '╗'));
|
|
99
|
+
console.log(chalk.cyan('║') + chalk[provider.color].bold(centerText(provider.name.toUpperCase(), W)) + chalk.cyan('║'));
|
|
100
|
+
console.log(chalk.cyan('╠' + '═'.repeat(W) + '╣'));
|
|
101
|
+
|
|
102
|
+
// Empty line
|
|
103
|
+
console.log(chalk.cyan('║') + ' '.repeat(W) + chalk.cyan('║'));
|
|
104
|
+
|
|
105
|
+
// Options in 2 columns
|
|
106
|
+
const opt1Title = '[1] Connect via Paid Plan';
|
|
107
|
+
const opt1Desc = 'Uses CLIProxy - No API key needed';
|
|
108
|
+
const opt2Title = '[2] Connect via API Key';
|
|
109
|
+
const opt2Desc = 'Enter your own API key';
|
|
110
|
+
|
|
111
|
+
// Row 1: Titles
|
|
112
|
+
const left1 = chalk.green(opt1Title);
|
|
113
|
+
const right1 = chalk.yellow(opt2Title);
|
|
114
|
+
const left1Len = visibleLength(left1);
|
|
115
|
+
const right1Len = visibleLength(right1);
|
|
116
|
+
const left1PadTotal = col1Width - left1Len;
|
|
117
|
+
const left1PadL = Math.floor(left1PadTotal / 2);
|
|
118
|
+
const left1PadR = left1PadTotal - left1PadL;
|
|
119
|
+
const right1PadTotal = col2Width - right1Len;
|
|
120
|
+
const right1PadL = Math.floor(right1PadTotal / 2);
|
|
121
|
+
const right1PadR = right1PadTotal - right1PadL;
|
|
122
|
+
|
|
123
|
+
console.log(
|
|
124
|
+
chalk.cyan('║') +
|
|
125
|
+
' '.repeat(left1PadL) + left1 + ' '.repeat(left1PadR) +
|
|
126
|
+
' '.repeat(right1PadL) + right1 + ' '.repeat(right1PadR) +
|
|
127
|
+
chalk.cyan('║')
|
|
128
|
+
);
|
|
129
|
+
|
|
130
|
+
// Row 2: Descriptions
|
|
131
|
+
const left2 = chalk.gray(opt1Desc);
|
|
132
|
+
const right2 = chalk.gray(opt2Desc);
|
|
133
|
+
const left2Len = visibleLength(left2);
|
|
134
|
+
const right2Len = visibleLength(right2);
|
|
135
|
+
const left2PadTotal = col1Width - left2Len;
|
|
136
|
+
const left2PadL = Math.floor(left2PadTotal / 2);
|
|
137
|
+
const left2PadR = left2PadTotal - left2PadL;
|
|
138
|
+
const right2PadTotal = col2Width - right2Len;
|
|
139
|
+
const right2PadL = Math.floor(right2PadTotal / 2);
|
|
140
|
+
const right2PadR = right2PadTotal - right2PadL;
|
|
141
|
+
|
|
142
|
+
console.log(
|
|
143
|
+
chalk.cyan('║') +
|
|
144
|
+
' '.repeat(left2PadL) + left2 + ' '.repeat(left2PadR) +
|
|
145
|
+
' '.repeat(right2PadL) + right2 + ' '.repeat(right2PadR) +
|
|
146
|
+
chalk.cyan('║')
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
// Empty line
|
|
150
|
+
console.log(chalk.cyan('║') + ' '.repeat(W) + chalk.cyan('║'));
|
|
151
|
+
|
|
152
|
+
// Status bar
|
|
153
|
+
console.log(chalk.cyan('╠' + '─'.repeat(W) + '╣'));
|
|
154
|
+
|
|
155
|
+
let statusText = '';
|
|
156
|
+
if (providerConfig.active) {
|
|
157
|
+
const connType = providerConfig.connectionType === 'cliproxy' ? 'CLIProxy' : 'API Key';
|
|
158
|
+
const modelName = providerConfig.modelName || 'N/A';
|
|
159
|
+
statusText = chalk.green('● ACTIVE') + chalk.gray(' Model: ') + chalk.yellow(modelName) + chalk.gray(' via ') + chalk.cyan(connType);
|
|
160
|
+
} else if (providerConfig.apiKey || providerConfig.connectionType) {
|
|
161
|
+
statusText = chalk.yellow('● CONFIGURED') + chalk.gray(' (not active)');
|
|
162
|
+
} else {
|
|
163
|
+
statusText = chalk.gray('○ NOT CONFIGURED');
|
|
164
|
+
}
|
|
165
|
+
console.log(chalk.cyan('║') + centerText(statusText, W) + chalk.cyan('║'));
|
|
166
|
+
|
|
167
|
+
// Disconnect option if active
|
|
168
|
+
if (providerConfig.active) {
|
|
169
|
+
console.log(chalk.cyan('╠' + '─'.repeat(W) + '╣'));
|
|
170
|
+
console.log(chalk.cyan('║') + chalk.red(centerText('[D] Disconnect', W)) + chalk.cyan('║'));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Back
|
|
174
|
+
console.log(chalk.cyan('╠' + '─'.repeat(W) + '╣'));
|
|
175
|
+
console.log(chalk.cyan('║') + chalk.red(centerText('[B] Back', W)) + chalk.cyan('║'));
|
|
176
|
+
console.log(chalk.cyan('╚' + '═'.repeat(W) + '╝'));
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
module.exports = {
|
|
180
|
+
draw2ColRow,
|
|
181
|
+
draw2ColTable,
|
|
182
|
+
drawProvidersTable,
|
|
183
|
+
drawModelsTable,
|
|
184
|
+
drawProviderWindow
|
|
185
|
+
};
|
package/src/pages/ai-agents.js
CHANGED
|
@@ -9,11 +9,13 @@ const chalk = require('chalk');
|
|
|
9
9
|
const os = require('os');
|
|
10
10
|
const path = require('path');
|
|
11
11
|
const fs = require('fs');
|
|
12
|
-
|
|
13
12
|
const ora = require('ora');
|
|
14
|
-
|
|
13
|
+
|
|
14
|
+
const { getLogoWidth } = require('../ui');
|
|
15
15
|
const { prompts } = require('../utils');
|
|
16
16
|
const { fetchModelsFromApi } = require('./ai-models');
|
|
17
|
+
const { drawProvidersTable, drawModelsTable, drawProviderWindow } = require('./ai-agents-ui');
|
|
18
|
+
const { isCliProxyRunning, fetchModelsFromCliProxy, getOAuthUrl, checkOAuthStatus } = require('../services/cliproxy');
|
|
17
19
|
|
|
18
20
|
// Config file path
|
|
19
21
|
const CONFIG_DIR = path.join(os.homedir(), '.hqx');
|
|
@@ -31,32 +33,20 @@ const AI_PROVIDERS = [
|
|
|
31
33
|
{ id: 'openrouter', name: 'OpenRouter', color: 'gray' },
|
|
32
34
|
];
|
|
33
35
|
|
|
34
|
-
/**
|
|
35
|
-
* Load AI config from file
|
|
36
|
-
* @returns {Object} Config object with provider settings
|
|
37
|
-
*/
|
|
36
|
+
/** Load AI config from file */
|
|
38
37
|
const loadConfig = () => {
|
|
39
38
|
try {
|
|
40
39
|
if (fs.existsSync(CONFIG_FILE)) {
|
|
41
|
-
|
|
42
|
-
return JSON.parse(data);
|
|
40
|
+
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
|
|
43
41
|
}
|
|
44
|
-
} catch (error) {
|
|
45
|
-
// Config file doesn't exist or is invalid
|
|
46
|
-
}
|
|
42
|
+
} catch (error) { /* ignore */ }
|
|
47
43
|
return { providers: {} };
|
|
48
44
|
};
|
|
49
45
|
|
|
50
|
-
/**
|
|
51
|
-
* Save AI config to file
|
|
52
|
-
* @param {Object} config - Config object to save
|
|
53
|
-
* @returns {boolean} Success status
|
|
54
|
-
*/
|
|
46
|
+
/** Save AI config to file */
|
|
55
47
|
const saveConfig = (config) => {
|
|
56
48
|
try {
|
|
57
|
-
if (!fs.existsSync(CONFIG_DIR)) {
|
|
58
|
-
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
59
|
-
}
|
|
49
|
+
if (!fs.existsSync(CONFIG_DIR)) fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
60
50
|
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
|
|
61
51
|
return true;
|
|
62
52
|
} catch (error) {
|
|
@@ -64,87 +54,28 @@ const saveConfig = (config) => {
|
|
|
64
54
|
}
|
|
65
55
|
};
|
|
66
56
|
|
|
67
|
-
/**
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
const leftLen = visibleLength(leftText);
|
|
84
|
-
const leftPad = col1Width - leftLen;
|
|
85
|
-
const leftPadL = Math.floor(leftPad / 2);
|
|
86
|
-
const rightLen = visibleLength(rightText || '');
|
|
87
|
-
const rightPad = col2Width - rightLen;
|
|
88
|
-
const rightPadL = Math.floor(rightPad / 2);
|
|
89
|
-
console.log(
|
|
90
|
-
chalk.cyan('║') +
|
|
91
|
-
' '.repeat(leftPadL) + leftText + ' '.repeat(leftPad - leftPadL) +
|
|
92
|
-
' '.repeat(rightPadL) + (rightText || '') + ' '.repeat(rightPad - rightPadL) +
|
|
93
|
-
chalk.cyan('║')
|
|
94
|
-
);
|
|
95
|
-
};
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Draw 2-column table
|
|
99
|
-
*/
|
|
100
|
-
const draw2ColTable = (title, titleColor, items, backText, W) => {
|
|
101
|
-
console.log(chalk.cyan('╔' + '═'.repeat(W) + '╗'));
|
|
102
|
-
console.log(chalk.cyan('║') + titleColor(centerText(title, W)) + chalk.cyan('║'));
|
|
103
|
-
console.log(chalk.cyan('╠' + '═'.repeat(W) + '╣'));
|
|
104
|
-
|
|
105
|
-
const rows = Math.ceil(items.length / 2);
|
|
106
|
-
for (let row = 0; row < rows; row++) {
|
|
107
|
-
const left = items[row];
|
|
108
|
-
const right = items[row + rows];
|
|
109
|
-
draw2ColRow(left || '', right || '', W);
|
|
57
|
+
/** Select a model from a pre-fetched list */
|
|
58
|
+
const selectModelFromList = async (provider, models, boxWidth) => {
|
|
59
|
+
while (true) {
|
|
60
|
+
console.clear();
|
|
61
|
+
drawModelsTable(provider, models, boxWidth);
|
|
62
|
+
|
|
63
|
+
const input = await prompts.textInput(chalk.cyan('Select model: '));
|
|
64
|
+
const choice = (input || '').toLowerCase().trim();
|
|
65
|
+
|
|
66
|
+
if (choice === 'b' || choice === '') return null;
|
|
67
|
+
|
|
68
|
+
const num = parseInt(choice);
|
|
69
|
+
if (!isNaN(num) && num >= 1 && num <= models.length) return models[num - 1];
|
|
70
|
+
|
|
71
|
+
console.log(chalk.red(' Invalid option.'));
|
|
72
|
+
await new Promise(r => setTimeout(r, 1000));
|
|
110
73
|
}
|
|
111
|
-
|
|
112
|
-
console.log(chalk.cyan('╠' + '─'.repeat(W) + '╣'));
|
|
113
|
-
console.log(chalk.cyan('║') + chalk.red(centerText(backText, W)) + chalk.cyan('║'));
|
|
114
|
-
console.log(chalk.cyan('╚' + '═'.repeat(W) + '╝'));
|
|
115
|
-
};
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Draw providers table
|
|
119
|
-
*/
|
|
120
|
-
const drawProvidersTable = (config, boxWidth) => {
|
|
121
|
-
const W = boxWidth - 2;
|
|
122
|
-
const items = AI_PROVIDERS.map((p, i) => {
|
|
123
|
-
const status = config.providers[p.id]?.active ? chalk.green(' ●') : '';
|
|
124
|
-
return chalk.cyan(`[${i + 1}]`) + ' ' + chalk[p.color](p.name) + status;
|
|
125
|
-
});
|
|
126
|
-
draw2ColTable('AI AGENTS CONFIGURATION', chalk.yellow.bold, items, '[B] Back to Menu', W);
|
|
127
|
-
};
|
|
128
|
-
|
|
129
|
-
/**
|
|
130
|
-
* Draw models table
|
|
131
|
-
*/
|
|
132
|
-
const drawModelsTable = (provider, models, boxWidth) => {
|
|
133
|
-
const W = boxWidth - 2;
|
|
134
|
-
const items = models.map((m, i) => chalk.cyan(`[${i + 1}]`) + ' ' + chalk.white(m.name));
|
|
135
|
-
draw2ColTable(`${provider.name.toUpperCase()} - MODELS`, chalk[provider.color].bold, items, '[B] Back', W);
|
|
136
74
|
};
|
|
137
75
|
|
|
138
|
-
/**
|
|
139
|
-
* Select a model for a provider (fetches from API)
|
|
140
|
-
* @param {Object} provider - Provider object
|
|
141
|
-
* @param {string} apiKey - API key for fetching models
|
|
142
|
-
* @returns {Object|null} Selected model or null if cancelled/failed
|
|
143
|
-
*/
|
|
76
|
+
/** Select a model for a provider (fetches from API) */
|
|
144
77
|
const selectModel = async (provider, apiKey) => {
|
|
145
78
|
const boxWidth = getLogoWidth();
|
|
146
|
-
|
|
147
|
-
// Fetch models from API
|
|
148
79
|
const spinner = ora({ text: 'Fetching models from API...', color: 'yellow' }).start();
|
|
149
80
|
const result = await fetchModelsFromApi(provider.id, apiKey);
|
|
150
81
|
|
|
@@ -155,129 +86,167 @@ const selectModel = async (provider, apiKey) => {
|
|
|
155
86
|
}
|
|
156
87
|
|
|
157
88
|
spinner.succeed(`Found ${result.models.length} models`);
|
|
158
|
-
|
|
89
|
+
return selectModelFromList(provider, result.models, boxWidth);
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/** Deactivate all providers and activate one */
|
|
93
|
+
const activateProvider = (config, providerId, data) => {
|
|
94
|
+
Object.keys(config.providers).forEach(id => {
|
|
95
|
+
if (config.providers[id]) config.providers[id].active = false;
|
|
96
|
+
});
|
|
97
|
+
if (!config.providers[providerId]) config.providers[providerId] = {};
|
|
98
|
+
Object.assign(config.providers[providerId], data, { active: true, configuredAt: new Date().toISOString() });
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** Handle CLIProxy connection */
|
|
102
|
+
const handleCliProxyConnection = async (provider, config, boxWidth) => {
|
|
103
|
+
console.log();
|
|
104
|
+
const spinner = ora({ text: 'Checking CLIProxy status...', color: 'yellow' }).start();
|
|
105
|
+
const proxyStatus = await isCliProxyRunning();
|
|
159
106
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
107
|
+
if (!proxyStatus.running) {
|
|
108
|
+
spinner.fail('CLIProxy is not running');
|
|
109
|
+
console.log(chalk.yellow('\n CLIProxy must be running on localhost:8317'));
|
|
110
|
+
console.log(chalk.gray(' Install: https://help.router-for.me\n'));
|
|
111
|
+
await prompts.waitForEnter();
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
spinner.succeed('CLIProxy is running');
|
|
116
|
+
const oauthResult = await getOAuthUrl(provider.id);
|
|
117
|
+
|
|
118
|
+
if (!oauthResult.success) {
|
|
119
|
+
// OAuth not supported - try direct model fetch
|
|
120
|
+
console.log(chalk.gray(` OAuth not available for ${provider.name}, checking models...`));
|
|
121
|
+
const modelsResult = await fetchModelsFromCliProxy();
|
|
166
122
|
|
|
167
|
-
if (
|
|
168
|
-
|
|
123
|
+
if (!modelsResult.success || modelsResult.models.length === 0) {
|
|
124
|
+
console.log(chalk.red(` No models available via CLIProxy for ${provider.name}`));
|
|
125
|
+
console.log(chalk.gray(` Error: ${modelsResult.error || 'Unknown'}`));
|
|
126
|
+
await prompts.waitForEnter();
|
|
127
|
+
return false;
|
|
169
128
|
}
|
|
170
129
|
|
|
171
|
-
const
|
|
172
|
-
if (!
|
|
173
|
-
return models[num - 1];
|
|
174
|
-
}
|
|
130
|
+
const selectedModel = await selectModelFromList(provider, modelsResult.models, boxWidth);
|
|
131
|
+
if (!selectedModel) return false;
|
|
175
132
|
|
|
176
|
-
|
|
177
|
-
|
|
133
|
+
activateProvider(config, provider.id, {
|
|
134
|
+
connectionType: 'cliproxy',
|
|
135
|
+
modelId: selectedModel.id,
|
|
136
|
+
modelName: selectedModel.name
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
if (saveConfig(config)) {
|
|
140
|
+
console.log(chalk.green(`\n ✓ ${provider.name} connected via CLIProxy.`));
|
|
141
|
+
console.log(chalk.cyan(` Model: ${selectedModel.name}`));
|
|
142
|
+
}
|
|
143
|
+
await prompts.waitForEnter();
|
|
144
|
+
return true;
|
|
178
145
|
}
|
|
179
|
-
};
|
|
180
|
-
|
|
181
|
-
/**
|
|
182
|
-
* Draw provider configuration window
|
|
183
|
-
* @param {Object} provider - Provider object
|
|
184
|
-
* @param {Object} config - Current config
|
|
185
|
-
* @param {number} boxWidth - Box width
|
|
186
|
-
*/
|
|
187
|
-
const drawProviderWindow = (provider, config, boxWidth) => {
|
|
188
|
-
const W = boxWidth - 2;
|
|
189
|
-
const col1Width = Math.floor(W / 2);
|
|
190
|
-
const col2Width = W - col1Width;
|
|
191
|
-
const providerConfig = config.providers[provider.id] || {};
|
|
192
146
|
|
|
193
|
-
//
|
|
194
|
-
console.log(chalk.cyan('
|
|
195
|
-
console.log(chalk.
|
|
196
|
-
console.log(chalk.
|
|
147
|
+
// OAuth flow
|
|
148
|
+
console.log(chalk.cyan('\n Open this URL in your browser to authenticate:\n'));
|
|
149
|
+
console.log(chalk.yellow(` ${oauthResult.url}\n`));
|
|
150
|
+
console.log(chalk.gray(' Waiting for authentication... (Press Enter to cancel)'));
|
|
197
151
|
|
|
198
|
-
|
|
199
|
-
|
|
152
|
+
let authenticated = false;
|
|
153
|
+
const maxWait = 120000, pollInterval = 3000;
|
|
154
|
+
let waited = 0;
|
|
200
155
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
156
|
+
const pollPromise = (async () => {
|
|
157
|
+
while (waited < maxWait) {
|
|
158
|
+
await new Promise(r => setTimeout(r, pollInterval));
|
|
159
|
+
waited += pollInterval;
|
|
160
|
+
if (oauthResult.state) {
|
|
161
|
+
const statusResult = await checkOAuthStatus(oauthResult.state);
|
|
162
|
+
if (statusResult.success && statusResult.status === 'ok') { authenticated = true; return true; }
|
|
163
|
+
if (statusResult.status === 'error') {
|
|
164
|
+
console.log(chalk.red(`\n Authentication error: ${statusResult.error || 'Unknown'}`));
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return false;
|
|
170
|
+
})();
|
|
206
171
|
|
|
207
|
-
|
|
208
|
-
const left1 = chalk.green(opt1Title);
|
|
209
|
-
const right1 = chalk.yellow(opt2Title);
|
|
210
|
-
const left1Len = visibleLength(left1);
|
|
211
|
-
const right1Len = visibleLength(right1);
|
|
212
|
-
const left1PadTotal = col1Width - left1Len;
|
|
213
|
-
const left1PadL = Math.floor(left1PadTotal / 2);
|
|
214
|
-
const left1PadR = left1PadTotal - left1PadL;
|
|
215
|
-
const right1PadTotal = col2Width - right1Len;
|
|
216
|
-
const right1PadL = Math.floor(right1PadTotal / 2);
|
|
217
|
-
const right1PadR = right1PadTotal - right1PadL;
|
|
172
|
+
await Promise.race([pollPromise, prompts.waitForEnter()]);
|
|
218
173
|
|
|
219
|
-
|
|
220
|
-
chalk.
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
);
|
|
174
|
+
if (!authenticated) {
|
|
175
|
+
console.log(chalk.yellow(' Authentication cancelled or timed out.'));
|
|
176
|
+
await prompts.waitForEnter();
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
225
179
|
|
|
226
|
-
|
|
227
|
-
const left2 = chalk.gray(opt1Desc);
|
|
228
|
-
const right2 = chalk.gray(opt2Desc);
|
|
229
|
-
const left2Len = visibleLength(left2);
|
|
230
|
-
const right2Len = visibleLength(right2);
|
|
231
|
-
const left2PadTotal = col1Width - left2Len;
|
|
232
|
-
const left2PadL = Math.floor(left2PadTotal / 2);
|
|
233
|
-
const left2PadR = left2PadTotal - left2PadL;
|
|
234
|
-
const right2PadTotal = col2Width - right2Len;
|
|
235
|
-
const right2PadL = Math.floor(right2PadTotal / 2);
|
|
236
|
-
const right2PadR = right2PadTotal - right2PadL;
|
|
180
|
+
console.log(chalk.green(' ✓ Authentication successful!'));
|
|
237
181
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
182
|
+
const modelsResult = await fetchModelsFromCliProxy();
|
|
183
|
+
if (modelsResult.success && modelsResult.models.length > 0) {
|
|
184
|
+
const selectedModel = await selectModelFromList(provider, modelsResult.models, boxWidth);
|
|
185
|
+
if (selectedModel) {
|
|
186
|
+
activateProvider(config, provider.id, {
|
|
187
|
+
connectionType: 'cliproxy',
|
|
188
|
+
modelId: selectedModel.id,
|
|
189
|
+
modelName: selectedModel.name
|
|
190
|
+
});
|
|
191
|
+
if (saveConfig(config)) {
|
|
192
|
+
console.log(chalk.green(`\n ✓ ${provider.name} connected via CLIProxy.`));
|
|
193
|
+
console.log(chalk.cyan(` Model: ${selectedModel.name}`));
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
} else {
|
|
197
|
+
activateProvider(config, provider.id, {
|
|
198
|
+
connectionType: 'cliproxy',
|
|
199
|
+
modelId: null,
|
|
200
|
+
modelName: 'Default'
|
|
201
|
+
});
|
|
202
|
+
if (saveConfig(config)) console.log(chalk.green(`\n ✓ ${provider.name} connected via CLIProxy.`));
|
|
203
|
+
}
|
|
244
204
|
|
|
245
|
-
|
|
246
|
-
|
|
205
|
+
await prompts.waitForEnter();
|
|
206
|
+
return true;
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/** Handle API Key connection */
|
|
210
|
+
const handleApiKeyConnection = async (provider, config) => {
|
|
211
|
+
console.clear();
|
|
212
|
+
console.log(chalk.yellow(`\n Enter your ${provider.name} API key:`));
|
|
213
|
+
console.log(chalk.gray(' (Press Enter to cancel)\n'));
|
|
247
214
|
|
|
248
|
-
|
|
249
|
-
console.log(chalk.cyan('╠' + '─'.repeat(W) + '╣'));
|
|
215
|
+
const apiKey = await prompts.textInput(chalk.cyan(' API Key: '), true);
|
|
250
216
|
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
statusText = chalk.green('● ACTIVE') + chalk.gray(' Model: ') + chalk.yellow(modelName) + chalk.gray(' via ') + chalk.cyan(connType);
|
|
256
|
-
} else if (providerConfig.apiKey || providerConfig.connectionType) {
|
|
257
|
-
statusText = chalk.yellow('● CONFIGURED') + chalk.gray(' (not active)');
|
|
258
|
-
} else {
|
|
259
|
-
statusText = chalk.gray('○ NOT CONFIGURED');
|
|
217
|
+
if (!apiKey || apiKey.trim() === '') {
|
|
218
|
+
console.log(chalk.gray(' Cancelled.'));
|
|
219
|
+
await prompts.waitForEnter();
|
|
220
|
+
return false;
|
|
260
221
|
}
|
|
261
|
-
console.log(chalk.cyan('║') + centerText(statusText, W) + chalk.cyan('║'));
|
|
262
222
|
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
223
|
+
if (apiKey.length < 20) {
|
|
224
|
+
console.log(chalk.red(' Invalid API key format (too short).'));
|
|
225
|
+
await prompts.waitForEnter();
|
|
226
|
+
return false;
|
|
267
227
|
}
|
|
268
228
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
229
|
+
const selectedModel = await selectModel(provider, apiKey.trim());
|
|
230
|
+
if (!selectedModel) return false;
|
|
231
|
+
|
|
232
|
+
activateProvider(config, provider.id, {
|
|
233
|
+
connectionType: 'apikey',
|
|
234
|
+
apiKey: apiKey.trim(),
|
|
235
|
+
modelId: selectedModel.id,
|
|
236
|
+
modelName: selectedModel.name
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
if (saveConfig(config)) {
|
|
240
|
+
console.log(chalk.green(`\n ✓ ${provider.name} connected via API Key.`));
|
|
241
|
+
console.log(chalk.cyan(` Model: ${selectedModel.name}`));
|
|
242
|
+
} else {
|
|
243
|
+
console.log(chalk.red('\n Failed to save config.'));
|
|
244
|
+
}
|
|
245
|
+
await prompts.waitForEnter();
|
|
246
|
+
return true;
|
|
273
247
|
};
|
|
274
248
|
|
|
275
|
-
/**
|
|
276
|
-
* Handle provider configuration
|
|
277
|
-
* @param {Object} provider - Provider to configure
|
|
278
|
-
* @param {Object} config - Current config
|
|
279
|
-
* @returns {Object} Updated config
|
|
280
|
-
*/
|
|
249
|
+
/** Handle provider configuration */
|
|
281
250
|
const handleProviderConfig = async (provider, config) => {
|
|
282
251
|
const boxWidth = getLogoWidth();
|
|
283
252
|
|
|
@@ -288,94 +257,23 @@ const handleProviderConfig = async (provider, config) => {
|
|
|
288
257
|
const input = await prompts.textInput(chalk.cyan('Select option: '));
|
|
289
258
|
const choice = (input || '').toLowerCase().trim();
|
|
290
259
|
|
|
291
|
-
if (choice === 'b' || choice === '')
|
|
292
|
-
break;
|
|
293
|
-
}
|
|
260
|
+
if (choice === 'b' || choice === '') break;
|
|
294
261
|
|
|
295
|
-
if (choice === 'd') {
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
console.log(chalk.yellow(`\n ${provider.name} disconnected.`));
|
|
301
|
-
await prompts.waitForEnter();
|
|
302
|
-
}
|
|
262
|
+
if (choice === 'd' && config.providers[provider.id]) {
|
|
263
|
+
config.providers[provider.id].active = false;
|
|
264
|
+
saveConfig(config);
|
|
265
|
+
console.log(chalk.yellow(`\n ${provider.name} disconnected.`));
|
|
266
|
+
await prompts.waitForEnter();
|
|
303
267
|
continue;
|
|
304
268
|
}
|
|
305
269
|
|
|
306
270
|
if (choice === '1') {
|
|
307
|
-
|
|
308
|
-
console.log();
|
|
309
|
-
console.log(chalk.cyan(' CLIProxy uses your paid plan subscription.'));
|
|
310
|
-
console.log(chalk.gray(' Model selection will be available after connecting.'));
|
|
311
|
-
console.log();
|
|
312
|
-
|
|
313
|
-
// Deactivate all other providers
|
|
314
|
-
Object.keys(config.providers).forEach(id => {
|
|
315
|
-
if (config.providers[id]) config.providers[id].active = false;
|
|
316
|
-
});
|
|
317
|
-
|
|
318
|
-
if (!config.providers[provider.id]) config.providers[provider.id] = {};
|
|
319
|
-
config.providers[provider.id].connectionType = 'cliproxy';
|
|
320
|
-
config.providers[provider.id].modelId = null;
|
|
321
|
-
config.providers[provider.id].modelName = 'N/A';
|
|
322
|
-
config.providers[provider.id].active = true;
|
|
323
|
-
config.providers[provider.id].configuredAt = new Date().toISOString();
|
|
324
|
-
|
|
325
|
-
if (saveConfig(config)) {
|
|
326
|
-
console.log(chalk.green(` ✓ ${provider.name} connected via CLIProxy.`));
|
|
327
|
-
} else {
|
|
328
|
-
console.log(chalk.red(' Failed to save config.'));
|
|
329
|
-
}
|
|
330
|
-
await prompts.waitForEnter();
|
|
271
|
+
await handleCliProxyConnection(provider, config, boxWidth);
|
|
331
272
|
continue;
|
|
332
273
|
}
|
|
333
274
|
|
|
334
275
|
if (choice === '2') {
|
|
335
|
-
|
|
336
|
-
console.clear();
|
|
337
|
-
console.log(chalk.yellow(`\n Enter your ${provider.name} API key:`));
|
|
338
|
-
console.log(chalk.gray(' (Press Enter to cancel)'));
|
|
339
|
-
console.log();
|
|
340
|
-
|
|
341
|
-
const apiKey = await prompts.textInput(chalk.cyan(' API Key: '), true);
|
|
342
|
-
|
|
343
|
-
if (!apiKey || apiKey.trim() === '') {
|
|
344
|
-
console.log(chalk.gray(' Cancelled.'));
|
|
345
|
-
await prompts.waitForEnter();
|
|
346
|
-
continue;
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
if (apiKey.length < 20) {
|
|
350
|
-
console.log(chalk.red(' Invalid API key format (too short).'));
|
|
351
|
-
await prompts.waitForEnter();
|
|
352
|
-
continue;
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
// Fetch models from API with the provided key
|
|
356
|
-
const selectedModel = await selectModel(provider, apiKey.trim());
|
|
357
|
-
if (!selectedModel) continue;
|
|
358
|
-
|
|
359
|
-
// Deactivate all other providers
|
|
360
|
-
Object.keys(config.providers).forEach(id => {
|
|
361
|
-
if (config.providers[id]) config.providers[id].active = false;
|
|
362
|
-
});
|
|
363
|
-
|
|
364
|
-
if (!config.providers[provider.id]) config.providers[provider.id] = {};
|
|
365
|
-
config.providers[provider.id].connectionType = 'apikey';
|
|
366
|
-
config.providers[provider.id].apiKey = apiKey.trim();
|
|
367
|
-
config.providers[provider.id].modelId = selectedModel.id;
|
|
368
|
-
config.providers[provider.id].modelName = selectedModel.name;
|
|
369
|
-
config.providers[provider.id].active = true;
|
|
370
|
-
config.providers[provider.id].configuredAt = new Date().toISOString();
|
|
371
|
-
|
|
372
|
-
if (saveConfig(config)) {
|
|
373
|
-
console.log(chalk.green(`\n ✓ ${provider.name} connected via API Key.`));
|
|
374
|
-
console.log(chalk.cyan(` Model: ${selectedModel.name}`));
|
|
375
|
-
} else {
|
|
376
|
-
console.log(chalk.red('\n Failed to save config.'));
|
|
377
|
-
}
|
|
378
|
-
await prompts.waitForEnter();
|
|
276
|
+
await handleApiKeyConnection(provider, config);
|
|
379
277
|
continue;
|
|
380
278
|
}
|
|
381
279
|
}
|
|
@@ -383,54 +281,41 @@ const handleProviderConfig = async (provider, config) => {
|
|
|
383
281
|
return config;
|
|
384
282
|
};
|
|
385
283
|
|
|
386
|
-
/**
|
|
387
|
-
* Get active AI provider config
|
|
388
|
-
* @returns {Object|null} Active provider config or null
|
|
389
|
-
*/
|
|
284
|
+
/** Get active AI provider config */
|
|
390
285
|
const getActiveProvider = () => {
|
|
391
286
|
const config = loadConfig();
|
|
392
287
|
for (const provider of AI_PROVIDERS) {
|
|
393
|
-
const
|
|
394
|
-
if (
|
|
288
|
+
const pc = config.providers[provider.id];
|
|
289
|
+
if (pc && pc.active) {
|
|
395
290
|
return {
|
|
396
291
|
id: provider.id,
|
|
397
292
|
name: provider.name,
|
|
398
|
-
connectionType:
|
|
399
|
-
apiKey:
|
|
400
|
-
modelId:
|
|
401
|
-
modelName:
|
|
293
|
+
connectionType: pc.connectionType,
|
|
294
|
+
apiKey: pc.apiKey || null,
|
|
295
|
+
modelId: pc.modelId || null,
|
|
296
|
+
modelName: pc.modelName || null
|
|
402
297
|
};
|
|
403
298
|
}
|
|
404
299
|
}
|
|
405
300
|
return null;
|
|
406
301
|
};
|
|
407
302
|
|
|
408
|
-
/**
|
|
409
|
-
|
|
410
|
-
* @returns {number} Number of active agents (0 or 1)
|
|
411
|
-
*/
|
|
412
|
-
const getActiveAgentCount = () => {
|
|
413
|
-
const active = getActiveProvider();
|
|
414
|
-
return active ? 1 : 0;
|
|
415
|
-
};
|
|
303
|
+
/** Count active AI agents */
|
|
304
|
+
const getActiveAgentCount = () => getActiveProvider() ? 1 : 0;
|
|
416
305
|
|
|
417
|
-
/**
|
|
418
|
-
* Main AI Agents menu
|
|
419
|
-
*/
|
|
306
|
+
/** Main AI Agents menu */
|
|
420
307
|
const aiAgentsMenu = async () => {
|
|
421
308
|
let config = loadConfig();
|
|
422
309
|
const boxWidth = getLogoWidth();
|
|
423
310
|
|
|
424
311
|
while (true) {
|
|
425
312
|
console.clear();
|
|
426
|
-
drawProvidersTable(config, boxWidth);
|
|
313
|
+
drawProvidersTable(AI_PROVIDERS, config, boxWidth);
|
|
427
314
|
|
|
428
315
|
const input = await prompts.textInput(chalk.cyan('Select provider: '));
|
|
429
316
|
const choice = (input || '').toLowerCase().trim();
|
|
430
317
|
|
|
431
|
-
if (choice === 'b' || choice === '')
|
|
432
|
-
break;
|
|
433
|
-
}
|
|
318
|
+
if (choice === 'b' || choice === '') break;
|
|
434
319
|
|
|
435
320
|
const num = parseInt(choice);
|
|
436
321
|
if (!isNaN(num) && num >= 1 && num <= AI_PROVIDERS.length) {
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLIProxy Service
|
|
3
|
+
*
|
|
4
|
+
* Connects to CLIProxyAPI (localhost:8317) for AI provider access
|
|
5
|
+
* via paid plans (Claude Pro, ChatGPT Plus, etc.)
|
|
6
|
+
*
|
|
7
|
+
* Docs: https://help.router-for.me
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const http = require('http');
|
|
11
|
+
|
|
12
|
+
// CLIProxy default endpoint
|
|
13
|
+
const CLIPROXY_BASE = 'http://localhost:8317';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Make HTTP request to CLIProxy
|
|
17
|
+
* @param {string} path - API path
|
|
18
|
+
* @param {string} method - HTTP method
|
|
19
|
+
* @param {Object} headers - Request headers
|
|
20
|
+
* @param {number} timeout - Timeout in ms (default 60000 per RULES.md #15)
|
|
21
|
+
* @returns {Promise<Object>} { success, data, error }
|
|
22
|
+
*/
|
|
23
|
+
const fetchCliProxy = (path, method = 'GET', headers = {}, timeout = 60000) => {
|
|
24
|
+
return new Promise((resolve) => {
|
|
25
|
+
const url = new URL(path, CLIPROXY_BASE);
|
|
26
|
+
const options = {
|
|
27
|
+
hostname: url.hostname,
|
|
28
|
+
port: url.port || 8317,
|
|
29
|
+
path: url.pathname + url.search,
|
|
30
|
+
method,
|
|
31
|
+
headers: {
|
|
32
|
+
'Content-Type': 'application/json',
|
|
33
|
+
...headers
|
|
34
|
+
},
|
|
35
|
+
timeout
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const req = http.request(options, (res) => {
|
|
39
|
+
let data = '';
|
|
40
|
+
res.on('data', chunk => data += chunk);
|
|
41
|
+
res.on('end', () => {
|
|
42
|
+
try {
|
|
43
|
+
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
44
|
+
resolve({ success: true, data: JSON.parse(data) });
|
|
45
|
+
} else {
|
|
46
|
+
resolve({ success: false, error: `HTTP ${res.statusCode}`, data: null });
|
|
47
|
+
}
|
|
48
|
+
} catch (error) {
|
|
49
|
+
resolve({ success: false, error: 'Invalid JSON response', data: null });
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
req.on('error', (error) => {
|
|
55
|
+
if (error.code === 'ECONNREFUSED') {
|
|
56
|
+
resolve({ success: false, error: 'CLIProxy not running', data: null });
|
|
57
|
+
} else {
|
|
58
|
+
resolve({ success: false, error: error.message, data: null });
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
req.on('timeout', () => {
|
|
63
|
+
req.destroy();
|
|
64
|
+
resolve({ success: false, error: 'Request timeout', data: null });
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
req.end();
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Check if CLIProxy is running
|
|
73
|
+
* @returns {Promise<Object>} { running, error }
|
|
74
|
+
*/
|
|
75
|
+
const isCliProxyRunning = async () => {
|
|
76
|
+
const result = await fetchCliProxy('/v1/models', 'GET', {}, 5000);
|
|
77
|
+
return {
|
|
78
|
+
running: result.success,
|
|
79
|
+
error: result.success ? null : result.error
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Fetch available models from CLIProxy
|
|
85
|
+
* @returns {Promise<Object>} { success, models, error }
|
|
86
|
+
*/
|
|
87
|
+
const fetchModelsFromCliProxy = async () => {
|
|
88
|
+
const result = await fetchCliProxy('/v1/models');
|
|
89
|
+
|
|
90
|
+
if (!result.success) {
|
|
91
|
+
return { success: false, models: [], error: result.error };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Parse OpenAI-compatible format: { data: [{ id, ... }] }
|
|
95
|
+
const data = result.data;
|
|
96
|
+
if (!data || !data.data || !Array.isArray(data.data)) {
|
|
97
|
+
return { success: false, models: [], error: 'Invalid response format' };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const models = data.data
|
|
101
|
+
.filter(m => m.id)
|
|
102
|
+
.map(m => ({
|
|
103
|
+
id: m.id,
|
|
104
|
+
name: m.id
|
|
105
|
+
}));
|
|
106
|
+
|
|
107
|
+
if (models.length === 0) {
|
|
108
|
+
return { success: false, models: [], error: 'No models available' };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return { success: true, models, error: null };
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Get OAuth URL for a provider
|
|
116
|
+
* @param {string} providerId - Provider ID (anthropic, openai, google, etc.)
|
|
117
|
+
* @returns {Promise<Object>} { success, url, state, error }
|
|
118
|
+
*/
|
|
119
|
+
const getOAuthUrl = async (providerId) => {
|
|
120
|
+
// Map HQX provider IDs to CLIProxy endpoints
|
|
121
|
+
const oauthEndpoints = {
|
|
122
|
+
anthropic: '/v0/management/anthropic-auth-url',
|
|
123
|
+
openai: '/v0/management/codex-auth-url',
|
|
124
|
+
google: '/v0/management/gemini-cli-auth-url',
|
|
125
|
+
// Others may not have OAuth support in CLIProxy
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const endpoint = oauthEndpoints[providerId];
|
|
129
|
+
if (!endpoint) {
|
|
130
|
+
return { success: false, url: null, state: null, error: 'OAuth not supported for this provider' };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const result = await fetchCliProxy(endpoint);
|
|
134
|
+
|
|
135
|
+
if (!result.success) {
|
|
136
|
+
return { success: false, url: null, state: null, error: result.error };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const data = result.data;
|
|
140
|
+
if (!data || !data.url) {
|
|
141
|
+
return { success: false, url: null, state: null, error: 'Invalid OAuth response' };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return {
|
|
145
|
+
success: true,
|
|
146
|
+
url: data.url,
|
|
147
|
+
state: data.state || null,
|
|
148
|
+
error: null
|
|
149
|
+
};
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Check OAuth status
|
|
154
|
+
* @param {string} state - OAuth state from getOAuthUrl
|
|
155
|
+
* @returns {Promise<Object>} { success, status, error }
|
|
156
|
+
*/
|
|
157
|
+
const checkOAuthStatus = async (state) => {
|
|
158
|
+
const result = await fetchCliProxy(`/v0/management/get-auth-status?state=${encodeURIComponent(state)}`);
|
|
159
|
+
|
|
160
|
+
if (!result.success) {
|
|
161
|
+
return { success: false, status: null, error: result.error };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const data = result.data;
|
|
165
|
+
// status can be: "wait", "ok", "error"
|
|
166
|
+
return {
|
|
167
|
+
success: true,
|
|
168
|
+
status: data.status || 'unknown',
|
|
169
|
+
error: data.error || null
|
|
170
|
+
};
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Get CLIProxy auth files (connected accounts)
|
|
175
|
+
* @returns {Promise<Object>} { success, files, error }
|
|
176
|
+
*/
|
|
177
|
+
const getAuthFiles = async () => {
|
|
178
|
+
const result = await fetchCliProxy('/v0/management/auth-files');
|
|
179
|
+
|
|
180
|
+
if (!result.success) {
|
|
181
|
+
return { success: false, files: [], error: result.error };
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
success: true,
|
|
186
|
+
files: result.data?.files || [],
|
|
187
|
+
error: null
|
|
188
|
+
};
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
module.exports = {
|
|
192
|
+
CLIPROXY_BASE,
|
|
193
|
+
isCliProxyRunning,
|
|
194
|
+
fetchModelsFromCliProxy,
|
|
195
|
+
getOAuthUrl,
|
|
196
|
+
checkOAuthStatus,
|
|
197
|
+
getAuthFiles,
|
|
198
|
+
fetchCliProxy
|
|
199
|
+
};
|