Repository navigation
Expand file tree
/
Copy pathproxy.php
More file actions
477 lines (418 loc) · 15.7 KB
/
Copy pathproxy.php
File metadata and controls
477 lines (418 loc) · 15.7 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
<?php
// SSE proxy between Kobo frontend and OpenCode server
// Persists session ID in a file so chat history is preserved across messages
// CORS: default allow-all for compatibility; set OPENCODE_CORS_ORIGIN to tighten.
$corsOrigin = getenv('OPENCODE_CORS_ORIGIN');
if (!$corsOrigin) {
$corsOrigin = '*';
}
header('Access-Control-Allow-Origin: ' . $corsOrigin);
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
while (ob_get_level()) ob_end_clean();
$prompt = isset($_GET['prompt']) ? $_GET['prompt'] : '';
$opencode = getenv('OPENCODE_URL');
if (!$opencode) {
$opencode = 'http://127.0.0.1:4096';
}
$opencode = rtrim($opencode, '/');
$sessionFile = __DIR__ . '/.opencode_session';
if (empty($prompt) && !isset($_GET['history']) && !isset($_GET['sessions']) && !isset($_GET['load'])) {
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
echo "data: " . json_encode(array('error' => 'No prompt provided')) . "\n\n";
echo "data: [DONE]\n\n";
flush();
exit;
}
// Helper: make a JSON request to the OpenCode server using curl CLI
function opencode_request($method, $url, $body = null) {
$cmd = 'curl -s -X ' . escapeshellarg($method) . ' ' . escapeshellarg($url);
$cmd .= ' -H "Content-Type: application/json"';
if ($body !== null) {
$cmd .= ' -d ' . escapeshellarg(json_encode($body));
}
$descriptors = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w')
);
$proc = proc_open($cmd, $descriptors, $pipes);
if (!is_resource($proc)) {
return null;
}
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($proc);
return json_decode($output, true);
}
// Handle history/import request (returns JSON, not SSE)
if (isset($_GET['history'])) {
header('Content-Type: application/json');
if (!file_exists($sessionFile)) {
echo json_encode(array('error' => 'No session found'));
exit;
}
$savedID = trim(file_get_contents($sessionFile));
if ($savedID === '') {
echo json_encode(array('error' => 'Empty session ID'));
exit;
}
// GET /session/{id}/message returns array of {info: {role, ...}, parts: [{type, text, ...}]}
$messages = opencode_request('GET', $opencode . '/session/' . $savedID . '/message');
if ($messages === null) {
echo json_encode(array('error' => 'Failed to fetch messages from server'));
exit;
}
echo json_encode($messages);
exit;
}
// Handle sessions list request (returns JSON list of recent sessions)
if (isset($_GET['sessions'])) {
header('Content-Type: application/json');
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 20;
$sessions = opencode_request('GET', $opencode . '/session?limit=' . $limit);
if ($sessions === null) {
echo json_encode(array('error' => 'Failed to fetch sessions'));
exit;
}
echo json_encode($sessions);
exit;
}
// Handle load session request (switches to an existing session and returns its messages)
if (isset($_GET['load'])) {
header('Content-Type: application/json');
$loadID = $_GET['load'];
if ($loadID === '') {
echo json_encode(array('error' => 'No session ID provided'));
exit;
}
// Verify session exists
$session = opencode_request('GET', $opencode . '/session/' . $loadID);
if (!$session || !isset($session['id'])) {
echo json_encode(array('error' => 'Session not found'));
exit;
}
// Save this session ID so subsequent prompts go to it
file_put_contents($sessionFile, $loadID);
// Return its messages
$messages = opencode_request('GET', $opencode . '/session/' . $loadID . '/message');
if ($messages === null) {
echo json_encode(array('error' => 'Failed to fetch messages'));
exit;
}
echo json_encode($messages);
exit;
}
// Streaming response (SSE)
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
// 1. Get or create session
$sessionID = null;
// Try to reuse existing session
if (file_exists($sessionFile)) {
$savedID = trim(file_get_contents($sessionFile));
if ($savedID !== '') {
// Verify session still exists
$check = opencode_request('GET', $opencode . '/session/' . $savedID);
if ($check && isset($check['id'])) {
$sessionID = $savedID;
}
}
}
// Create new session if needed
if ($sessionID === null) {
$session = opencode_request('POST', $opencode . '/session', new stdClass());
if (!$session || !isset($session['id'])) {
echo "data: " . json_encode(array('error' => 'Failed to create session')) . "\n\n";
echo "data: [DONE]\n\n";
flush();
exit;
}
$sessionID = $session['id'];
file_put_contents($sessionFile, $sessionID);
}
// 2. Connect to the /event SSE stream via curl subprocess (long-lived)
$sseCmd = 'curl -sN ' . escapeshellarg($opencode . '/event');
$sseDescriptors = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w')
);
$sseProc = proc_open($sseCmd, $sseDescriptors, $ssePipes);
if (!is_resource($sseProc)) {
echo "data: " . json_encode(array('error' => 'Failed to connect to event stream')) . "\n\n";
echo "data: [DONE]\n\n";
flush();
exit;
}
fclose($ssePipes[0]);
// Wait for SSE connection to establish (server.connected event)
// Read lines until we see server.connected, discarding any buffered events
stream_set_blocking($ssePipes[1], true);
stream_set_timeout($ssePipes[1], 5);
$connected = false;
$connectAttempts = 0;
while (!$connected && $connectAttempts < 20) {
$connectLine = fgets($ssePipes[1]);
$connectAttempts++;
if ($connectLine === false) break;
$connectLine = trim($connectLine);
if (strpos($connectLine, 'data: ') === 0) {
$connectData = json_decode(substr($connectLine, 6), true);
if ($connectData && isset($connectData['type']) && $connectData['type'] === 'server.connected') {
$connected = true;
fgets($ssePipes[1]); // consume trailing blank line
}
}
}
if (!$connected) {
echo "data: " . json_encode(array('error' => 'Failed to establish SSE connection')) . "\n\n";
echo "data: [DONE]\n\n";
flush();
fclose($ssePipes[1]);
fclose($ssePipes[2]);
proc_close($sseProc);
exit;
}
// 3. Send the prompt asynchronously
// Read provider/model from query params, fall back to anthropic/claude-haiku-4-5
$providerID = isset($_GET['provider']) ? $_GET['provider'] : 'anthropic';
$modelID = isset($_GET['model']) ? $_GET['model'] : 'claude-haiku-4-5';
$promptBody = array(
'model' => array(
'providerID' => $providerID,
'modelID' => $modelID
),
'parts' => array(
array(
'type' => 'text',
'text' => $prompt
)
)
);
$promptJson = json_encode($promptBody);
$promptUrl = $opencode . '/session/' . $sessionID . '/prompt_async';
$promptCmd = 'curl -s -X POST ' . escapeshellarg($promptUrl)
. ' -H "Content-Type: application/json"'
. ' -d ' . escapeshellarg($promptJson)
. ' -o /dev/null -w "%{http_code}"';
$promptDescriptors = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'w')
);
$promptProc = proc_open($promptCmd, $promptDescriptors, $promptPipes);
if (is_resource($promptProc)) {
fclose($promptPipes[0]);
$httpCode = trim(stream_get_contents($promptPipes[1]));
fclose($promptPipes[1]);
fclose($promptPipes[2]);
proc_close($promptProc);
if ($httpCode !== '204' && $httpCode !== '200') {
echo "data: " . json_encode(array('error' => 'Failed to send prompt (HTTP ' . $httpCode . ')')) . "\n\n";
echo "data: [DONE]\n\n";
flush();
fclose($ssePipes[1]);
fclose($ssePipes[2]);
proc_close($sseProc);
exit;
}
} else {
echo "data: " . json_encode(array('error' => 'Failed to start prompt request')) . "\n\n";
echo "data: [DONE]\n\n";
flush();
fclose($ssePipes[1]);
fclose($ssePipes[2]);
proc_close($sseProc);
exit;
}
// 4. Read SSE events and forward text deltas to the frontend
$wordBuffer = '';
$done = false;
$assistantMsgID = '';
$sawAssistantText = false;
$sentTools = array(); // Track which tool parts we've already sent 'running' for (keyed by part ID)
$timeout = 120; // seconds
$startTime = time();
stream_set_timeout($ssePipes[1], 2);
while (!$done && (time() - $startTime) < $timeout) {
$line = fgets($ssePipes[1]);
if ($line === false) {
$status = proc_get_status($sseProc);
if (!$status['running']) {
break;
}
continue;
}
$line = trim($line);
// Skip empty lines and SSE comments
if ($line === '' || $line[0] === ':') {
continue;
}
if (strpos($line, 'data: ') !== 0) {
continue;
}
$data = substr($line, 6);
$event = json_decode($data, true);
if (!$event || !isset($event['type'])) {
continue;
}
$type = $event['type'];
$props = isset($event['properties']) ? $event['properties'] : array();
// Track the assistant message ID so we only forward its text parts
if ($type === 'message.updated') {
$info = isset($props['info']) ? $props['info'] : array();
if (isset($info['role']) && $info['role'] === 'assistant' &&
isset($info['sessionID']) && $info['sessionID'] === $sessionID) {
$assistantMsgID = $info['id'];
}
// Check for errors on the assistant message
if (isset($info['error']) && isset($info['id']) && $info['id'] === $assistantMsgID) {
$errMsg = 'AI error';
if (isset($info['error']['data']['message'])) {
$errMsg = $info['error']['data']['message'];
} elseif (isset($info['error']['name'])) {
$errMsg = $info['error']['name'];
}
echo "data: " . json_encode(array('error' => $errMsg)) . "\n\n";
flush();
$done = true;
}
}
// Forward text deltas and tool status from the assistant message only
if ($type === 'message.part.updated') {
$part = isset($props['part']) ? $props['part'] : null;
$delta = isset($props['delta']) ? $props['delta'] : null;
// Forward tool steps (just name + status), deduplicated by part ID
if ($part && isset($part['type']) && $part['type'] === 'tool' &&
isset($part['messageID']) && $part['messageID'] === $assistantMsgID) {
$partID = isset($part['id']) ? $part['id'] : '';
$toolName = isset($part['tool']) ? $part['tool'] : 'unknown';
$state = isset($part['state']) ? $part['state'] : array();
$toolStatus = isset($state['status']) ? $state['status'] : '';
$title = isset($state['title']) ? $state['title'] : '';
if ($title === '' && isset($state['input']) && isset($state['input']['description'])) {
$title = $state['input']['description'];
}
// Only send on meaningful status changes, and deduplicate 'running'
$shouldSend = false;
if ($toolStatus === 'running') {
if ($partID !== '' && !isset($sentTools[$partID])) {
$sentTools[$partID] = 'running';
$shouldSend = true;
} elseif ($partID === '') {
// No part ID available, fall back to sending
$shouldSend = true;
}
// If already sent 'running' for this partID, skip
} elseif ($toolStatus === 'completed' || $toolStatus === 'error') {
$shouldSend = true;
if ($partID !== '') {
$sentTools[$partID] = $toolStatus;
}
}
if ($shouldSend) {
$sawAssistantText = true;
// Flush any pending text buffer first
if ($wordBuffer !== '') {
echo "data: " . json_encode(array('text' => $wordBuffer)) . "\n\n";
flush();
$wordBuffer = '';
}
$toolEvent = array(
'tool' => $toolName,
'status' => $toolStatus,
'title' => $title
);
if ($partID !== '') {
$toolEvent['id'] = $partID;
}
echo "data: " . json_encode($toolEvent) . "\n\n";
flush();
}
}
if ($part && isset($part['type']) && $part['type'] === 'text' &&
isset($part['messageID']) && $part['messageID'] === $assistantMsgID) {
if ($delta !== null && $delta !== '') {
$sawAssistantText = true;
$wordBuffer .= $delta;
// Count complete words and flush every ~5
$trimmed = trim($wordBuffer);
if ($trimmed !== '') {
$endsWithSpace = preg_match('/\s$/', $wordBuffer);
$words = preg_split('/\s+/', $trimmed);
$completeWordCount = $endsWithSpace ? count($words) : count($words) - 1;
if ($completeWordCount >= 5) {
echo "data: " . json_encode(array('text' => $wordBuffer)) . "\n\n";
flush();
$wordBuffer = '';
}
}
}
// When a text part finishes, flush the buffer but do NOT stop --
// there may be more steps (tool calls followed by more text)
if (isset($part['time']) && isset($part['time']['end']) && $part['time']['end'] > 0) {
if ($wordBuffer !== '') {
echo "data: " . json_encode(array('text' => $wordBuffer)) . "\n\n";
flush();
$wordBuffer = '';
}
}
}
}
// Session error
if ($type === 'session.error') {
if (isset($props['sessionID']) && $props['sessionID'] === $sessionID) {
$errMsg = 'Session error';
if (isset($props['error']['data']['message'])) {
$errMsg = $props['error']['data']['message'];
} elseif (isset($props['error']['name'])) {
$errMsg = $props['error']['name'];
}
echo "data: " . json_encode(array('error' => $errMsg)) . "\n\n";
flush();
$done = true;
}
}
// Session idle = done (only after we've seen assistant text)
if ($type === 'session.idle' || $type === 'session.status') {
$matchSession = false;
if ($type === 'session.idle' && isset($props['sessionID']) && $props['sessionID'] === $sessionID) {
$matchSession = true;
}
if ($type === 'session.status' && isset($props['sessionID']) && $props['sessionID'] === $sessionID) {
$statusObj = isset($props['status']) ? $props['status'] : array();
$statusType = isset($statusObj['type']) ? $statusObj['type'] : '';
if ($statusType === 'idle') {
$matchSession = true;
}
}
if ($matchSession && $sawAssistantText) {
$done = true;
}
}
if (connection_aborted()) {
break;
}
}
// Flush remaining buffer
if ($wordBuffer !== '') {
echo "data: " . json_encode(array('text' => $wordBuffer)) . "\n\n";
flush();
}
echo "data: [DONE]\n\n";
flush();
// Cleanup SSE connection (but NOT the session -- keep it for history)
fclose($ssePipes[1]);
fclose($ssePipes[2]);
proc_close($sseProc);
?>