-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenCodeHttpClient.java
More file actions
353 lines (303 loc) · 13 KB
/
OpenCodeHttpClient.java
File metadata and controls
353 lines (303 loc) · 13 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
package com.opencode.minecraft.client.http;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.opencode.minecraft.OpenCodeMod;
import com.opencode.minecraft.client.session.SessionInfo;
import com.opencode.minecraft.config.ModConfig;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Flow;
import java.util.function.Consumer;
/**
* HTTP client for communicating with the OpenCode server.
* Uses Java's built-in HttpClient for REST and SSE.
*/
public class OpenCodeHttpClient {
private final HttpClient httpClient;
private final String baseUrl;
private final String directory;
private final Gson gson = new Gson();
private final ExecutorService executor = Executors.newCachedThreadPool();
private volatile boolean connected = false;
private volatile boolean sseRunning = false;
private Consumer<SseEvent> eventHandler;
private Consumer<String> responseHandler;
public OpenCodeHttpClient(ModConfig config) {
this.baseUrl = config.serverUrl;
this.directory = config.workingDirectory;
this.httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.executor(executor)
.build();
}
/**
* Checks if the server is healthy
*/
public CompletableFuture<Boolean> checkHealth() {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/global/health"))
.timeout(Duration.ofSeconds(5))
.GET()
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
connected = response.statusCode() == 200;
return connected;
})
.exceptionally(e -> {
connected = false;
OpenCodeMod.LOGGER.warn("Health check failed: {}", e.getMessage());
return false;
});
}
/**
* Creates a new session
*/
public CompletableFuture<SessionInfo> createSession() {
JsonObject body = new JsonObject();
// Don't send x-opencode-directory header - let OpenCode use its default directory
// (The mod's config directory contains a config file that OpenCode doesn't understand)
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/session"))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(10))
.POST(HttpRequest.BodyPublishers.ofString(body.toString()))
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() != 200 && response.statusCode() != 201) {
throw new RuntimeException("Failed to create session: " + response.statusCode());
}
JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
return SessionInfo.fromJson(json);
});
}
/**
* Lists all sessions
*/
public CompletableFuture<List<SessionInfo>> listSessions() {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/session"))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() != 200) {
throw new RuntimeException("Failed to list sessions: " + response.statusCode());
}
JsonArray array = JsonParser.parseString(response.body()).getAsJsonArray();
List<SessionInfo> sessions = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
sessions.add(SessionInfo.fromJson(array.get(i).getAsJsonObject()));
}
return sessions;
});
}
/**
* Gets a specific session
*/
public CompletableFuture<SessionInfo> getSession(String sessionId) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/session/" + sessionId))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() != 200) {
throw new RuntimeException("Failed to get session: " + response.statusCode());
}
JsonObject json = JsonParser.parseString(response.body()).getAsJsonObject();
return SessionInfo.fromJson(json);
});
}
/**
* Sends a prompt to a session via the /session/{id}/message endpoint.
* This is the correct API endpoint for sending messages programmatically.
*/
public CompletableFuture<String> sendPrompt(String sessionId, String text) {
// Build the message body with parts array structure
JsonObject textPart = new JsonObject();
textPart.addProperty("type", "text");
textPart.addProperty("text", text);
JsonArray parts = new JsonArray();
parts.add(textPart);
JsonObject body = new JsonObject();
body.add("parts", parts);
String url = baseUrl + "/session/" + sessionId + "/message";
OpenCodeMod.LOGGER.info("Sending message to session {}: {}", sessionId, text);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.timeout(Duration.ofMinutes(10))
.POST(HttpRequest.BodyPublishers.ofString(body.toString()))
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() != 200) {
OpenCodeMod.LOGGER.error("Failed to send message: {} - {}", response.statusCode(), response.body());
throw new RuntimeException("Failed to send message: " + response.statusCode());
}
OpenCodeMod.LOGGER.info("Message sent successfully to session {}", sessionId);
// Response is streamed, SSE events will deliver the actual content
return "Message sent";
})
.exceptionally(e -> {
OpenCodeMod.LOGGER.error("Failed to send message: {}", e.getMessage(), e);
return "Error: " + e.getMessage();
});
}
/**
* Aborts the current session operation
*/
public CompletableFuture<Void> abortSession(String sessionId) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/session/" + sessionId + "/abort"))
.timeout(Duration.ofSeconds(10))
.POST(HttpRequest.BodyPublishers.noBody())
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.discarding())
.thenAccept(response -> {
if (response.statusCode() != 200 && response.statusCode() != 204) {
OpenCodeMod.LOGGER.warn("Abort returned status: {}", response.statusCode());
}
});
}
/**
* Gets the message history for a session
*/
public CompletableFuture<JsonArray> getSessionMessages(String sessionId) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/session/" + sessionId + "/message"))
.timeout(Duration.ofSeconds(10))
.GET()
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(response -> {
if (response.statusCode() != 200) {
OpenCodeMod.LOGGER.warn("Failed to get messages: {}", response.statusCode());
return new JsonArray();
}
return JsonParser.parseString(response.body()).getAsJsonArray();
})
.exceptionally(e -> {
OpenCodeMod.LOGGER.warn("Failed to get messages: {}", e.getMessage());
return new JsonArray();
});
}
/**
* Subscribes to the global event stream (SSE)
*/
public void subscribeToEvents(Consumer<SseEvent> handler) {
this.eventHandler = handler;
if (sseRunning) {
OpenCodeMod.LOGGER.debug("SSE already running");
return;
}
sseRunning = true;
executor.submit(this::runSseLoop);
}
private void runSseLoop() {
while (sseRunning) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/global/event"))
.header("Accept", "text/event-stream")
.GET()
.build();
httpClient.sendAsync(request, HttpResponse.BodyHandlers.fromLineSubscriber(
new SseLineSubscriber(this::handleSseLine)))
.join();
} catch (Exception e) {
if (sseRunning) {
OpenCodeMod.LOGGER.warn("SSE connection error, reconnecting in 5s: {}", e.getMessage());
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
}
}
}
}
private void handleSseLine(String line) {
if (line == null || line.isEmpty()) return;
if (line.startsWith("data: ")) {
String data = line.substring(6);
try {
JsonObject json = JsonParser.parseString(data).getAsJsonObject();
// SSE events have structure: { directory, payload: { type, properties } }
String dir = json.has("directory") ? json.get("directory").getAsString() : "";
String type = "unknown";
JsonObject properties = null;
if (json.has("payload")) {
JsonObject payload = json.getAsJsonObject("payload");
type = payload.has("type") ? payload.get("type").getAsString() : "unknown";
if (payload.has("properties")) {
properties = payload.getAsJsonObject("properties");
}
}
OpenCodeMod.LOGGER.debug("SSE event received: type={}, hasProps={}", type, properties != null);
SseEvent event = new SseEvent(type, properties, dir);
if (eventHandler != null) {
eventHandler.accept(event);
}
} catch (Exception e) {
OpenCodeMod.LOGGER.warn("Failed to parse SSE data: {} - raw: {}", e.getMessage(), data);
}
}
}
public void setResponseHandler(Consumer<String> handler) {
this.responseHandler = handler;
}
public boolean isConnected() {
return connected;
}
public void disconnect() {
sseRunning = false;
connected = false;
}
public void shutdown() {
disconnect();
executor.shutdown();
}
/**
* Simple line subscriber for SSE
*/
private static class SseLineSubscriber implements Flow.Subscriber<String> {
private final Consumer<String> lineHandler;
private Flow.Subscription subscription;
SseLineSubscriber(Consumer<String> lineHandler) {
this.lineHandler = lineHandler;
}
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(String item) {
lineHandler.accept(item);
}
@Override
public void onError(Throwable throwable) {
OpenCodeMod.LOGGER.debug("SSE stream error: {}", throwable.getMessage());
}
@Override
public void onComplete() {
OpenCodeMod.LOGGER.debug("SSE stream completed");
}
}
}