-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcodex_provider.cpp
More file actions
257 lines (232 loc) · 8.55 KB
/
Copy pathcodex_provider.cpp
File metadata and controls
257 lines (232 loc) · 8.55 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
#include "codex_provider.hpp"
#include "codex/codex_app_server_client.hpp"
#include "../utils/logger.hpp"
#include "../utils/utf8_path.hpp"
#include <condition_variable>
#include <filesystem>
#include <mutex>
#include <sstream>
namespace acecode {
namespace {
std::string current_cwd_utf8() {
std::error_code ec;
auto cwd = std::filesystem::current_path(ec);
if (ec) return {};
return path_to_utf8(cwd);
}
std::string role_label(const ChatMessage& message) {
if (message.role == "system") return "System";
if (message.role == "assistant") return "Assistant";
if (message.role == "tool") return "Tool";
if (message.role == "user") return "User";
return "Message";
}
std::string build_codex_input_text(const std::vector<ChatMessage>& messages) {
std::ostringstream out;
out << "Continue this ACECode conversation. Preserve the user's latest "
"request as the active task.\n\n";
for (const auto& message : messages) {
if (message.is_meta || message.content.empty()) continue;
out << "### " << role_label(message);
if (!message.tool_call_id.empty()) out << " tool_call_id=" << message.tool_call_id;
out << "\n" << message.content << "\n\n";
if (message.role == "assistant" && !message.tool_calls.is_null() &&
!message.tool_calls.empty()) {
out << "Assistant tool calls:\n" << message.tool_calls.dump() << "\n\n";
}
}
return out.str();
}
void emit_error(const StreamCallback& callback,
const std::string& model,
const std::string& message) {
ProviderErrorInfo info;
info.kind = ProviderErrorKind::Unknown;
info.provider = "codex";
info.model = model;
info.display_message = message;
StreamEvent evt;
evt.type = StreamEventType::Error;
evt.error = message;
evt.provider_error = std::move(info);
callback(evt);
}
std::string turn_error_message(const nlohmann::json& turn) {
if (!turn.is_object()) return "Codex turn failed";
if (turn.contains("error") && turn["error"].is_object()) {
const auto& err = turn["error"];
if (err.contains("message") && err["message"].is_string()) {
return err["message"].get<std::string>();
}
}
return "Codex turn status: " + turn.value("status", std::string{"unknown"});
}
} // namespace
CodexProvider::CodexProvider(std::string model)
: model_(std::move(model)) {}
bool CodexProvider::is_authenticated() {
codex::AppServerClient client;
std::string error;
if (!client.start(&error) || !client.initialize(&error)) {
LOG_WARN("[codex] auth probe failed: " + error);
return false;
}
auto account = client.read_account(false, &error);
if (!account.has_value()) {
LOG_WARN("[codex] account/read failed: " + error);
return false;
}
return account->present;
}
ChatResponse CodexProvider::chat(
const std::vector<ChatMessage>& messages,
const std::vector<ToolDef>& tools
) {
ChatResponse response;
response.finish_reason = "stop";
chat_stream(messages, tools, [&](const StreamEvent& evt) {
if (evt.type == StreamEventType::Delta) {
response.content += evt.content;
} else if (evt.type == StreamEventType::ReasoningDelta) {
response.reasoning_content += evt.content;
} else if (evt.type == StreamEventType::Usage) {
response.usage = evt.usage;
} else if (evt.type == StreamEventType::Error) {
response.content = "[Error] " + evt.error;
response.finish_reason = "error";
response.provider_error = evt.provider_error;
}
});
return response;
}
void CodexProvider::chat_stream(
const std::vector<ChatMessage>& messages,
const std::vector<ToolDef>& tools,
const StreamCallback& callback,
std::atomic<bool>* abort_flag
) {
if (!tools.empty()) {
LOG_WARN("[codex] ACECode tool definitions are not forwarded to app-server; "
"Codex app-server owns its own tool runtime");
}
codex::AppServerClient client;
std::string error;
if (!client.start(&error) || !client.initialize(&error)) {
emit_error(callback, model_, "Codex app-server unavailable: " + error);
return;
}
auto account = client.read_account(false, &error);
if (!account.has_value() || !account->present) {
emit_error(callback, model_,
"Codex account is not logged in. Run `acecode configure` and select Codex.");
return;
}
std::mutex mu;
std::condition_variable cv;
bool completed = false;
bool failed = false;
std::string failure_message;
TokenUsage last_usage;
client.set_notification_handler([&](const std::string& method, const nlohmann::json& params) {
if (method == "item/agentMessage/delta") {
std::string delta;
if (params.contains("delta") && params["delta"].is_string()) {
delta = params["delta"].get<std::string>();
}
if (!delta.empty()) {
StreamEvent evt;
evt.type = StreamEventType::Delta;
evt.content = std::move(delta);
callback(evt);
}
return;
}
if (method == "item/reasoning/summaryTextDelta") {
std::string delta;
if (params.contains("delta") && params["delta"].is_string()) {
delta = params["delta"].get<std::string>();
}
if (!delta.empty()) {
StreamEvent evt;
evt.type = StreamEventType::ReasoningDelta;
evt.content = std::move(delta);
callback(evt);
}
return;
}
if (method == "thread/tokenUsage/updated" &&
params.contains("tokenUsage") && params["tokenUsage"].is_object()) {
const auto& usage = params["tokenUsage"];
const auto* source = &usage;
if (usage.contains("last") && usage["last"].is_object()) {
source = &usage["last"];
}
TokenUsage parsed;
parsed.prompt_tokens = source->value("inputTokens", 0);
parsed.completion_tokens = source->value("outputTokens", 0);
parsed.reasoning_tokens = source->value("reasoningOutputTokens", 0);
parsed.cache_read_tokens = source->value("cachedInputTokens", 0);
parsed.total_tokens = source->value("totalTokens", 0);
parsed.has_data = true;
std::lock_guard<std::mutex> lk(mu);
last_usage = parsed;
return;
}
if (method == "turn/completed") {
std::lock_guard<std::mutex> lk(mu);
completed = true;
if (params.contains("turn") && params["turn"].is_object()) {
std::string status = params["turn"].value("status", std::string{});
if (status != "completed") {
failed = true;
failure_message = turn_error_message(params["turn"]);
}
}
cv.notify_all();
}
});
auto thread_id = client.start_thread(model_, current_cwd_utf8(), &error);
if (!thread_id.has_value()) {
emit_error(callback, model_, "Codex thread/start failed: " + error);
return;
}
const std::string input_text = build_codex_input_text(messages);
auto turn_id = client.start_turn(*thread_id, model_, current_cwd_utf8(), input_text, &error);
if (!turn_id.has_value()) {
emit_error(callback, model_, "Codex turn/start failed: " + error);
return;
}
std::unique_lock<std::mutex> lk(mu);
while (!completed) {
if (abort_flag && abort_flag->load()) {
failed = true;
failure_message = "Request cancelled";
break;
}
cv.wait_for(lk, std::chrono::milliseconds(100));
if (!client.running()) {
failed = true;
failure_message = "Codex app-server stopped before turn completion";
break;
}
}
if (last_usage.has_data) {
StreamEvent usage_evt;
usage_evt.type = StreamEventType::Usage;
usage_evt.usage = last_usage;
lk.unlock();
callback(usage_evt);
lk.lock();
}
if (failed) {
std::string message = failure_message.empty() ? "Codex turn failed" : failure_message;
lk.unlock();
emit_error(callback, model_, message);
return;
}
lk.unlock();
StreamEvent done;
done.type = StreamEventType::Done;
callback(done);
}
} // namespace acecode