-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
388 lines (358 loc) · 14.6 KB
/
Copy pathmain.cpp
File metadata and controls
388 lines (358 loc) · 14.6 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
// SPDX-FileCopyrightText: 2026 Paolo Anzani
// SPDX-License-Identifier: Apache-2.0
#include "agent.h"
#include "conversation.h"
#include "model-catalog.h"
#include "oauth.h"
#include "response-item.h"
#include "ui.h"
#include <chrono>
#include <charconv>
#include <cstdlib>
#include <expected>
#include <filesystem>
#include <iostream>
#include <limits>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
namespace {
constexpr std::string_view default_model = "gpt-5.6-sol";
void printUsage(const std::string_view executable) {
std::cout << "Usage:\n"
<< " " << executable << " login [--device-auth]\n"
<< " " << executable << " logout\n"
<< " " << executable << " list\n"
<< " " << executable << " show ID\n"
<< " " << executable << " [--model MODEL] resume ID [PROMPT]\n"
<< " " << executable << " [--model MODEL]\n"
<< " " << executable << " [--model MODEL] PROMPT\n";
}
struct AgentRequest {
std::string model;
bool model_explicit;
std::optional<std::string> prompt;
std::optional<std::string> resume_id;
};
std::expected<AgentRequest, std::string> parseAgentRequest(const int argc, char *argv[]) {
std::string model(default_model);
bool model_explicit = false;
int argument = 1;
if (argument < argc && std::string_view(argv[argument]) == "--model") {
if (++argument == argc || std::string_view(argv[argument]).empty()) {
return std::unexpected("--model requires a model name");
}
model = argv[argument++];
model_explicit = true;
}
std::optional<std::string> resume_id;
if (argument < argc && std::string_view(argv[argument]) == "resume") {
++argument;
if (argument == argc || std::string_view(argv[argument]).empty()) {
return std::unexpected("resume requires a conversation ID");
}
resume_id = argv[argument++];
}
std::string prompt;
for (; argument < argc; ++argument) {
if (!prompt.empty()) {
prompt += ' ';
}
prompt += argv[argument];
}
return AgentRequest{
.model = std::move(model),
.model_explicit = model_explicit,
.prompt = prompt.empty() ? std::nullopt
: std::optional<std::string>(std::move(prompt)),
.resume_id = std::move(resume_id),
};
}
std::expected<std::filesystem::path, std::string> conversationPath(const std::string_view id) {
if (id.empty() || id.find('/') != std::string_view::npos || id == "." || id == "..") {
return std::unexpected("Invalid conversation ID");
}
auto directory = microcodex::conversationDirectory();
if (!directory) return std::unexpected(directory.error());
std::filesystem::path filename(id);
if (filename.extension() != ".jsonl") filename += ".jsonl";
const std::filesystem::path path = *directory / filename;
std::error_code error;
if (!std::filesystem::is_regular_file(path, error)) {
return std::unexpected("Conversation '" + std::string(id) + "' was not found");
}
return path;
}
int listSavedConversations() {
auto directory = microcodex::conversationDirectory();
if (!directory) {
std::cerr << directory.error() << '\n';
return 1;
}
auto conversations = microcodex::listConversations(*directory);
if (!conversations) {
std::cerr << conversations.error() << '\n';
return 1;
}
for (const microcodex::ConversationSummary &conversation : *conversations) {
std::cout << conversation.metadata.id << '\t'
<< conversation.metadata.created_at << '\t'
<< conversation.metadata.model << '\t'
<< conversation.metadata.working_directory << '\n';
}
return 0;
}
std::expected<void, std::string> printSavedTurn(const microcodex::SavedTurn &turn) {
for (const std::string &item : turn.items) {
auto message = microcodex::responseMessage(item);
if (!message) return std::unexpected(message.error());
if (*message) {
std::cout << (*message)->role << ": " << (*message)->text << '\n';
continue;
}
auto call = microcodex::responseToolCall(item);
if (!call) return std::unexpected(call.error());
if (*call) {
std::cout << "tool " << (*call)->name << ": " << (*call)->arguments << '\n';
continue;
}
auto output = microcodex::responseToolOutput(item);
if (!output) return std::unexpected(output.error());
if (*output) {
std::cout << "tool output " << (*output)->call_id << ": "
<< (*output)->output << '\n';
}
}
return {};
}
int showSavedConversation(const std::string_view id) {
auto path = conversationPath(id);
if (!path) {
std::cerr << path.error() << '\n';
return 1;
}
auto file = microcodex::ConversationFile::openReadOnly(*path);
if (!file) {
std::cerr << file.error() << '\n';
return 1;
}
auto resumed = file->resume();
if (!resumed) {
std::cerr << resumed.error() << '\n';
return 1;
}
auto turns = file->readTurnsBefore(file->turnCount(),
std::numeric_limits<std::size_t>::max());
if (!turns) {
std::cerr << turns.error() << '\n';
return 1;
}
for (const microcodex::SavedTurn &turn : *turns) {
auto printed = printSavedTurn(turn);
if (!printed) {
std::cerr << printed.error() << '\n';
return 1;
}
}
return 0;
}
int completeLogin(const std::expected<microcodex::OAuthCredentials, std::string> &credentials) {
if (!credentials) {
std::cerr << "Login failed: " << credentials.error() << '\n';
return 1;
}
auto saved = microcodex::saveOAuthCredentials(*credentials);
if (!saved) {
std::cerr << "Login succeeded, but credentials could not be saved: " << saved.error() << '\n';
return 1;
}
std::cout << "Logged in.\n";
return 0;
}
int login() {
auto login = microcodex::OAuthLogin::start();
if (!login) {
std::cerr << "Login failed: " << login.error() << '\n';
return 1;
}
std::cout << "Open this URL to log in:\n" << login->authorizationUrl() << "\n\n"
<< "Waiting for the browser callback on port " << login->callbackPort() << "...\n"
<< "On a remote machine? Run 'microcodex login --device-auth' instead.\n";
return completeLogin(login->finish(std::chrono::minutes(5)));
}
int deviceLogin() {
auto login = microcodex::startOAuthDeviceLogin();
if (!login) {
std::cerr << "Login failed: " << login.error() << '\n';
return 1;
}
std::cout << "Open this URL in your browser:\n" << login->verification_url << "\n\n"
<< "Enter this one-time code (expires in 15 minutes):\n"
<< login->user_code << "\n\n"
<< "Continue only if you started this login in MicroCodex.\n"
<< "Waiting for authorization...\n";
return completeLogin(microcodex::finishOAuthDeviceLogin(*login));
}
int logout() {
auto logged_out = microcodex::logoutOAuth();
if (!logged_out) {
std::cerr << "Logout failed: " << logged_out.error() << '\n';
return 1;
}
std::cout << (*logged_out ? "Logged out.\n" : "Already logged out.\n");
return 0;
}
int runPrompt(microcodex::CodexApiConfig config, const std::string_view prompt) {
bool received_text = false;
microcodex::CodexEventEmitter events([&received_text](const microcodex::CodexEvent &event) {
switch (event.type) {
case microcodex::CodexEventType::TextDelta:
std::cout << event.text << std::flush;
received_text = true;
break;
case microcodex::CodexEventType::ToolStarted:
std::cerr << "\n[tool " << event.tool_name << "] " << event.text << '\n';
break;
case microcodex::CodexEventType::ToolFinished:
std::cerr << "[tool " << event.tool_name << (event.succeeded ? " completed]" : " failed]")
<< ' ' << event.text << '\n';
break;
default:
break;
}
});
microcodex::CodexApi agent(std::move(config), events);
auto response = agent.sendUserMessage(prompt);
if (!response) {
std::cerr << "Agent failed: " << response.error() << '\n';
return 1;
}
if (!received_text && !response->text.empty()) {
std::cout << response->text;
}
if (received_text || !response->text.empty()) {
std::cout << '\n';
}
return 0;
}
std::expected<void, std::string> applySizeEnvironment(const char *name, std::size_t &destination) {
const char *text = std::getenv(name);
if (text == nullptr || text[0] == '\0') return {};
std::size_t value = 0;
const char *end = text;
while (*end != '\0') ++end;
const auto [parsed_end, error] = std::from_chars(text, end, value);
if (error != std::errc{} || parsed_end != end) {
return std::unexpected(std::string(name) + " must be an unsigned integer");
}
destination = value;
return {};
}
std::expected<void, std::string> applyConversationEnvironment(microcodex::CodexApiConfig &config) {
auto compact_at = applySizeEnvironment("MICROCODEX_COMPACT_AT_TOKENS",
config.compaction.compact_at_tokens);
if (!compact_at) return compact_at;
return applySizeEnvironment("MICROCODEX_RETAINED_CONTEXT_TOKENS",
config.compaction.retained_context_tokens);
}
std::expected<void, std::string> applyModelContextLimits(microcodex::CodexApiConfig &config) {
auto models = microcodex::fetchModelContextLimits(config.endpoint, config.access_token, config.account_id);
if (!models) return std::unexpected(models.error());
const microcodex::ModelContextLimits *model = microcodex::findModelContextLimits(*models, config.model);
if (model == nullptr) return std::unexpected("Models API did not return metadata for '" + config.model + "'");
config.compaction = microcodex::compactionConfigForModel(*model, config.compaction.retained_context_tokens, config.compaction.maximum_summary_bytes);
return {};
}
} // namespace
int main(const int argc, char *argv[]) {
const std::string_view executable = argc > 0 ? argv[0] : "microcodex";
if (argc > 1 && (std::string_view(argv[1]) == "--help" || std::string_view(argv[1]) == "-h")) {
printUsage(executable);
return 0;
}
if (argc > 1 && std::string_view(argv[1]) == "login") {
if (argc == 2) return login();
if (argc == 3 && std::string_view(argv[2]) == "--device-auth") return deviceLogin();
printUsage(executable);
return 1;
}
if (argc > 1 && std::string_view(argv[1]) == "logout") {
return logout();
}
if (argc > 1 && std::string_view(argv[1]) == "list") {
return listSavedConversations();
}
if (argc > 1 && std::string_view(argv[1]) == "show") {
if (argc != 3) {
std::cerr << "show requires one conversation ID\n";
return 1;
}
return showSavedConversation(argv[2]);
}
auto request = parseAgentRequest(argc, argv);
if (!request) {
std::cerr << request.error() << '\n';
printUsage(executable);
return 1;
}
std::optional<std::filesystem::path> resume_path;
if (request->resume_id) {
auto path = conversationPath(*request->resume_id);
if (!path) {
std::cerr << path.error() << '\n';
return 1;
}
auto metadata = microcodex::readConversationMetadata(*path);
if (!metadata) {
std::cerr << metadata.error() << '\n';
return 1;
}
if (!request->model_explicit) request->model = metadata->model;
std::error_code error;
std::filesystem::current_path(metadata->working_directory, error);
if (error) {
std::cerr << "Could not restore conversation working directory: "
<< error.message() << '\n';
return 1;
}
resume_path = std::move(*path);
}
auto credentials = microcodex::loadOAuthCredentials();
if (!credentials) {
std::cerr << "Could not load saved credentials: " << credentials.error() << '\n';
return 1;
}
if (!*credentials) {
std::cerr << "Not logged in. Run '" << executable << " login' first.\n";
return 1;
}
auto config = microcodex::makeCodingAgentConfig(std::move(request->model));
config.resume_conversation = std::move(resume_path);
microcodex::applyOAuthCredentials(config, **credentials);
// Keep transport selection at the executable boundary so black-box tests
// can exercise the real CLI against a deterministic loopback server. The
// default remains the production Codex endpoint.
if (const char *endpoint = std::getenv("MICROCODEX_API_ENDPOINT");
endpoint != nullptr && endpoint[0] != '\0') {
config.endpoint = endpoint;
}
auto model_context = applyModelContextLimits(config);
if (!model_context) {
std::cerr << "Warning: " << model_context.error() << ". Using built-in context limits.\n";
}
auto configured = applyConversationEnvironment(config);
if (!configured) {
std::cerr << configured.error() << '\n';
return 1;
}
if (request->prompt) {
return runPrompt(std::move(config), *request->prompt);
}
auto result = microcodex::runInteractive(std::move(config));
if (!result) {
std::cerr << result.error() << '\n';
return 1;
}
return 0;
}