hedgequantx 2.6.161 → 2.6.163

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/package.json +1 -1
  2. package/src/menus/ai-agent-connect.js +181 -0
  3. package/src/menus/ai-agent-models.js +219 -0
  4. package/src/menus/ai-agent-oauth.js +292 -0
  5. package/src/menus/ai-agent-ui.js +141 -0
  6. package/src/menus/ai-agent.js +88 -1489
  7. package/src/pages/algo/copy-engine.js +449 -0
  8. package/src/pages/algo/copy-trading.js +11 -543
  9. package/src/pages/algo/smart-logs-data.js +218 -0
  10. package/src/pages/algo/smart-logs.js +9 -214
  11. package/src/pages/algo/ui-constants.js +144 -0
  12. package/src/pages/algo/ui-summary.js +184 -0
  13. package/src/pages/algo/ui.js +42 -526
  14. package/src/pages/stats-calculations.js +191 -0
  15. package/src/pages/stats-ui.js +381 -0
  16. package/src/pages/stats.js +14 -507
  17. package/src/services/ai/client-analysis.js +194 -0
  18. package/src/services/ai/client-models.js +333 -0
  19. package/src/services/ai/client.js +6 -489
  20. package/src/services/ai/index.js +2 -257
  21. package/src/services/ai/providers/direct-providers.js +323 -0
  22. package/src/services/ai/providers/index.js +8 -472
  23. package/src/services/ai/providers/other-providers.js +104 -0
  24. package/src/services/ai/proxy-install.js +249 -0
  25. package/src/services/ai/proxy-manager.js +29 -411
  26. package/src/services/ai/proxy-remote.js +161 -0
  27. package/src/services/ai/supervisor-optimize.js +215 -0
  28. package/src/services/ai/supervisor-sync.js +178 -0
  29. package/src/services/ai/supervisor.js +50 -515
  30. package/src/services/ai/validation.js +250 -0
  31. package/src/services/hqx-server-events.js +110 -0
  32. package/src/services/hqx-server-handlers.js +217 -0
  33. package/src/services/hqx-server-latency.js +136 -0
  34. package/src/services/hqx-server.js +51 -403
  35. package/src/services/position-constants.js +28 -0
  36. package/src/services/position-exit-logic.js +174 -0
  37. package/src/services/position-manager.js +90 -629
  38. package/src/services/position-momentum.js +206 -0
  39. package/src/services/projectx/accounts.js +142 -0
  40. package/src/services/projectx/index.js +40 -289
  41. package/src/services/projectx/trading.js +180 -0
  42. package/src/services/rithmic/contracts.js +218 -0
  43. package/src/services/rithmic/handlers.js +2 -208
  44. package/src/services/rithmic/index.js +28 -712
  45. package/src/services/rithmic/latency-tracker.js +182 -0
  46. package/src/services/rithmic/market-data-decoders.js +229 -0
  47. package/src/services/rithmic/market-data.js +1 -278
  48. package/src/services/rithmic/orders-fast.js +246 -0
  49. package/src/services/rithmic/orders.js +1 -251
  50. package/src/services/rithmic/proto-decoders.js +403 -0
  51. package/src/services/rithmic/protobuf.js +7 -443
  52. package/src/services/rithmic/specs.js +146 -0
  53. package/src/services/rithmic/trade-history.js +254 -0
  54. package/src/services/strategy/hft-signal-calc.js +147 -0
  55. package/src/services/strategy/hft-tick.js +33 -133
  56. package/src/services/tradovate/index.js +6 -119
  57. package/src/services/tradovate/orders.js +145 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hedgequantx",
3
- "version": "2.6.161",
3
+ "version": "2.6.163",
4
4
  "description": "HedgeQuantX - Prop Futures Trading CLI",
5
5
  "main": "src/app.js",
