-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathconfigure.cpp
More file actions
643 lines (581 loc) · 23.8 KB
/
Copy pathconfigure.cpp
File metadata and controls
643 lines (581 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
#include "configure.hpp"
#include "configure_catalog.hpp"
#include "configure_picker.hpp"
#include "provider/codex/codex_app_server_client.hpp"
#include "provider/codex/codex_model_catalog.hpp"
#include "config/config.hpp"
#include "provider/auth/github_auth.hpp"
#include "network/proxy_resolver.hpp"
#include "provider/anthropic_provider.hpp"
#include "provider/builtin_model_catalog.hpp"
#include "utils/logger.hpp"
#include "utils/models_dev_catalog.hpp"
#include "utils/terminal_input.hpp"
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <optional>
#include <utility>
#include <cpr/cpr.h>
#include <cpr/ssl_options.h>
#include <nlohmann/json.hpp>
namespace acecode {
// Mask an API key for display: "****" + last 4 chars
static std::string mask_key(const std::string& key) {
if (key.empty()) return "(not set)";
if (key.size() > 4) {
return "****" + key.substr(key.size() - 4);
}
return "****";
}
static std::string configured_saved_model_name(const AppConfig& cfg) {
if (cfg.provider == "codex") return "codex";
if (cfg.provider == "copilot") return "copilot";
if (cfg.openai.models_dev_provider_id.has_value() &&
!cfg.openai.models_dev_provider_id->empty()) {
return *cfg.openai.models_dev_provider_id;
}
return "openai";
}
static ModelProfile configured_profile_from_current_fields(const AppConfig& cfg) {
ModelProfile profile;
profile.name = configured_saved_model_name(cfg);
if (cfg.provider == "openai") {
profile.provider = "openai";
profile.base_url = cfg.openai.base_url;
profile.api_key = cfg.openai.api_key;
profile.model = cfg.openai.model;
profile.stream_timeout_ms = cfg.openai.stream_timeout_ms;
profile.request_headers = cfg.openai.request_headers;
profile.models_dev_provider_id = cfg.openai.models_dev_provider_id;
if (profile.models_dev_provider_id.has_value() &&
is_acemodel_provider_id(*profile.models_dev_provider_id)) {
if (const ModelEntry* model =
find_acemodel_catalog_model(profile.model)) {
profile.capabilities = model_capability_tags(*model);
profile.capabilities_source = "catalog";
}
}
} else if (cfg.provider == "codex") {
profile.provider = "codex";
profile.model = cfg.codex.model;
} else {
profile.provider = "copilot";
profile.model = cfg.copilot.model;
}
return profile;
}
static void upsert_configured_saved_model(AppConfig& cfg) {
ModelProfile profile = configured_profile_from_current_fields(cfg);
for (auto& existing : cfg.saved_models) {
if (existing.name == profile.name) {
if ((profile.provider == "openai" || profile.provider == "anthropic") &&
profile.request_headers.empty() &&
!existing.request_headers.empty()) {
profile.request_headers = existing.request_headers;
}
existing = profile;
cfg.default_model_name = profile.name;
return;
}
}
cfg.saved_models.push_back(profile);
cfg.default_model_name = profile.name;
}
static void upsert_saved_model_profile(AppConfig& cfg, ModelProfile profile) {
for (auto& existing : cfg.saved_models) {
if (existing.name == profile.name) {
if ((profile.provider == "openai" || profile.provider == "anthropic") &&
profile.request_headers.empty() &&
!existing.request_headers.empty()) {
profile.request_headers = existing.request_headers;
}
existing = profile;
cfg.default_model_name = profile.name;
return;
}
}
cfg.saved_models.push_back(profile);
cfg.default_model_name = profile.name;
}
static ModelProfile default_anthropic_profile(const AppConfig& cfg) {
ModelProfile fallback;
fallback.name = "anthropic";
fallback.provider = "anthropic";
fallback.base_url = AnthropicProvider::kDefaultBaseUrl;
fallback.model = "";
fallback.models_dev_provider_id = "anthropic";
const ModelProfile* candidate = nullptr;
for (const auto& entry : cfg.saved_models) {
if (entry.provider == "anthropic" && entry.name == cfg.default_model_name) {
candidate = &entry;
break;
}
}
if (!candidate) {
for (const auto& entry : cfg.saved_models) {
if (entry.provider == "anthropic") {
candidate = &entry;
break;
}
}
}
if (!candidate) return fallback;
ModelProfile profile = *candidate;
if (profile.base_url.empty()) profile.base_url = AnthropicProvider::kDefaultBaseUrl;
if (!profile.models_dev_provider_id.has_value()) {
profile.models_dev_provider_id = "anthropic";
}
return profile;
}
static void configure_copilot(AppConfig& cfg) {
std::cout << "\n--- Copilot Configuration ---\n" << std::endl;
// Authentication first (needed to fetch available models)
std::string github_token = load_github_token();
if (github_token.empty()) {
std::cout << "GitHub authentication required." << std::endl;
} else {
std::cout << "GitHub authentication: Already authenticated." << std::endl;
if (read_confirm("Re-authenticate?", false)) {
github_token.clear(); // force re-auth below
}
}
if (github_token.empty()) {
std::cout << "\nStarting GitHub authentication..." << std::endl;
DeviceCodeResponse dc = request_device_code();
if (dc.device_code.empty()) {
std::cerr << "Error: Failed to request device code from GitHub." << std::endl;
return;
}
std::cout << "\n Please open: " << dc.verification_uri << std::endl;
std::cout << " Enter code: " << dc.user_code << std::endl;
std::cout << std::endl;
github_token = poll_for_access_token(
dc.device_code, dc.interval, dc.expires_in,
[](const std::string& status) {
std::cout << " " << status << std::endl;
}
);
if (github_token.empty()) {
std::cerr << "Authentication failed or timed out." << std::endl;
return;
}
save_github_token(github_token);
std::cout << "Authentication successful!" << std::endl;
}
// Fetch available models from Copilot API
std::cout << "\nFetching available models..." << std::endl;
std::vector<std::string> model_ids;
CopilotModelsResult models_result = fetch_copilot_model_ids(github_token);
if (models_result.error.empty()) {
model_ids = std::move(models_result.models);
} else if (!models_result.message.empty()) {
std::cerr << "Warning: Could not fetch Copilot model list: "
<< models_result.message << std::endl;
}
// Catalog augmentation: enrich each id with metadata from models.dev
// (`github-copilot` provider) when available, and fall back to the catalog
// list entirely when GitHub `/models` returned nothing.
const ProviderEntry* copilot_catalog = find_provider("github-copilot");
auto label_for = [&](const std::string& id) -> std::string {
if (!copilot_catalog) return id;
const ModelEntry* m = find_model(*copilot_catalog, id);
if (!m) return id + " (no metadata)";
std::ostringstream oss;
oss << id;
auto ctx = format_context(m->context);
if (!ctx.empty()) oss << " ctx=" << ctx;
auto caps = format_capabilities(*m);
if (!caps.empty()) oss << " " << caps;
return oss.str();
};
std::vector<std::string> labels;
std::vector<std::string> choice_ids;
if (!model_ids.empty()) {
for (const auto& id : model_ids) {
labels.push_back(label_for(id));
choice_ids.push_back(id);
}
} else if (copilot_catalog && !copilot_catalog->models.empty()) {
std::cerr << "Warning: GitHub /models unavailable, falling back to catalog list." << std::endl;
for (const auto& m : copilot_catalog->models) {
labels.push_back(label_for(m.id));
choice_ids.push_back(m.id);
}
}
if (!choice_ids.empty()) {
int default_idx = 0;
for (size_t i = 0; i < choice_ids.size(); ++i) {
if (choice_ids[i] == cfg.copilot.model) {
default_idx = static_cast<int>(i);
break;
}
}
std::vector<PickerItem> items;
items.reserve(choice_ids.size());
for (size_t i = 0; i < choice_ids.size(); ++i) {
PickerItem it;
it.label = choice_ids[i];
// labels[i] already starts with the id; strip it so the helper
// renders id as the bold label and only the metadata as secondary.
if (labels[i].rfind(choice_ids[i], 0) == 0) {
std::string rest = labels[i].substr(choice_ids[i].size());
while (!rest.empty() && rest.front() == ' ') rest.erase(rest.begin());
it.secondary = rest;
} else {
it.secondary = labels[i];
}
items.push_back(std::move(it));
}
PickerOptions opts;
opts.title = "Select a Copilot model";
opts.page_size = 30;
opts.allow_custom = true;
opts.default_index = static_cast<size_t>(default_idx);
PickerResult r = run_ftxui_picker(items, opts);
if (r.cancelled) {
std::cout << "Model selection cancelled — keeping: "
<< cfg.copilot.model << "\n";
} else if (r.custom) {
cfg.copilot.model = read_line("Custom model id", cfg.copilot.model);
} else {
cfg.copilot.model = choice_ids[r.index];
}
} else {
std::cerr << "Warning: Could not fetch model list from Copilot API and no catalog entry available." << std::endl;
cfg.copilot.model = read_line("Model", cfg.copilot.model);
}
}
static std::string codex_account_label(const codex::AccountInfo& account) {
if (!account.present) return "(not logged in)";
std::ostringstream oss;
oss << account.type;
if (!account.email.empty()) oss << " " << account.email;
if (!account.plan_type.empty()) oss << " (" << account.plan_type << ")";
return oss.str();
}
static bool wait_for_codex_login(codex::AppServerClient& client,
const std::string& login_id) {
std::mutex mu;
std::condition_variable cv;
bool done = false;
client.set_notification_handler(
[&](const std::string& method, const nlohmann::json& params) {
if (method != "account/login/completed") return;
if (!login_id.empty() && params.contains("loginId") &&
params["loginId"].is_string() &&
params["loginId"].get<std::string>() != login_id) {
return;
}
{
std::lock_guard<std::mutex> lk(mu);
done = true;
}
cv.notify_all();
});
std::unique_lock<std::mutex> lk(mu);
for (int elapsed = 0; elapsed < 600; ++elapsed) {
if (cv.wait_for(lk, std::chrono::seconds(1), [&] { return done; })) {
return true;
}
if ((elapsed + 1) % 10 == 0) {
std::cout << " Waiting for Codex login..." << std::endl;
}
}
return false;
}
static void configure_codex(AppConfig& cfg) {
std::cout << "\n--- Codex Configuration ---\n" << std::endl;
codex::AppServerClient client;
std::string error;
if (!client.start(&error) || !client.initialize(&error)) {
std::cerr << "Error: Failed to start `codex app-server`: "
<< error << std::endl;
std::cerr << "Install or update the official Codex CLI, then retry."
<< std::endl;
return;
}
auto account = client.read_account(false, &error);
if (!account.has_value()) {
std::cerr << "Warning: Codex account check failed: " << error << std::endl;
} else if (account->present) {
std::cout << "Codex authentication: "
<< codex_account_label(*account) << std::endl;
if (read_confirm("Re-authenticate?", false)) {
account->present = false;
}
} else {
std::cout << "Codex authentication required." << std::endl;
}
if (!account.has_value() || !account->present) {
std::cout << "\nStarting Codex ChatGPT device login..." << std::endl;
auto login = client.start_device_login(&error);
if (!login.has_value()) {
std::cerr << "Error: Failed to start Codex login: "
<< error << std::endl;
return;
}
std::string url = !login->verification_url.empty()
? login->verification_url
: login->auth_url;
std::cout << "\n Please open: " << url << std::endl;
if (!login->user_code.empty()) {
std::cout << " Enter code: " << login->user_code << std::endl;
}
std::cout << std::endl;
if (!wait_for_codex_login(client, login->login_id)) {
std::cerr << "Authentication timed out." << std::endl;
return;
}
account = client.read_account(true, &error);
if (!account.has_value() || !account->present) {
std::cerr << "Authentication did not produce a Codex account.";
if (!error.empty()) std::cerr << " " << error;
std::cerr << std::endl;
return;
}
std::cout << "Authentication successful: "
<< codex_account_label(*account) << std::endl;
}
std::cout << "\nFetching available Codex models..." << std::endl;
auto models = client.list_models(false, &error);
if (!models.empty()) {
std::vector<PickerItem> items;
std::vector<std::string> ids;
items.reserve(models.size());
ids.reserve(models.size());
std::size_t default_index = 0;
for (std::size_t i = 0; i < models.size(); ++i) {
const auto& m = models[i];
PickerItem item;
item.label = m.id;
std::ostringstream secondary;
bool has_secondary = false;
if (!m.display_name.empty() && m.display_name != m.id) {
secondary << m.display_name;
has_secondary = true;
}
if (!m.description.empty()) {
if (has_secondary) secondary << " ";
secondary << m.description;
has_secondary = true;
}
int context = codex::context_window_for_model(m.id);
if (context > 0) {
if (has_secondary) secondary << " ";
secondary << "ctx=" << format_context(context);
has_secondary = true;
}
if (m.is_default) {
if (has_secondary) secondary << " ";
secondary << "default";
}
item.secondary = secondary.str();
items.push_back(std::move(item));
ids.push_back(m.id);
if (m.id == cfg.codex.model || (cfg.codex.model.empty() && m.is_default)) {
default_index = i;
}
}
PickerOptions opts;
opts.title = "Select a Codex model";
opts.page_size = 30;
opts.allow_custom = true;
opts.default_index = default_index;
PickerResult r = run_ftxui_picker(items, opts);
if (r.cancelled) {
std::cout << "Model selection cancelled - keeping: "
<< cfg.codex.model << "\n";
} else if (r.custom) {
cfg.codex.model = read_line("Custom model id", cfg.codex.model);
} else {
cfg.codex.model = ids[r.index];
}
} else {
std::cerr << "Warning: Could not fetch Codex model list";
if (!error.empty()) std::cerr << ": " << error;
std::cerr << std::endl;
cfg.codex.model = read_line("Model", cfg.codex.model);
}
cfg.provider = "codex";
cfg.openai.models_dev_provider_id.reset();
}
static void configure_openai(AppConfig& cfg) {
std::cout << "\n--- OpenAI Compatible Configuration ---\n" << std::endl;
// Base URL
cfg.openai.base_url = read_line("Base URL", cfg.openai.base_url);
// API Key (masked)
cfg.openai.api_key = read_password("API Key", cfg.openai.api_key);
// Model
cfg.openai.model = read_line("Model", cfg.openai.model);
// Optional connection test
if (read_confirm("\nTest connection?", true)) {
std::cout << "Testing connection to " << cfg.openai.base_url << "/models ..." << std::endl;
cpr::Header headers;
if (!cfg.openai.api_key.empty()) {
headers["Authorization"] = "Bearer " + cfg.openai.api_key;
}
const std::string models_url = cfg.openai.base_url + "/models";
auto proxy_opts = network::proxy_options_for(models_url);
auto r = cpr::Get(
cpr::Url{models_url},
headers,
network::build_ssl_options(proxy_opts),
proxy_opts.proxies,
proxy_opts.auth,
cpr::Timeout{10000}
);
if (r.status_code == 200) {
std::cout << "Connection successful!" << std::endl;
} else if (r.status_code == 0) {
std::cerr << "Connection failed: " << r.error.message << std::endl;
if (!read_confirm("Save configuration anyway?", true)) {
return;
}
} else {
std::cerr << "Connection failed: HTTP " << r.status_code << std::endl;
if (!read_confirm("Save configuration anyway?", true)) {
return;
}
}
}
}
static ModelProfile configure_anthropic(const AppConfig& cfg) {
std::cout << "\n--- Anthropic Configuration ---\n" << std::endl;
std::cout << "Anthropic model listing is not probed yet; enter the model id manually."
<< std::endl;
ModelProfile profile = default_anthropic_profile(cfg);
profile.name = read_line("Profile name", profile.name);
if (profile.name.empty()) profile.name = "anthropic";
profile.base_url = read_line("Base URL", profile.base_url.empty()
? std::string(AnthropicProvider::kDefaultBaseUrl)
: profile.base_url);
do {
profile.api_key = read_password("API Key", profile.api_key);
if (profile.api_key.empty()) {
std::cerr << "API Key is required." << std::endl;
}
} while (profile.api_key.empty());
do {
profile.model = read_line("Model", profile.model);
if (profile.model.empty()) {
std::cerr << "Model is required." << std::endl;
}
} while (profile.model.empty());
profile.provider = "anthropic";
profile.models_dev_provider_id = "anthropic";
return profile;
}
static void configure_upgrade_service(AppConfig& cfg) {
std::cout << "\n--- Upgrade Service Configuration ---\n" << std::endl;
const std::string current = normalize_upgrade_base_url(cfg.upgrade.base_url);
while (true) {
const std::string raw = read_line("Upgrade service URL", current);
const std::string normalized = normalize_upgrade_base_url(raw);
if (is_valid_upgrade_base_url(normalized)) {
cfg.upgrade.base_url = normalized;
return;
}
std::cerr << "Invalid upgrade service URL: use a non-empty http or https URL."
<< std::endl;
if (!read_confirm("Try again?", true)) {
cfg.upgrade.base_url = current;
std::cout << "Keeping upgrade service URL: " << current << std::endl;
return;
}
}
}
int run_configure(const AppConfig& current_config) {
AppConfig cfg = current_config;
std::cout << "\n=== acecode Configuration Wizard ===\n" << std::endl;
const auto compat_providers = openai_compat_providers();
const auto provider_choices =
build_configure_provider_choices(compat_providers);
const std::size_t default_provider =
default_configure_provider_index(cfg, provider_choices);
const auto selected_index =
run_configure_provider_picker(provider_choices, default_provider);
if (!selected_index.has_value()) {
std::cout << "Configuration cancelled.\n";
return 0;
}
const ConfigureProviderChoice& selected = provider_choices[*selected_index];
std::optional<ModelProfile> configured_profile_override;
switch (selected.kind) {
case ConfigureProviderKind::Copilot:
cfg.provider = "copilot";
// Switching to Copilot wipes the openai-side provider hint to avoid
// stale source labels in future configure runs.
cfg.openai.models_dev_provider_id.reset();
configure_copilot(cfg);
break;
case ConfigureProviderKind::CustomAnthropic:
cfg.provider = "anthropic";
cfg.openai.models_dev_provider_id.reset();
configured_profile_override = configure_anthropic(cfg);
break;
case ConfigureProviderKind::CustomOpenAI:
cfg.provider = "openai";
cfg.openai.models_dev_provider_id.reset();
configure_openai(cfg);
break;
case ConfigureProviderKind::Catalog:
if (!selected.catalog_provider) {
std::cerr << "Selected catalog provider is unavailable.\n";
return 1;
}
if (!configure_openai_from_provider_preset(
cfg, *selected.catalog_provider)) {
std::cout << "Configuration cancelled.\n";
return 0;
}
break;
}
if (configured_profile_override.has_value()) {
upsert_saved_model_profile(cfg, *configured_profile_override);
} else {
upsert_configured_saved_model(cfg);
}
configure_upgrade_service(cfg);
// Configuration summary
std::cout << "\n--- Configuration Summary ---" << std::endl;
std::cout << " Source: " << format_source_line(cfg) << std::endl;
std::cout << " Provider: " << cfg.provider << std::endl;
if (cfg.provider == "copilot") {
std::cout << " Model: " << cfg.copilot.model << std::endl;
} else if (cfg.provider == "anthropic" && configured_profile_override.has_value()) {
std::cout << " Base URL: " << configured_profile_override->base_url << std::endl;
std::cout << " API Key: " << mask_key(configured_profile_override->api_key) << std::endl;
std::cout << " Model: " << configured_profile_override->model << std::endl;
} else {
std::cout << " Base URL: " << cfg.openai.base_url << std::endl;
std::cout << " API Key: " << mask_key(cfg.openai.api_key) << std::endl;
std::cout << " Model: " << cfg.openai.model << std::endl;
if (cfg.openai.models_dev_provider_id.has_value()) {
std::cout << " Provider id (models.dev): "
<< *cfg.openai.models_dev_provider_id << std::endl;
}
}
std::cout << " Saved model: " << cfg.default_model_name << std::endl;
std::cout << " Upgrade service URL: " << cfg.upgrade.base_url << std::endl;
std::cout << std::endl;
if (read_confirm("Save configuration?", true)) {
save_config(cfg);
LOG_INFO(std::string("configure: saved (") + format_source_line(cfg) +
", model=" + (cfg.provider == "copilot"
? cfg.copilot.model
: (cfg.provider == "anthropic" && configured_profile_override.has_value()
? configured_profile_override->model
: cfg.openai.model)) + ")");
std::cout << "Configuration saved!" << std::endl;
} else {
std::cout << "Configuration cancelled." << std::endl;
}
return 0;
}
} // namespace acecode