-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug_proxy.py
More file actions
67 lines (55 loc) · 2.28 KB
/
debug_proxy.py
File metadata and controls
67 lines (55 loc) · 2.28 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
import http.server
import http.client
import sys
# Configuration
LISTEN_PORT = 9999
TARGET_HOST = "127.0.0.1"
TARGET_PORT = 6006
class ProxyHandler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
# 1. Capture Request from OpenCode
content_len = int(self.headers.get('Content-Length', 0))
post_body = self.rfile.read(content_len)
print(f"\n{'='*20} 📤 REQUEST TO OLLAMA {'='*20}")
try:
print(post_body.decode('utf-8'))
except:
print("[Binary Request Data]")
# 2. Open Connection to Ollama
conn = http.client.HTTPConnection(TARGET_HOST, TARGET_PORT)
conn.request(self.command, self.path, post_body, headers=self.headers)
response = conn.getresponse()
# 3. Send Headers back to OpenCode IMMEDIATEY
self.send_response(response.status)
for key, value in response.getheaders():
# Filter out headers that might confuse the transfer encoding
if key.lower() not in ['content-length', 'transfer-encoding', 'connection']:
self.send_header(key, value)
self.send_header('Transfer-Encoding', 'chunked')
self.end_headers()
# 4. Stream the Body (Forward chunks instantly)
print(f"\n{'='*20} 📥 STREAMING RESPONSE {'='*20}")
while True:
# Read small chunks to support streaming
chunk = response.read(1024)
if not chunk:
break
# Print to Terminal (Decode if possible to see text)
try:
print(chunk.decode('utf-8', errors='ignore'), end='', flush=True)
except:
pass
# Forward to OpenCode
# (Write chunk size in hex + CRLF + chunk + CRLF)
self.wfile.write(f"{len(chunk):x}\r\n".encode())
self.wfile.write(chunk)
self.wfile.write(b"\r\n")
self.wfile.flush()
# End of stream
self.wfile.write(b"0\r\n\r\n")
conn.close()
print("\n[Stream Finished]")
def log_message(self, format, *args):
return # Disable default console spam
print(f"✅ Streaming Proxy running on port {LISTEN_PORT} -> {TARGET_HOST}:{TARGET_PORT}")
http.server.HTTPServer(('', LISTEN_PORT), ProxyHandler).serve_forever()