-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatomcode_proxy.py
More file actions
1245 lines (1030 loc) · 44.1 KB
/
Copy pathatomcode_proxy.py
File metadata and controls
1245 lines (1030 loc) · 44.1 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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
AtomCode Reverse Proxy — OpenAI-compatible proxy via AtomCode Daemon
Architecture:
┌──────────────┐ OpenAI API calls ┌──────────────────┐ POST /chat ┌────────────┐
│ Any AI Tool │ ───────────────────────▶ │ Proxy Server │ ──────────────▶ │ Daemon │
│ (Cline/Codex)│ ◀─────────────────────── │ (:8080/v1) │ ◀────────────── │ :13456 │
└──────────────┘ └──────────────────┘ └────────────┘
Usage:
1. Start the proxy (auto-manages daemon):
python3 atomcode_proxy.py start
2. Or manually:
ATOMCODE_TELEMETRY=0 atomcode daemon
python3 atomcode_proxy.py serve --port 8080
3. Configure your AI tool:
API Base URL: http://localhost:8080/v1
API Key: anything (not validated)
Model: deepseek-v4-flash
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import logging
import os
import pathlib
import platform
import re
import shutil
import signal
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, AsyncGenerator, Dict, List, Optional
import yaml
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, Field
try:
import aiohttp
except ImportError:
aiohttp = None # type: ignore
# ─── Logging ──────────────────────────────────────────────────────────────────
logger = logging.getLogger("atomcode-proxy")
# ─── Configuration ─────────────────────────────────────────────────────────────
DEFAULT_CONFIG = {
"server": {"host": "0.0.0.0", "port": 8080},
"daemon": {
"url": os.environ.get("ATOMCODE_DAEMON_URL", "http://localhost:13456"),
"binary_path": None, # auto-detect
"auto_manage": False, # proxy manages daemon lifecycle
"telemetry": False, # ATOMCODE_TELEMETRY=0
},
"logging": {"level": "INFO", "file": None},
"sessions": {"max_age_minutes": 30},
"setup": {
"auto_login": True, # attempt OAuth login if not logged in
"auto_claim": True, # attempt CodingPlan claim if needed
},
}
CONFIG_SEARCH_PATHS = [
pathlib.Path("proxy.yaml"),
pathlib.Path("~/.atomcode/proxy.yaml").expanduser(),
pathlib.Path("/etc/atomcode/proxy.yaml"),
]
def find_atomcode_binary() -> str:
candidates = [
shutil.which("atomcode"),
"/usr/local/bin/atomcode",
os.path.expanduser("~/.local/bin/atomcode"),
]
for c in candidates:
if c:
return c
raise FileNotFoundError(
"atomcode binary not found. Install it with:\n"
" curl -fsSL https://raw.atomgit.com/atomgit_atomcode/atomcode/raw/main/scripts/install.sh | sh"
)
def load_config() -> dict:
config = dict(DEFAULT_CONFIG)
# Load from first existing search path
for p in CONFIG_SEARCH_PATHS:
resolved = p.expanduser().resolve() if hasattr(p, "expanduser") else pathlib.Path(p).expanduser().resolve()
if resolved.exists():
with open(resolved) as f:
loaded = yaml.safe_load(f) or {}
_deep_merge(config, loaded)
logger.info("Loaded config from %s", resolved)
break
# Auto-detect binary path
if config["daemon"]["binary_path"] is None:
try:
config["daemon"]["binary_path"] = find_atomcode_binary()
except FileNotFoundError:
config["daemon"]["binary_path"] = "atomcode"
# Env overrides
config["daemon"]["url"] = os.environ.get("ATOMCODE_DAEMON_URL", config["daemon"]["url"])
if "ATOMCODE_TELEMETRY" in os.environ:
config["daemon"]["telemetry"] = os.environ["ATOMCODE_TELEMETRY"] == "0"
return config
def _deep_merge(base: dict, overlay: dict) -> None:
"""Recursively merge overlay into base dict."""
for k, v in overlay.items():
if k in base and isinstance(base[k], dict) and isinstance(v, dict):
_deep_merge(base[k], v)
else:
base[k] = v
@dataclass
class AppState:
config: dict = field(default_factory=load_config)
daemon_proc: Optional[subprocess.Popen] = None
daemon_running: bool = False
daemon_fail_count: int = 0
start_time: float = field(default_factory=time.time)
sessions: Dict[str, str] = field(default_factory=dict) # conv_hash → daemon_session_id
session_times: Dict[str, float] = field(default_factory=dict) # conv_hash → last used timestamp
# ─── Pydantic Models (OpenAI-Compatible) ──────────────────────────────────────
class Message(BaseModel):
role: str = "user"
content: Any = "" # str or List[dict] (multi-part)
class ChatCompletionRequest(BaseModel):
model: Optional[str] = None
messages: List[Message] = Field(default_factory=list)
stream: bool = False
temperature: Optional[float] = None
max_tokens: Optional[int] = None
top_p: Optional[float] = None
frequency_penalty: Optional[float] = None
presence_penalty: Optional[float] = None
stop: Any = None
user: Optional[str] = None
class ChatUsage(BaseModel):
prompt_tokens: int = 0
completion_tokens: int = 0
total_tokens: int = 0
class ChatChoice(BaseModel):
index: int = 0
message: dict = Field(default_factory=lambda: {"role": "assistant", "content": ""})
finish_reason: Optional[str] = None
class ChatCompletionResponse(BaseModel):
id: str = "chatcmpl-atomcode"
object: str = "chat.completion"
created: int = Field(default_factory=lambda: int(time.time()))
model: str = "unknown"
choices: List[ChatChoice] = Field(default_factory=list)
usage: Optional[ChatUsage] = None
# ─── SSE Translation ──────────────────────────────────────────────────────────
def _translate_daemon_event(event: dict, model: str, tool_call_index: int) -> Optional[dict]:
"""
Translate a daemon SSE event dict into an OpenAI SSE chunk dict.
Returns None if the event should be skipped (no translation).
Tracks tool_call_index to assign sequential tool call IDs.
"""
etype = event.get("type")
if etype == "text":
return {
"choices": [{"delta": {"content": event.get("content", "")}, "index": 0}],
}
elif etype == "reasoning":
return {
"choices": [{"delta": {"reasoning_content": event.get("content", "")}, "index": 0}],
}
elif etype == "tool_start":
tid = event.get("id", f"call_{tool_call_index}")
name = event.get("name", "")
args_text = event.get("arguments", "{}")
return {
"choices": [{
"delta": {
"tool_calls": [{
"index": 0,
"id": tid,
"type": "function",
"function": {"name": name, "arguments": args_text},
}]
},
"index": 0,
}],
}
elif etype == "tool_output":
# Intermediate progress — skip in OpenAI format
return None
elif etype == "tool_result":
# Final tool result — skip in streaming (folded into next assistant response)
return None
elif etype == "tokens":
pt = event.get("prompt", 0)
ct = event.get("completion", 0)
tt = event.get("total", 0)
return {
"choices": [],
"usage": {"prompt_tokens": pt, "completion_tokens": ct, "total_tokens": tt},
}
elif etype == "done":
return {"type": "done", "session_id": event.get("session_id")}
elif etype == "error":
return {
"choices": [{"delta": {}, "finish_reason": "error", "index": 0}],
}
elif etype == "stopped":
return {"type": "done"}
return None
def _build_openai_chunk(base: dict, model: str | None) -> dict:
"""Wrap a delta dict into a full OpenAI SSE chunk."""
chunk = {
"id": "chatcmpl-atomcode",
"object": "chat.completion.chunk",
"created": int(time.time()),
"model": model or "unknown",
}
chunk.update(base)
return chunk
# ─── Daemon Client ────────────────────────────────────────────────────────────
class DaemonClient:
"""Async HTTP client for the AtomCode daemon REST API."""
def __init__(self, base_url: str):
self.base_url = base_url.rstrip("/")
self._http_timeout = 120
# ── Sync helpers (for simple request/response) ──
def _sync_request(self, method: str, path: str, body: Any = None) -> tuple[int, Any]:
url = f"{self.base_url}{path}"
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/json")
try:
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.status, json.loads(resp.read())
except urllib.error.HTTPError as e:
body_text = e.read().decode()
try:
return e.code, json.loads(body_text)
except json.JSONDecodeError:
return e.code, {"error": body_text}
except urllib.error.URLError as e:
return 503, {"error": f"Daemon unreachable: {e.reason}"}
def health(self) -> dict:
_, data = self._sync_request("GET", "/health")
return data
def auth_status(self) -> dict:
_, data = self._sync_request("GET", "/auth/status")
return data
def login_start(self) -> dict:
_, data = self._sync_request("POST", "/auth/login/start", {"open_browser": False})
return data
def login_poll(self, login_id: str) -> dict:
_, data = self._sync_request("POST", f"/auth/login/{login_id}/poll", {})
return data
def codingplan_setup(self) -> dict:
_, data = self._sync_request("POST", "/codingplan/setup", {})
return data
def models_list(self) -> list:
_, data = self._sync_request("GET", "/models")
return data if isinstance(data, list) else []
def providers_list(self) -> dict:
_, data = self._sync_request("GET", "/providers")
return data if isinstance(data, dict) else {}
# ── Async SSE chat stream ──
async def chat_stream(self, message: str, stream: bool = True,
provider: str | None = None, system: str | None = None,
session_id: str | None = None
) -> AsyncGenerator[dict, None]:
"""
POST /chat to daemon, yield parsed SSE event dicts asynchronously.
Uses aiohttp if available, falls back to sync thread.
Pass session_id to continue an existing conversation context.
"""
body: dict = {"message": message, "stream": stream}
if provider:
body["provider"] = provider
if system:
body["system"] = system
if session_id:
body["session_id"] = session_id
url = f"{self.base_url}/chat"
headers = {"Content-Type": "application/json", "Accept": "text/event-stream"}
if aiohttp is not None:
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self._http_timeout)) as session:
async with session.post(url, json=body, headers=headers) as resp:
async for raw_line in resp.content:
line = raw_line.decode("utf-8", errors="replace").strip()
if not line:
continue
if line.startswith("data: "):
data_str = line[6:]
if data_str == "[DONE]":
yield {"type": "done"}
return
try:
yield json.loads(data_str)
except json.JSONDecodeError:
pass
else:
# Fallback: sync request in thread pool
loop = asyncio.get_event_loop()
data = json.dumps(body).encode()
req = urllib.request.Request(url, data=data, method="POST")
for k, v in headers.items():
req.add_header(k, v)
def _read_sse():
resp = urllib.request.urlopen(req, timeout=self._http_timeout)
for raw_line in resp:
line = raw_line.decode("utf-8", errors="replace").strip()
yield line
lines = await loop.run_in_executor(None, _read_sse)
for line in lines:
if not line:
continue
if line.startswith("data: "):
data_str = line[6:]
if data_str == "[DONE]":
yield {"type": "done"}
return
try:
yield json.loads(data_str)
except json.JSONDecodeError:
pass
# ─── Daemon Process Manager ──────────────────────────────────────────────────
class DaemonManager:
"""Manages the AtomCode daemon subprocess lifecycle."""
def __init__(self, config: dict):
self.config = config
self._proc: Optional[subprocess.Popen] = None
self._daemon_url = config["daemon"]["url"]
self._binary = config["daemon"]["binary_path"]
self._telemetry = config["daemon"].get("telemetry", True)
@property
def running(self) -> bool:
if self._proc is None:
return False
poll = self._proc.poll()
return poll is None
def start(self) -> bool:
if self.running:
logger.info("Daemon already running (PID %d)", self._proc.pid)
return True
logger.info("Starting AtomCode daemon...")
env = os.environ.copy()
if not self._telemetry:
env["ATOMCODE_TELEMETRY"] = "0"
log_path = self.config["logging"].get("file")
stdout = stderr = None
if log_path:
stdout = open(log_path, "a")
stderr = subprocess.STDOUT
try:
self._proc = subprocess.Popen(
[self._binary, "daemon"],
env=env,
stdout=stdout,
stderr=stderr,
stdin=subprocess.DEVNULL,
)
logger.info("Daemon started (PID %d)", self._proc.pid)
# Wait for readiness
for i in range(15):
if self._check_health():
logger.info("Daemon ready after %ds", i + 1)
return True
time.sleep(1)
logger.error("Daemon failed to become ready within 15s")
self.stop()
return False
except FileNotFoundError:
logger.error("Daemon binary not found: %s", self._binary)
return False
def stop(self) -> bool:
if self._proc is None:
return True
logger.info("Stopping daemon (PID %d)...", self._proc.pid)
try:
self._proc.terminate()
self._proc.wait(timeout=10)
except subprocess.TimeoutExpired:
logger.warning("Daemon did not terminate, killing...")
self._proc.kill()
self._proc.wait(timeout=5)
except Exception as e:
logger.error("Error stopping daemon: %s", e)
return False
self._proc = None
logger.info("Daemon stopped")
return True
def restart(self) -> bool:
self.stop()
time.sleep(1)
return self.start()
def _check_health(self) -> bool:
try:
data = json.loads(urllib.request.urlopen(
urllib.request.Request(f"{self._daemon_url}/health"),
timeout=3,
).read())
return data.get("status") == "ok"
except Exception:
return False
# ─── Session Helper ──────────────────────────────────────────────────────────
def _conversation_key(messages: List[dict], system: str = "") -> str:
"""
Generate a deterministic hash for a conversation prefix.
Includes all messages except the last user message, plus system prompt.
Used to identify the same conversation context across proxy restarts.
"""
payload = system
for m in messages[:-1]:
role = m.get("role", "")
content = str(m.get("content", ""))
payload += f"|{role}:{content}"
return hashlib.md5(payload.encode()).hexdigest()[:16]
def _format_messages_for_daemon(messages: List[dict], system_prompt: str) -> str:
"""
Format the full messages history into a single message string
for the daemon's /chat endpoint.
"""
parts = []
for m in messages:
role = m.get("role", "user")
content = m.get("content", "")
if isinstance(content, list):
# Multi-part content: extract text parts
texts = [p.get("text", "") for p in content if isinstance(p, dict) and p.get("type") == "text"]
content = "\n".join(texts)
if role == "system":
continue # system is handled separately
if not content:
continue
role_label = {"user": "User", "assistant": "Assistant", "tool": "Tool"}.get(role, role.capitalize())
parts.append(f"{role_label}: {content}")
msg = "\n\n".join(parts) if parts else messages[-1].get("content", "")
return msg
# ─── FastAPI App ──────────────────────────────────────────────────────────────
def create_app(config: dict) -> FastAPI:
app = FastAPI(
title="AtomCode Reverse Proxy",
version="2.0.0",
docs_url=None, # disable docs in production
redoc_url=None,
)
daemon_client = DaemonClient(config["daemon"]["url"])
daemon_mgr = DaemonManager(config)
app.state.config = config
app.state.daemon_client = daemon_client
app.state.daemon_mgr = daemon_mgr
app.state.start_time = time.time()
app.state.sessions: Dict[str, str] = {}
app.state.session_times: Dict[str, float] = {}
app.state.daemon_fail_count = 0
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ── Events ──
@app.on_event("startup")
async def startup():
# Start daemon if auto_manage is enabled
if config["daemon"].get("auto_manage", False):
daemon_mgr.start()
# Start health monitor background task
asyncio.create_task(_health_monitor())
@app.on_event("shutdown")
async def shutdown():
if config["daemon"].get("auto_manage", False):
daemon_mgr.stop()
async def _health_monitor():
"""Periodically check daemon health and attempt recovery."""
while True:
await asyncio.sleep(15)
try:
h = daemon_client.health()
if h.get("status") == "ok":
app.state.daemon_fail_count = 0
app.state.daemon_running = True
else:
app.state.daemon_fail_count += 1
except Exception:
app.state.daemon_fail_count += 1
app.state.daemon_running = False
# Auto-recovery after 3 consecutive failures
if app.state.daemon_fail_count >= 3 and config["daemon"].get("auto_manage", False):
logger.warning("Daemon unreachable, attempting restart...")
daemon_mgr.restart()
app.state.daemon_fail_count = 0
# ── Helpers ──
async def _check_daemon_ready() -> bool:
"""Verify daemon is running and logged in. Returns True if OK."""
try:
h = daemon_client.health()
if h.get("status") != "ok":
raise HTTPException(status_code=502, detail={
"error": {"message": f"Daemon not ready: {h}", "code": 502}
})
app.state.daemon_running = True
app.state.daemon_fail_count = 0
auth = daemon_client.auth_status()
if not auth.get("logged_in"):
raise HTTPException(status_code=502, detail={
"error": {
"message": "Daemon running but not logged in. Run: python3 atomcode_proxy.py login",
"code": 502,
}
})
return True
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=502, detail={
"error": {"message": f"Daemon unreachable at {config['daemon']['url']}: {e}", "code": 502}
})
# ── Endpoints ──
@app.options("/v1/{path:path}")
async def options_handler(path: str):
return JSONResponse(status_code=204, headers={
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
})
@app.get("/v1/health")
async def health():
try:
h = daemon_client.health()
auth = daemon_client.auth_status()
daemon_ok = h.get("status") == "ok"
logged_in = auth.get("logged_in", False)
except Exception as e:
daemon_ok = False
logged_in = False
h = {"error": str(e)}
auth = {}
return {
"status": "ok",
"uptime_seconds": int(time.time() - app.state.start_time),
"daemon": {
"connected": daemon_ok,
"version": h.get("version", "?"),
"service": h.get("service", "?"),
},
"logged_in": logged_in,
"user": auth.get("user"),
}
@app.get("/v1/models")
async def list_models():
try:
models = daemon_client.models_list()
except Exception as e:
raise HTTPException(status_code=502, detail={
"error": {"message": f"Failed to fetch models: {e}", "code": 502}
})
return {
"object": "list",
"data": [
{
"id": m.get("model", m.get("name", "unknown")),
"object": "model",
"created": int(time.time()),
"owned_by": "atomcode",
}
for m in models
],
}
@app.post("/v1/chat/completions")
async def chat_completions(req: ChatCompletionRequest, request: Request):
await _check_daemon_ready()
messages = [m.model_dump() if hasattr(m, 'model_dump') else dict(m) for m in req.messages]
model = req.model or ""
stream = req.stream
# 1. Extract system prompt
system_prompt = ""
remaining = []
for m in messages:
if m.get("role") == "system":
system_prompt = str(m.get("content", ""))
else:
remaining.append(m)
messages = remaining
if not messages:
raise HTTPException(status_code=400, detail={
"error": {"message": "No user/assistant messages found", "code": 400}
})
# 2. Determine provider from model name
provider = None
if model:
try:
providers_data = daemon_client.providers_list()
provider_list = providers_data.get("providers", []) if isinstance(providers_data, dict) else providers_data or []
for p in provider_list:
if isinstance(p, dict) and p.get("model", "").lower() == model.lower():
provider = p.get("name")
break
except Exception:
pass
# 3. Format messages into daemon message string
daemon_message = _format_messages_for_daemon(messages, system_prompt)
# 4. Session tracking — reuse daemon session_id for multi-turn context
conv_key = _conversation_key(messages, system_prompt)
daemon_session_id = app.state.sessions.get(conv_key)
now = time.time()
app.state.session_times[conv_key] = now
# Clean expired sessions
max_age = config["sessions"]["max_age_minutes"] * 60
expired_keys = [k for k, v in app.state.session_times.items() if now - v > max_age]
for k in expired_keys:
app.state.sessions.pop(k, None)
app.state.session_times.pop(k, None)
logger.info("Chat: model=%s, stream=%s, provider=%s, msgs=%d, sys=%s, sid=%s",
model, stream, provider, len(messages), bool(system_prompt),
daemon_session_id or "(new)")
# ── Non-streaming ──
if not stream:
full_text = ""
usage_data = ChatUsage()
tool_calls: list = []
new_session_id = daemon_session_id
try:
async for event in daemon_client.chat_stream(
message=daemon_message, stream=True, provider=provider,
system=system_prompt, session_id=daemon_session_id
):
etype = event.get("type")
if etype == "text":
full_text += event.get("content", "")
elif etype == "reasoning":
pass # skip reasoning in non-streaming
elif etype == "tool_start":
tool_calls.append({
"id": event.get("id", ""),
"type": "function",
"function": {
"name": event.get("name", ""),
"arguments": event.get("arguments", "{}"),
},
})
elif etype == "tokens":
usage_data = ChatUsage(
prompt_tokens=event.get("prompt", 0),
completion_tokens=event.get("completion", 0),
total_tokens=event.get("total", 0),
)
elif etype == "done":
new_session_id = event.get("session_id") or new_session_id
break
elif etype == "error":
raise HTTPException(status_code=502, detail={
"error": {"message": event.get("message", "Daemon error"), "code": 502}
})
except HTTPException:
raise
except Exception as e:
logger.error("Chat error: %s", e, exc_info=True)
raise HTTPException(status_code=502, detail={
"error": {"message": f"Daemon error: {e}", "code": 502}
})
message: dict = {"role": "assistant", "content": full_text}
if tool_calls:
message["tool_calls"] = tool_calls
finish_reason = "tool_calls"
else:
finish_reason = "stop"
# Persist session_id for multi-turn continuity
if new_session_id and new_session_id != daemon_session_id:
app.state.sessions[conv_key] = new_session_id
return ChatCompletionResponse(
model=model or "unknown",
choices=[ChatChoice(
message=message,
finish_reason=finish_reason,
)],
usage=usage_data if usage_data.total_tokens > 0 else None,
)
# ── Streaming ──
else:
async def event_stream():
tool_idx = 0
current_session_id = daemon_session_id
try:
async for event in daemon_client.chat_stream(
message=daemon_message, stream=True, provider=provider,
system=system_prompt, session_id=daemon_session_id
):
# Internal control events
if event.get("type") == "done":
current_session_id = event.get("session_id") or current_session_id
yield f"data: [DONE]\n\n"
# Persist session_id for multi-turn
if current_session_id and current_session_id != daemon_session_id:
app.state.sessions[conv_key] = current_session_id
return
translated = _translate_daemon_event(event, model or "unknown", tool_idx)
if translated is None:
continue
if translated.get("type") == "done":
yield f"data: [DONE]\n\n"
return
if "choices" in translated and translated["choices"]:
for c in translated["choices"]:
if "tool_calls" in c.get("delta", {}):
tool_idx += 1
chunk = _build_openai_chunk(translated, model)
yield f"data: {json.dumps(chunk)}\n\n"
yield f"data: [DONE]\n\n"
except HTTPException:
raise
except Exception as e:
logger.error("Stream error: %s", e)
yield f"data: {json.dumps({'error': str(e)})}\n\n"
return StreamingResponse(
event_stream(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
"Access-Control-Allow-Origin": "*",
},
)
return app
# ─── CLI ──────────────────────────────────────────────────────────────────────
def load_config_for_cli() -> dict:
try:
return load_config()
except Exception:
return dict(DEFAULT_CONFIG)
def cmd_serve(args: argparse.Namespace):
"""Start the proxy server only (no daemon management)."""
config = load_config_for_cli()
if args.port:
config["server"]["port"] = args.port
if args.host:
config["server"]["host"] = args.host
# Setup logging
log_level = getattr(logging, config["logging"].get("level", "INFO").upper(), logging.INFO)
log_file = config["logging"].get("file")
logging.basicConfig(level=log_level, format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%H:%M:%S")
host = config["server"]["host"]
port = config["server"]["port"]
logger.info("=" * 60)
logger.info("AtomCode Reverse Proxy v2.0.0")
logger.info("Listening on http://%s:%d", host, port)
logger.info("OpenAI endpoint: http://localhost:%d/v1", port)
logger.info("Daemon: %s", config["daemon"]["url"])
logger.info("Daemon auto-manage: %s", config["daemon"].get("auto_manage", False))
logger.info("=" * 60)
app = create_app(config)
import uvicorn
uvicorn.run(app, host=host, port=port, log_level=config["logging"].get("level", "info").lower())
def cmd_start(args: argparse.Namespace):
"""Start daemon + proxy together."""
config = load_config_for_cli()
if args.port:
config["server"]["port"] = args.port
log_level = getattr(logging, config["logging"].get("level", "INFO").upper(), logging.INFO)
logging.basicConfig(level=log_level, format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%H:%M:%S")
# Ensure auto_manage is enabled
config["daemon"]["auto_manage"] = True
host = config["server"]["host"]
port = config["server"]["port"]
logger.info("=" * 60)
logger.info("AtomCode Reverse Proxy v2.0.0 — START")
logger.info("=" * 60)
# Start daemon
mgr = DaemonManager(config)
if not mgr.start():
logger.error("Failed to start daemon. Aborting.")
sys.exit(1)
# Check login / attempt auto-login
client = DaemonClient(config["daemon"]["url"])
try:
auth = client.auth_status()
if not auth.get("logged_in"):
logger.warning("Not logged in.")
if config.get("setup", {}).get("auto_login", True):
logger.info("Attempting auto-login...")
_run_auto_login(client, config)
except Exception as e:
logger.warning("Cannot check auth: %s", e)
# Start proxy (in same process via uvicorn)
logger.info("Starting proxy on http://%s:%d", host, port)
logger.info("Daemon: %s", config["daemon"]["url"])
logger.info("=" * 60)
app = create_app(config)
import uvicorn
try:
uvicorn.run(app, host=host, port=port, log_level=config["logging"].get("level", "info").lower())
except KeyboardInterrupt:
logger.info("Shutting down...")
finally:
mgr.stop()
def cmd_stop(args: argparse.Namespace):
"""Stop daemon (and proxy if running via start)."""
config = load_config_for_cli()
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%H:%M:%S")
mgr = DaemonManager(config)
mgr.stop()
logger.info("Stopped.")
def cmd_restart(args: argparse.Namespace):
"""Restart daemon + proxy."""
cmd_stop(args)
time.sleep(1)
cmd_start(args)
def cmd_status(args: argparse.Namespace):
"""Show daemon and proxy status."""
config = load_config_for_cli()
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%H:%M:%S")
daemon_url = config["daemon"]["url"]
client = DaemonClient(daemon_url)
logger.info("AtomCode Reverse Proxy — Status")
logger.info("=" * 60)
# Daemon health
try:
h = client.health()
logger.info("Daemon: ✅ %s (v%s)", h.get("status", "?"), h.get("version", "?"))
except Exception as e:
logger.info("Daemon: ❌ unreachable (%s)", e)
# Auth status