6
6
  "bin": {
@@ -0,0 +1,181 @@
1
+ /**
2
+ * AI Agent Connection Setup
3
+ * @module menus/ai-agent-connect
4
+ *
5
+ * Credential collection and connection validation flow.
6
+ */
7
+
8
+ const chalk = require('chalk');
9
+ const ora = require('ora');
10
+
11
+ const { drawBoxHeaderContinue, drawBoxFooter, displayBanner } = require('../ui');
12
+ const { prompts } = require('../utils');
13
+ const aiService = require('../services/ai');
14
+ const { makeLine, getBoxDimensions } = require('./ai-agent-ui');
15
+
16
+ /**
17
+ * Get instructions for each credential type
18
+ */
19
+ const getCredentialInstructions = (provider, option, field) => {
20
+ const instructions = {
21
+ apiKey: {
22
+ title: 'API KEY REQUIRED',
23
+ steps: ['1. CLICK THE LINK BELOW TO OPEN IN BROWSER', '2. SIGN IN OR CREATE AN ACCOUNT', '3. GENERATE A NEW API KEY', '4. COPY AND PASTE IT HERE']
24
+ },
25
+ sessionKey: {
26
+ title: 'SESSION KEY REQUIRED (SUBSCRIPTION PLAN)',
27
+ steps: ['1. OPEN THE LINK BELOW IN YOUR BROWSER', '2. SIGN IN WITH YOUR SUBSCRIPTION ACCOUNT', '3. OPEN DEVELOPER TOOLS (F12 OR CMD+OPT+I)', '4. GO TO APPLICATION > COOKIES', '5. FIND "sessionKey" OR SIMILAR TOKEN', '6. COPY THE VALUE AND PASTE IT HERE']
28
+ },
29
+ accessToken: {
30
+ title: 'ACCESS TOKEN REQUIRED (SUBSCRIPTION PLAN)',
31
+ steps: ['1. OPEN THE LINK BELOW IN YOUR BROWSER', '2. SIGN IN WITH YOUR SUBSCRIPTION ACCOUNT', '3. OPEN DEVELOPER TOOLS (F12 OR CMD+OPT+I)', '4. GO TO APPLICATION > COOKIES OR LOCAL STORAGE', '5. FIND "accessToken" OR "token"', '6. COPY THE VALUE AND PASTE IT HERE']
32
+ },
33
+ endpoint: {
34
+ title: 'ENDPOINT URL',
35
+ steps: ['1. ENTER THE API ENDPOINT URL', '2. USUALLY http://localhost:PORT FOR LOCAL']
36
+ },
37
+ model: {
38
+ title: 'MODEL NAME',
39
+ steps: ['1. ENTER THE MODEL NAME TO USE', '2. CHECK PROVIDER DOCS FOR AVAILABLE MODELS']
40
+ }
41
+ };
42
+
43
+ return instructions[field] || { title: field.toUpperCase(), steps: [] };
44
+ };
45
+
46
+ /**
47
+ * Collect credentials from user
48
+ */
49
+ const collectCredentials = async (provider, option, onBack) => {
50
+ const { boxWidth, W } = getBoxDimensions();
51
+ const credentials = {};
52
+
53
+ for (const field of option.fields) {
54
+ console.clear();
55
+ displayBanner();
56
+ drawBoxHeaderContinue(`CONNECT TO ${provider.name}`, boxWidth);
57
+
58
+ const instructions = getCredentialInstructions(provider, option, field);
59
+
60
+ console.log(makeLine(W, chalk.yellow(instructions.title)));
61
+ console.log(makeLine(W, ''));
62
+
63
+ for (const step of instructions.steps) {
64
+ console.log(makeLine(W, chalk.white(step)));
65
+ }
66
+
67
+ console.log(makeLine(W, ''));
68
+
69
+ if (option.url && (field === 'apiKey' || field === 'sessionKey' || field === 'accessToken')) {
70
+ console.log(makeLine(W, chalk.cyan('GET KEY: ') + chalk.white(option.url)));
71
+ }
72
+
73
+ if (field === 'endpoint' && option.defaultEndpoint) {
74
+ console.log(makeLine(W, chalk.white(`DEFAULT: ${option.defaultEndpoint}`)));
75
+ }
76
+
77
+ console.log(makeLine(W, ''));
78
+ console.log(makeLine(W, chalk.white('TYPE < TO GO BACK')));
79
+
80
+ drawBoxFooter(boxWidth);
81
+ console.log();
82
+
83
+ let value;
84
+
85
+ switch (field) {
86
+ case 'apiKey':
87
+ value = await prompts.textInput(chalk.cyan('PASTE API KEY:'));
88
+ if (!value || value.trim() === '<' || value.trim() === '') return null;
89
+ credentials.apiKey = value.trim();
90
+ break;
91
+ case 'sessionKey':
92
+ value = await prompts.textInput(chalk.cyan('PASTE SESSION KEY:'));
93
+ if (!value || value.trim() === '<' || value.trim() === '') return null;
94
+ credentials.sessionKey = value.trim();
95
+ break;
96
+ case 'accessToken':
97
+ value = await prompts.textInput(chalk.cyan('PASTE ACCESS TOKEN:'));
98
+ if (!value || value.trim() === '<' || value.trim() === '') return null;
99
+ credentials.accessToken = value.trim();
100
+ break;
101
+ case 'endpoint':
102
+ const defaultEndpoint = option.defaultEndpoint || '';
103
+ value = await prompts.textInput(chalk.cyan(`ENDPOINT [${defaultEndpoint || 'required'}]:`));
104
+ if (!value || value.trim() === '<' || value.trim() === '') {
105
+ if (!defaultEndpoint) return null;
106
+ }
107
+ credentials.endpoint = (value && value.trim() !== '<' ? value : defaultEndpoint).trim();
108
+ if (!credentials.endpoint) return null;
109
+ break;
110
+ case 'model':
111
+ value = await prompts.textInput(chalk.cyan('MODEL NAME:'));
112
+ if (!value || value.trim() === '<' || value.trim() === '') return null;
113
+ credentials.model = value.trim();
114
+ break;
115
+ }
116
+ }
117
+
118
+ return credentials;
119
+ };
120
+
121
+ /**
122
+ * Validate connection and fetch models
123
+ */
124
+ const validateAndFetchModels = async (provider, option, credentials) => {
125
+ console.log();
126
+ const spinner = ora({ text: 'VALIDATING CONNECTION...', color: 'cyan' }).start();
127
+
128
+ const validation = await aiService.validateConnection(provider.id, option.id, credentials);
129
+
130
+ if (!validation.valid) {
131
+ spinner.fail(`CONNECTION FAILED: ${validation.error}`);
132
+ return { valid: false, error: validation.error };
133
+ }
134
+
135
+ spinner.text = 'FETCHING AVAILABLE MODELS...';
136
+
137
+ // Fetch models from real API
138
+ const { fetchAnthropicModels, fetchGeminiModels, fetchOpenAIModels } = require('../services/ai/client');
139
+
140
+ let models = null;
141
+ if (provider.id === 'anthropic') {
142
+ models = await fetchAnthropicModels(credentials.apiKey);
143
+ } else if (provider.id === 'gemini') {
144
+ models = await fetchGeminiModels(credentials.apiKey);
145
+ } else {
146
+ const endpoint = credentials.endpoint || provider.endpoint;
147
+ models = await fetchOpenAIModels(endpoint, credentials.apiKey);
148
+ }
149
+
150
+ if (!models || models.length === 0) {
151
+ spinner.fail('COULD NOT FETCH MODELS FROM API');
152
+ console.log(chalk.white(' Check your API key or network connection.'));
153
+ return { valid: false, error: 'No models found' };
154
+ }
155
+
156
+ spinner.succeed(`FOUND ${models.length} MODELS`);
157
+ return { valid: true, models };
158
+ };
159
+
160
+ /**
161
+ * Add agent after successful connection
162
+ */
163
+ const addConnectedAgent = async (provider, option, credentials, selectedModel) => {
164
+ try {
165
+ await aiService.addAgent(provider.id, option.id, credentials, selectedModel, provider.name);
166
+
167
+ console.log(chalk.green(`\n AGENT ADDED: ${provider.name}`));
168
+ console.log(chalk.white(` MODEL: ${selectedModel}`));
169
+ return true;
170
+ } catch (error) {
171
+ console.log(chalk.red(`\n FAILED TO SAVE: ${error.message}`));
172
+ return false;
173
+ }
174
+ };
175
+
176
+ module.exports = {
177
+ getCredentialInstructions,
178
+ collectCredentials,
179
+ validateAndFetchModels,
180
+ addConnectedAgent,
181
+ };
@@ -0,0 +1,219 @@
1
+ /**
2
+ * AI Agent Model Selection
3
+ * Model selection and management for AI agents
4
+ */
5
+
6
+ const chalk = require('chalk');
7
+
8
+ const { displayBanner, drawBoxHeaderContinue, drawBoxFooter } = require('../ui');
9
+ const { prompts } = require('../utils');
10
+ const aiService = require('../services/ai');
11
+ const { makeLine, getBoxDimensions } = require('./ai-agent-ui');
12
+
13
+ /**
14
+ * Select model from a list (used when adding new agent)
15
+ * @param {Array} models - Array of model IDs from API
16
+ * @param {string} providerName - Provider name for display
17
+ * @returns {string|null} Selected model ID or null if cancelled
18
+ *
19
+ * Data source: models array comes from provider API (/v1/models)
20
+ */
21
+ const selectModelFromList = async (models, providerName) => {
22
+ const { boxWidth, W } = getBoxDimensions();
23
+
24
+ console.clear();
25
+ displayBanner();
26
+ drawBoxHeaderContinue(`SELECT MODEL - ${providerName}`, boxWidth);
27
+
28
+ if (!models || models.length === 0) {
29
+ console.log(makeLine(W, chalk.red('NO MODELS AVAILABLE')));
30
+ console.log(makeLine(W, chalk.white('[<] BACK')));
31
+ drawBoxFooter(boxWidth);
32
+ await prompts.waitForEnter();
33
+ return null;
34
+ }
35
+
36
+ // Sort models (newest first)
37
+ const sortedModels = [...models].sort((a, b) => b.localeCompare(a));
38
+
39
+ // Display models in 2 columns
40
+ const rows = Math.ceil(sortedModels.length / 2);
41
+ const colWidth = Math.floor((W - 4) / 2);
42
+
43
+ for (let i = 0; i < rows; i++) {
44
+ const leftIndex = i;
45
+ const rightIndex = i + rows;
46
+
47
+ // Left column
48
+ const leftModel = sortedModels[leftIndex];
49
+ const leftNum = chalk.cyan(`[${leftIndex + 1}]`);
50
+ const leftName = leftModel.length > colWidth - 6
51
+ ? leftModel.substring(0, colWidth - 9) + '...'
52
+ : leftModel;
53
+ const leftText = `${leftNum} ${chalk.yellow(leftName)}`;
54
+ const leftPlain = `[${leftIndex + 1}] ${leftName}`;
55
+
56
+ // Right column (if exists)
57
+ let rightText = '';
58
+ let rightPlain = '';
59
+ if (rightIndex < sortedModels.length) {
60
+ const rightModel = sortedModels[rightIndex];
61
+ const rightNum = chalk.cyan(`[${rightIndex + 1}]`);
62
+ const rightName = rightModel.length > colWidth - 6
63
+ ? rightModel.substring(0, colWidth - 9) + '...'
64
+ : rightModel;
65
+ rightText = `${rightNum} ${chalk.yellow(rightName)}`;
66
+ rightPlain = `[${rightIndex + 1}] ${rightName}`;
67
+ }
68
+
69
+ // Pad left column and combine
70
+ const leftPadding = colWidth - leftPlain.length;
71
+ const line = leftText + ' '.repeat(Math.max(2, leftPadding)) + rightText;
72
+ console.log(makeLine(W, line));
73
+ }
74
+
75
+ console.log(makeLine(W, ''));
76
+ console.log(makeLine(W, chalk.white('[<] BACK')));
77
+
78
+ drawBoxFooter(boxWidth);
79
+
80
+ const choice = await prompts.textInput(chalk.cyan('SELECT MODEL:'));
81
+
82
+ // Empty input or < = go back
83
+ if (!choice || choice.trim() === '' || choice === '<' || choice?.toLowerCase() === 'b') {
84
+ return null;
85
+ }
86
+
87
+ const index = parseInt(choice) - 1;
88
+ if (isNaN(index) || index < 0 || index >= sortedModels.length) {
89
+ return await selectModelFromList(models, providerName);
90
+ }
91
+
92
+ return sortedModels[index];
93
+ };
94
+
95
+ /**
96
+ * Select/change model for an existing agent
97
+ * Fetches available models from the provider's API
98
+ * @param {Object} agent - Agent object
99
+ * @param {Function} aiAgentMenuFn - Callback to return to main menu
100
+ */
101
+ const selectModel = async (agent, aiAgentMenuFn) => {
102
+ const { boxWidth, W } = getBoxDimensions();
103
+
104
+ console.clear();
105
+ displayBanner();
106
+ drawBoxHeaderContinue(`SELECT MODEL - ${agent.name}`, boxWidth);
107
+
108
+ console.log(makeLine(W, chalk.white('FETCHING AVAILABLE MODELS FROM API...')));
109
+ drawBoxFooter(boxWidth);
110
+
111
+ // Fetch models from real API
112
+ const { fetchAnthropicModels, fetchAnthropicModelsOAuth, fetchGeminiModels, fetchOpenAIModels } = require('../services/ai/client');
113
+
114
+ let models = null;
115
+ const agentCredentials = aiService.getAgentCredentials(agent.id);
116
+
117
+ if (agent.providerId === 'anthropic') {
118
+ const token = agentCredentials?.apiKey || agentCredentials?.accessToken || agentCredentials?.sessionKey;
119
+ const isOAuthToken = agentCredentials?.oauth?.access || (token && token.startsWith('sk-ant-oat'));
120
+
121
+ if (isOAuthToken) {
122
+ const accessToken = agentCredentials?.oauth?.access || token;
123
+ models = await fetchAnthropicModelsOAuth(accessToken);
124
+ } else {
125
+ models = await fetchAnthropicModels(token);
126
+ }
127
+ } else if (agent.providerId === 'gemini') {
128
+ models = await fetchGeminiModels(agentCredentials?.apiKey);
129
+ } else {
130
+ const endpoint = agentCredentials?.endpoint || agent.provider?.endpoint;
131
+ models = await fetchOpenAIModels(endpoint, agentCredentials?.apiKey);
132
+ }
133
+
134
+ // Redraw with results
135
+ console.clear();
136
+ displayBanner();
137
+ drawBoxHeaderContinue(`SELECT MODEL - ${agent.name}`, boxWidth);
138
+
139
+ if (!models || models.length === 0) {
140
+ console.log(makeLine(W, chalk.red('COULD NOT FETCH MODELS FROM API')));
141
+ console.log(makeLine(W, chalk.white('Check your API key or network connection.')));
142
+ console.log(makeLine(W, ''));
143
+ console.log(makeLine(W, chalk.white('[<] BACK')));
144
+ drawBoxFooter(boxWidth);
145
+
146
+ await prompts.waitForEnter();
147
+ return await aiAgentMenuFn();
148
+ }
149
+
150
+ // Sort models (newest first typically)
151
+ models.sort((a, b) => b.localeCompare(a));
152
+
153
+ // Display models in 2 columns
154
+ const rows = Math.ceil(models.length / 2);
155
+ const colWidth = Math.floor((W - 4) / 2);
156
+
157
+ for (let i = 0; i < rows; i++) {
158
+ const leftIndex = i;
159
+ const rightIndex = i + rows;
160
+
161
+ // Left column
162
+ const leftModel = models[leftIndex];
163
+ const leftNum = chalk.cyan(`[${leftIndex + 1}]`);
164
+ const leftCurrent = leftModel === agent.model ? chalk.green(' *') : '';
165
+ const leftName = leftModel.length > colWidth - 8
166
+ ? leftModel.substring(0, colWidth - 11) + '...'
167
+ : leftModel;
168
+ const leftText = `${leftNum} ${chalk.yellow(leftName)}${leftCurrent}`;
169
+ const leftPlain = `[${leftIndex + 1}] ${leftName}${leftModel === agent.model ? ' *' : ''}`;
170
+
171
+ // Right column (if exists)
172
+ let rightText = '';
173
+ let rightPlain = '';
174
+ if (rightIndex < models.length) {
175
+ const rightModel = models[rightIndex];
176
+ const rightNum = chalk.cyan(`[${rightIndex + 1}]`);
177
+ const rightCurrent = rightModel === agent.model ? chalk.green(' *') : '';
178
+ const rightName = rightModel.length > colWidth - 8
179
+ ? rightModel.substring(0, colWidth - 11) + '...'
180
+ : rightModel;
181
+ rightText = `${rightNum} ${chalk.yellow(rightName)}${rightCurrent}`;
182
+ rightPlain = `[${rightIndex + 1}] ${rightName}${rightModel === agent.model ? ' *' : ''}`;
183
+ }
184
+
185
+ // Pad left column and combine
186
+ const leftPadding = colWidth - leftPlain.length;
187
+ const line = leftText + ' '.repeat(Math.max(2, leftPadding)) + rightText;
188
+ console.log(makeLine(W, line));
189
+ }
190
+
191
+ console.log(makeLine(W, ''));
192
+ console.log(makeLine(W, chalk.white('[<] BACK') + chalk.white(' * = CURRENT')));
193
+
194
+ drawBoxFooter(boxWidth);
195
+
196
+ const choice = await prompts.textInput(chalk.cyan('SELECT MODEL:'));
197
+
198
+ // Empty input or < = go back
199
+ if (!choice || choice.trim() === '' || choice === '<' || choice?.toLowerCase() === 'b') {
200
+ return await aiAgentMenuFn();
201
+ }
202
+
203
+ const index = parseInt(choice) - 1;
204
+ if (isNaN(index) || index < 0 || index >= models.length) {
205
+ return await selectModel(agent, aiAgentMenuFn);
206
+ }
207
+
208
+ const selectedModel = models[index];
209
+ aiService.updateAgent(agent.id, { model: selectedModel });
210
+
211
+ console.log(chalk.green(`\n MODEL CHANGED TO: ${selectedModel}`));
212
+ await prompts.waitForEnter();
213
+ return await aiAgentMenuFn();
214
+ };
215
+
216
+ module.exports = {
217
+ selectModelFromList,
218
+ selectModel
219
+ };
@@ -0,0 +1,292 @@
1
+ /**
2
+ * AI Agent OAuth Flows
3
+ * OAuth authentication handling for AI providers via CLIProxyAPI
4
+ */
5
+
6
+ const chalk = require('chalk');
7
+ const ora = require('ora');
8
+
9
+ const { displayBanner, drawBoxHeaderContinue, drawBoxFooter } = require('../ui');
10
+ const { prompts } = require('../utils');
11
+ const aiService = require('../services/ai');
12
+ const proxyManager = require('../services/ai/proxy-manager');
13
+ const { makeLine, getBoxDimensions, openBrowser, isRemoteEnvironment } = require('./ai-agent-ui');
14
+
15
+ /**
16
+ * Get OAuth config for provider
17
+ * @param {string} providerId - Provider identifier
18
+ * @returns {Object|undefined} OAuth configuration
19
+ */
20
+ const getOAuthConfig = (providerId) => {
21
+ const configs = {
22
+ anthropic: {
23
+ name: 'CLAUDE PRO/MAX',
24
+ accountName: 'Claude',
25
+ optionId: 'oauth_max',
26
+ agentName: 'Claude Pro/Max'
27
+ },
28
+ openai: {
29
+ name: 'CHATGPT PLUS/PRO',
30
+ accountName: 'ChatGPT',
31
+ optionId: 'oauth_plus',
32
+ agentName: 'ChatGPT Plus/Pro'
33
+ },
34
+ gemini: {
35
+ name: 'GEMINI ADVANCED',
36
+ accountName: 'Google',
37
+ optionId: 'oauth_advanced',
38
+ agentName: 'Gemini Advanced'
39
+ },
40
+ qwen: {
41
+ name: 'QWEN CHAT',
42
+ accountName: 'Qwen',
43
+ optionId: 'oauth_chat',
44
+ agentName: 'Qwen Chat'
45
+ },
46
+ iflow: {
47
+ name: 'IFLOW',
48
+ accountName: 'iFlow',
49
+ optionId: 'oauth_sub',
50
+ agentName: 'iFlow'
51
+ }
52
+ };
53
+ return configs[providerId];
54
+ };
55
+
56
+ /**
57
+ * Setup OAuth connection for any provider with OAuth support
58
+ * Uses CLIProxyAPI for proper OAuth handling and API access
59
+ * @param {Object} provider - Provider object
60
+ * @param {Function} selectProviderOptionFn - Callback to return to provider selection
61
+ * @param {Function} selectModelFromListFn - Callback to select model
62
+ * @param {Function} aiAgentMenuFn - Callback to return to main menu
63
+ */
64
+ const setupOAuthConnection = async (provider, selectProviderOptionFn, selectModelFromListFn, aiAgentMenuFn) => {
65
+ const config = getOAuthConfig(provider.id);
66
+ if (!config) {
67
+ console.log(chalk.red('OAuth not supported for this provider'));
68
+ await prompts.waitForEnter();
69
+ return await selectProviderOptionFn(provider);
70
+ }
71
+
72
+ const { boxWidth, W } = getBoxDimensions();
73
+
74
+ // Step 1: Ensure CLIProxyAPI is installed and running
75
+ const spinner = ora({ text: 'Setting up CLIProxyAPI...', color: 'cyan' }).start();
76
+
77
+ try {
78
+ await proxyManager.ensureRunning();
79
+ spinner.succeed('CLIProxyAPI ready');
80
+ } catch (error) {
81
+ spinner.fail(`Failed to start CLIProxyAPI: ${error.message}`);
82
+ console.log();
83
+ console.log(chalk.yellow(' CLIProxyAPI is required for OAuth authentication.'));
84
+ console.log(chalk.gray(' It will be downloaded automatically on first use.'));
85
+ console.log();
86
+ await prompts.waitForEnter();
87
+ return await selectProviderOptionFn(provider);
88
+ }
89
+
90
+ // Step 2: Get OAuth URL from CLIProxyAPI
91
+ spinner.text = 'Getting authorization URL...';
92
+ spinner.start();
93
+
94
+ let authUrl, authState;
95
+ try {
96
+ const authInfo = await proxyManager.getAuthUrl(provider.id);
97
+ authUrl = authInfo.url;
98
+ authState = authInfo.state;
99
+ spinner.succeed('Authorization URL ready');
100
+ } catch (error) {
101
+ spinner.fail(`Failed to get auth URL: ${error.message}`);
102
+ await prompts.waitForEnter();
103
+ return await selectProviderOptionFn(provider);
104
+ }
105
+
106
+ // Step 3: Show instructions to user
107
+ console.clear();
108
+ displayBanner();
109
+ drawBoxHeaderContinue(`CONNECT ${config.name}`, boxWidth);
110
+
111
+ console.log(makeLine(W, chalk.yellow('CONNECT YOUR ACCOUNT')));
112
+ console.log(makeLine(W, ''));
113
+ console.log(makeLine(W, chalk.white('1. OPEN THE LINK BELOW IN YOUR BROWSER')));
114
+ console.log(makeLine(W, ''));
115
+ console.log(makeLine(W, chalk.white(`2. LOGIN WITH YOUR ${config.accountName.toUpperCase()} ACCOUNT`)));
116
+ console.log(makeLine(W, ''));
117
+ console.log(makeLine(W, chalk.white('3. CLICK "AUTHORIZE"')));
118
+ console.log(makeLine(W, ''));
119
+ console.log(makeLine(W, chalk.green('4. WAIT FOR CONFIRMATION HERE')));
120
+ console.log(makeLine(W, chalk.white(' (The page will close automatically)')));
121
+ console.log(makeLine(W, ''));
122
+
123
+ drawBoxFooter(boxWidth);
124
+
125
+ // Display URL
126
+ console.log();
127
+ console.log(chalk.yellow(' OPEN THIS URL IN YOUR BROWSER:'));
128
+ console.log();
129
+ console.log(chalk.cyan(` ${authUrl}`));
130
+ console.log();
131
+
132
+ // Try to open browser automatically
133
+ const browserOpened = await openBrowser(authUrl);
134
+ if (browserOpened) {
135
+ console.log(chalk.gray(' (Browser opened automatically)'));
136
+ } else {
137
+ console.log(chalk.gray(' (Copy and paste the URL in your browser)'));
138
+ }
139
+ console.log();
140
+
141
+ // Step 4: Wait for OAuth callback
142
+ const isRemote = isRemoteEnvironment();
143
+ let authSuccess = false;
144
+
145
+ if (isRemote) {
146
+ // Remote/VPS: Ask for callback URL directly
147
+ authSuccess = await handleRemoteOAuth(provider, selectProviderOptionFn);
148
+ } else {
149
+ // Local: Wait for automatic callback
150
+ authSuccess = await handleLocalOAuth(authState, selectProviderOptionFn, provider);
151
+ }
152
+
153
+ if (!authSuccess) {
154
+ return await selectProviderOptionFn(provider);
155
+ }
156
+
157
+ // Step 5: Fetch and select model, save agent
158
+ return await completeOAuthSetup(provider, config, selectProviderOptionFn, selectModelFromListFn, aiAgentMenuFn);
159
+ };
160
+
161
+ /**
162
+ * Handle OAuth callback for remote/VPS environment
163
+ */
164
+ const handleRemoteOAuth = async (provider, selectProviderOptionFn) => {
165
+ console.log(chalk.yellow(' After authorizing, paste the callback URL from your browser:'));
166
+ console.log(chalk.gray(' (The page showing http://localhost:54545/callback?code=...)'));
167
+ console.log();
168
+
169
+ const inquirer = require('inquirer');
170
+ let callbackUrl = '';
171
+ try {
172
+ const result = await inquirer.prompt([{
173
+ type: 'input',
174
+ name: 'callbackUrl',
175
+ message: 'Callback URL:',
176
+ prefix: ' '
177
+ }]);
178
+ callbackUrl = result.callbackUrl || '';
179
+ } catch (e) {
180
+ const readline = require('readline');
181
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
182
+ callbackUrl = await new Promise(resolve => {
183
+ rl.question(' Callback URL: ', answer => {
184
+ rl.close();
185
+ resolve(answer || '');
186
+ });
187
+ });
188
+ }
189
+
190
+ if (!callbackUrl || !callbackUrl.trim()) {
191
+ console.log(chalk.gray(' Cancelled.'));
192
+ await prompts.waitForEnter();
193
+ return false;
194
+ }
195
+
196
+ const submitSpinner = ora({ text: 'Submitting callback...', color: 'cyan' }).start();
197
+ try {
198
+ await proxyManager.submitCallback(callbackUrl.trim(), provider.id);
199
+ await new Promise(resolve => setTimeout(resolve, 500));
200
+ submitSpinner.succeed('Authorization successful!');
201
+ return true;
202
+ } catch (submitError) {
203
+ submitSpinner.fail(`Failed: ${submitError.message}`);
204
+ await prompts.waitForEnter();
205
+ return false;
206
+ }
207
+ };
208
+
209
+ /**
210
+ * Handle OAuth callback for local environment
211
+ */
212
+ const handleLocalOAuth = async (authState, selectProviderOptionFn, provider) => {
213
+ const waitSpinner = ora({ text: 'Waiting for authorization...', color: 'cyan' }).start();
214
+
215
+ try {
216
+ await proxyManager.waitForAuth(authState, 300000, (status) => {
217
+ waitSpinner.text = status;
218
+ });
219
+ waitSpinner.succeed('Authorization successful!');
220
+ return true;
221
+ } catch (error) {
222
+ waitSpinner.fail(`Authorization failed: ${error.message}`);
223
+ await prompts.waitForEnter();
224
+ return false;
225
+ }
226
+ };
227
+
228
+ /**
229
+ * Complete OAuth setup: fetch models and save agent
230
+ */
231
+ const completeOAuthSetup = async (provider, config, selectProviderOptionFn, selectModelFromListFn, aiAgentMenuFn) => {
232
+ try {
233
+ // Fetch models from CLIProxyAPI
234
+ const modelSpinner = ora({ text: 'Fetching available models from API...', color: 'cyan' }).start();
235
+
236
+ let models = [];
237
+ try {
238
+ models = await proxyManager.getModels(provider.id);
239
+ modelSpinner.succeed(`Found ${models.length} models for ${provider.name}`);
240
+ } catch (error) {
241
+ modelSpinner.fail(`Failed to fetch models: ${error.message}`);
242
+ await prompts.waitForEnter();
243
+ return await selectProviderOptionFn(provider);
244
+ }
245
+
246
+ if (!models || models.length === 0) {
247
+ console.log();
248
+ console.log(chalk.red(' ERROR: No models found for this provider'));
249
+ console.log(chalk.gray(' Make sure your subscription is active and authorization completed.'));
250
+ console.log();
251
+ await prompts.waitForEnter();
252
+ return await selectProviderOptionFn(provider);
253
+ }
254
+
255
+ // Let user select model
256
+ const selectedModel = await selectModelFromListFn(models, config.name);
257
+ if (!selectedModel) {
258
+ return await selectProviderOptionFn(provider);
259
+ }
260
+
261
+ // Save agent config
262
+ const credentials = {
263
+ useProxy: true,
264
+ provider: provider.id
265
+ };
266
+
267
+ try {
268
+ await aiService.addAgent(provider.id, config.optionId, credentials, selectedModel, config.agentName);
269
+
270
+ console.log(chalk.green(`\n CONNECTED TO ${config.name}`));
271
+ console.log(chalk.white(` MODEL: ${selectedModel}`));
272
+ console.log(chalk.white(' UNLIMITED USAGE WITH YOUR SUBSCRIPTION'));
273
+ } catch (error) {
274
+ console.log(chalk.red(`\n FAILED TO SAVE: ${error.message}`));
275
+ }
276
+
277
+ await prompts.waitForEnter();
278
+ return await aiAgentMenuFn();
279
+ } catch (unexpectedError) {
280
+ console.log();
281
+ console.log(chalk.red(` UNEXPECTED ERROR: ${unexpectedError.message}`));
282
+ console.log(chalk.gray(` Stack: ${unexpectedError.stack}`));
283
+ console.log();
284
+ await prompts.waitForEnter();
285
+ return await selectProviderOptionFn(provider);
286
+ }
287
+ };
288
+
289
+ module.exports = {
290
+ getOAuthConfig,
291
+ setupOAuthConnection
292
+ };