-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1833 lines (1552 loc) · 66.4 KB
/
server.py
File metadata and controls
1833 lines (1552 loc) · 66.4 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
"""
OpenChiken Web Server
─────────────────────
FastAPI — 로컬 전용 온보딩(/setup) · 관리 UI(local_ui/) + /static 자산
uv run python server.py
공개 랜딩(landing/)은 별도 도메인 정적 배포. 이 서버 루트(/)는 온보딩으로 연결됩니다.
"""
from __future__ import annotations
import json
import logging
import os
import sqlite3
import subprocess
import sys
import time
import urllib.parse
import urllib.request
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
from pathlib import Path
from fastapi import FastAPI, HTTPException, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
logger = logging.getLogger(__name__)
KST = timezone(timedelta(hours=9))
# ── 릴레이 송신 활동 인메모리 로그 (최대 200건) ──────────────────────────────
_relay_activity_log: list[dict] = []
# ── 경로 설정 ──────────────────────────────────────────────────
ROOT = Path(__file__).parent
STATIC_DIR = ROOT / "static"
LOCAL_UI_DIR = ROOT / "local_ui"
OPENCHIKEN_HOME = Path.home() / ".openchiken"
ENV_FILE = OPENCHIKEN_HOME / ".env"
CREDENTIALS_DST = OPENCHIKEN_HOME / "credentials.json"
# main.py 서브프로세스 핸들 (단일 인스턴스 관리)
_main_proc: subprocess.Popen | None = None
def _db_path() -> str:
"""DB 파일 절대 경로. settings.database_url이 환경별 절대 경로를 반환."""
from config.settings import settings
return settings.database_url.replace("sqlite:///", "")
def _init_db() -> None:
"""서버 시작 시 DB 테이블이 없으면 생성 (main.py 없이 web만 실행할 때도 동작)."""
try:
db_path = _db_path()
with sqlite3.connect(db_path) as conn:
conn.executescript("""
CREATE TABLE IF NOT EXISTS message_store (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
message TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS memo_store (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT UNIQUE NOT NULL,
content TEXT,
created_at TEXT,
updated_at TEXT
);
CREATE TABLE IF NOT EXISTS task_store (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
description TEXT DEFAULT '',
status TEXT DEFAULT 'pending',
result TEXT DEFAULT '',
created_at TEXT,
updated_at TEXT
);
""")
logger.info("DB 테이블 초기화 완료: %s", db_path)
except Exception as e:
logger.warning("DB 초기화 실패 (온보딩 전 정상): %s", e)
def _try_start_main() -> None:
"""main.py를 백그라운드 서브프로세스로 실행. 이미 실행 중이면 스킵."""
global _main_proc
if _main_proc is not None and _main_proc.poll() is None:
return
try:
_main_proc = subprocess.Popen(
["uv", "run", "python", "main.py"],
cwd=str(ROOT),
stdout=open(ROOT / "openchiken.log", "a", encoding="utf-8"),
stderr=subprocess.STDOUT,
)
logger.info("main.py 자동 시작 완료 (pid=%d)", _main_proc.pid)
except FileNotFoundError:
_main_proc = subprocess.Popen(
[sys.executable, "main.py"],
cwd=str(ROOT),
stdout=open(ROOT / "openchiken.log", "a", encoding="utf-8"),
stderr=subprocess.STDOUT,
)
logger.info("main.py 자동 시작 완료 (pid=%d)", _main_proc.pid)
except Exception as e:
logger.warning("main.py 자동 시작 실패: %s", e)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""서버 시작 시 DB 초기화 후, 온보딩 완료 상태면 main.py 자동 구동."""
_init_db()
if ENV_FILE.exists():
logger.info("온보딩 완료 상태 확인 — main.py 자동 시작")
_try_start_main()
else:
logger.info("온보딩 미완료 — main.py 자동 시작 건너뜀")
yield
app = FastAPI(title="OpenChiken Web Server", docs_url=None, redoc_url=None, lifespan=lifespan) # v2.0
# Chrome Extension (chrome-extension://*) 및 localhost UI 허용
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["*"],
)
# ── Pydantic 모델 ──────────────────────────────────────────────
class SetupConfig(BaseModel):
# Step 1 — Persona
ASSISTANT_NAME: str = "치킨"
ASSISTANT_TONE: str = ""
ASSISTANT_PERSONA: str = ""
ASSISTANT_EXTRA: str = ""
# Step 2 — LLM
LLM_PROVIDER: str = "openai"
OPENAI_API_KEY: str = ""
OPENAI_MODEL: str = "gpt-4o"
ANTHROPIC_API_KEY: str = ""
ANTHROPIC_MODEL: str = "claude-3-5-sonnet-latest"
GEMINI_API_KEY: str = ""
GEMINI_MODEL: str = "gemini-2.0-flash"
OLLAMA_BASE_URL: str = "http://localhost:11434"
OLLAMA_MODEL: str = "llama3.2"
# Step 3 — Telegram
TELEGRAM_BOT_TOKEN: str = ""
ALLOWED_USER_IDS: str = ""
# Step 5 — Database
DATABASE_URL: str = "sqlite:///openchiken.db"
# Step 6 — Scheduler
MORNING_BRIEFING_HOUR: str = "8"
REMINDER_MINUTES_BEFORE: str = "15"
# Step 7 — Skills (all | comma-separated skill ids)
ENABLED_SKILLS: str = "all"
# Step 8 — Channels
SLACK_BOT_TOKEN: str = ""
SLACK_APP_TOKEN: str = ""
DISCORD_BOT_TOKEN: str = ""
IMESSAGE_ALLOWED_HANDLES: str = ""
IMESSAGE_POLL_INTERVAL: str = "3"
ENABLED_CHANNELS: str = "telegram"
# ── API 라우터 ─────────────────────────────────────────────────
# ── Browser Channel (Chrome Extension) ────────────────────────
class ChatRequest(BaseModel):
message: str
session_id: str = "extension"
class ChatResponse(BaseModel):
ok: bool
reply: str = ""
error: str = ""
class RelayActivityEntry(BaseModel):
direction: str # "sent" | "received"
agentId: str
skill: str
status: str # "approved" | "rejected" | "error"
summary: str = ""
@app.post("/api/chat", response_model=ChatResponse)
async def api_chat(req: ChatRequest):
"""Chrome Extension 등 브라우저 채널에서 에이전트에게 메시지를 전송합니다.
Telegram과 동일하게 router.route_message()를 경유하여
오케스트레이터(스킬 플래닝 → 허브 설치 → Plan-and-Execute)를 사용합니다.
"""
try:
from channels.router import route_message, parse_command, InboundEvent
command, args = parse_command(req.message)
event = InboundEvent(
channel="extension",
session_id=req.session_id,
user_id="extension",
text=req.message,
command=command,
args=args,
)
reply = await route_message(event)
return ChatResponse(ok=True, reply=reply)
except EnvironmentError as e:
raise HTTPException(
status_code=503,
detail=f"LLM 공급자 설정이 필요합니다: {e}",
)
except Exception as e:
logger.error("api_chat failed: %s", e, exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/chat/history")
def api_chat_history(session_id: str = "extension", limit: int = 20):
"""브라우저 채널 대화 기록 조회."""
try:
conn = sqlite3.connect(_db_path())
cursor = conn.cursor()
cursor.execute(
"SELECT id, message FROM message_store "
"WHERE session_id = ? ORDER BY id DESC LIMIT ?",
(session_id, limit),
)
rows = cursor.fetchall()
conn.close()
messages = []
for row_id, msg_json in reversed(rows):
try:
data = json.loads(msg_json)
content = data.get("data", {}).get("content", "")
msg_type = data.get("type", "")
if content.strip():
messages.append({"id": row_id, "type": msg_type, "content": content})
except (json.JSONDecodeError, KeyError):
continue
return {"ok": True, "messages": messages}
except Exception as e:
logger.warning("api_chat_history failed: %s", e)
return {"ok": False, "messages": [], "error": str(e)}
@app.get("/")
def root_redirect():
"""셋업 완료(.env 존재) 시 대시보드로, 미완료 시 온보딩으로 이동."""
if ENV_FILE.exists():
return RedirectResponse(url="/dashboard.html", status_code=302)
return RedirectResponse(url="/setup.html", status_code=302)
@app.get("/api/setup/status")
def get_setup_status():
"""셋업 완료 여부 확인"""
env_exists = ENV_FILE.exists()
credentials_exists = CREDENTIALS_DST.exists() or (ROOT / "credentials.json").exists()
return {
"completed": env_exists,
"env_file": str(ENV_FILE),
"has_credentials": credentials_exists,
}
@app.post("/api/setup/save")
def save_setup(config: SetupConfig):
"""설정을 .env 파일로 저장"""
try:
OPENCHIKEN_HOME.mkdir(parents=True, exist_ok=True)
except OSError as e:
raise HTTPException(status_code=500, detail=f"홈 디렉토리 생성 실패: {e}")
def keep(new: str, env_key: str) -> str:
"""빈 값이면 기존 환경변수를 유지 (API 키 보호)."""
return new if new else os.getenv(env_key, "")
lines = [
"# OpenChiken 환경 설정 – web setup wizard 로 생성됨",
f"# {time.strftime('%Y-%m-%d %H:%M:%S')}",
"",
"# ── Persona ──────────────────────────────",
f"ASSISTANT_NAME={config.ASSISTANT_NAME}",
f"ASSISTANT_TONE={config.ASSISTANT_TONE}",
f"ASSISTANT_PERSONA={config.ASSISTANT_PERSONA}",
f"ASSISTANT_EXTRA={config.ASSISTANT_EXTRA}",
"",
"# ── LLM ─────────────────────────────────",
f"LLM_PROVIDER={config.LLM_PROVIDER}",
f"OPENAI_API_KEY={keep(config.OPENAI_API_KEY, 'OPENAI_API_KEY')}",
f"OPENAI_MODEL={config.OPENAI_MODEL}",
f"ANTHROPIC_API_KEY={keep(config.ANTHROPIC_API_KEY, 'ANTHROPIC_API_KEY')}",
f"ANTHROPIC_MODEL={config.ANTHROPIC_MODEL}",
f"GEMINI_API_KEY={keep(config.GEMINI_API_KEY, 'GEMINI_API_KEY')}",
f"GEMINI_MODEL={config.GEMINI_MODEL}",
f"OLLAMA_BASE_URL={config.OLLAMA_BASE_URL}",
f"OLLAMA_MODEL={config.OLLAMA_MODEL}",
"",
"# ── Telegram ─────────────────────────────",
f"TELEGRAM_BOT_TOKEN={keep(config.TELEGRAM_BOT_TOKEN, 'TELEGRAM_BOT_TOKEN')}",
"",
"# ── 허용 사용자 (전 채널 공통: Telegram · Discord · Slack) ──",
f"ALLOWED_USER_IDS={config.ALLOWED_USER_IDS}",
"",
"# ── Database ─────────────────────────────",
f"DATABASE_URL={config.DATABASE_URL}",
"",
"# ── Scheduler ────────────────────────────",
f"MORNING_BRIEFING_HOUR={config.MORNING_BRIEFING_HOUR}",
f"REMINDER_MINUTES_BEFORE={config.REMINDER_MINUTES_BEFORE}",
"",
"# ── Skills ───────────────────────────────",
f"ENABLED_SKILLS={config.ENABLED_SKILLS}",
"",
"# ── Channels ─────────────────────────────",
f"ENABLED_CHANNELS={config.ENABLED_CHANNELS}",
]
slack_bot = keep(config.SLACK_BOT_TOKEN, "SLACK_BOT_TOKEN")
slack_app = keep(config.SLACK_APP_TOKEN, "SLACK_APP_TOKEN")
if slack_bot:
lines += [
"",
"# ── Slack ────────────────────────────────",
f"SLACK_BOT_TOKEN={slack_bot}",
f"SLACK_APP_TOKEN={slack_app}",
]
discord_token = keep(config.DISCORD_BOT_TOKEN, "DISCORD_BOT_TOKEN")
if discord_token:
lines += [
"",
"# ── Discord ──────────────────────────────",
f"DISCORD_BOT_TOKEN={discord_token}",
]
if config.ENABLED_CHANNELS and "imessage" in config.ENABLED_CHANNELS:
lines += [
"",
"# ── iMessage (macOS) ─────────────────────",
f"IMESSAGE_ALLOWED_HANDLES={config.IMESSAGE_ALLOWED_HANDLES}",
f"IMESSAGE_POLL_INTERVAL={config.IMESSAGE_POLL_INTERVAL}",
]
ENV_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8")
return {"ok": True, "path": str(ENV_FILE)}
@app.post("/api/setup/credentials")
async def upload_credentials(file: UploadFile = File(...)):
"""credentials.json 업로드"""
if file.filename and not file.filename.endswith(".json"):
raise HTTPException(status_code=400, detail="JSON 파일만 업로드 가능합니다.")
try:
OPENCHIKEN_HOME.mkdir(parents=True, exist_ok=True)
content = await file.read()
CREDENTIALS_DST.write_bytes(content)
return {"ok": True, "path": str(CREDENTIALS_DST)}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
class ModelFetchRequest(BaseModel):
key: str
def _fetch_openai_models(api_key: str) -> list[dict]:
req = urllib.request.Request(
"https://api.openai.com/v1/models",
headers={"Authorization": f"Bearer {api_key}"},
)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read())
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="ignore")
raise HTTPException(status_code=e.code, detail=f"OpenAI API 오류: {body[:300]}")
INCLUDE_PREFIXES = ("gpt-4", "gpt-3.5", "o1", "o3", "o4", "chatgpt")
EXCLUDE_TOKENS = ("instruct", "embedding", "whisper", "tts", "dall-e",
"babbage", "davinci", "curie", "ada", "moderation",
"realtime", "audio", "search", "ft:")
models = [
m for m in data.get("data", [])
if any(m["id"].startswith(p) for p in INCLUDE_PREFIXES)
and not any(x in m["id"] for x in EXCLUDE_TOKENS)
]
models.sort(key=lambda m: m.get("created", 0), reverse=True)
return [{"id": m["id"], "name": m["id"]} for m in models[:10]]
def _fetch_anthropic_models(api_key: str) -> list[dict]:
req = urllib.request.Request(
"https://api.anthropic.com/v1/models",
headers={"x-api-key": api_key, "anthropic-version": "2023-06-01"},
)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read())
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="ignore")
raise HTTPException(status_code=e.code, detail=f"Anthropic API 오류: {body[:300]}")
models = data.get("data", [])
models.sort(key=lambda m: m.get("created_at", ""), reverse=True)
return [{"id": m["id"], "name": m.get("display_name", m["id"])} for m in models[:10]]
def _fetch_gemini_models(api_key: str) -> list[dict]:
url = f"https://generativelanguage.googleapis.com/v1beta/models?key={urllib.parse.quote(api_key)}"
req = urllib.request.Request(url)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
data = json.loads(resp.read())
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="ignore")
raise HTTPException(status_code=e.code, detail=f"Gemini API 오류: {body[:300]}")
models = [
m for m in data.get("models", [])
if "generateContent" in m.get("supportedGenerationMethods", [])
and "gemini" in m.get("name", "")
and "embedding" not in m.get("name", "")
and "aqa" not in m.get("name", "")
]
models.sort(key=lambda m: m.get("name", ""), reverse=True)
return [
{"id": m["name"].replace("models/", ""), "name": m.get("displayName", m["name"].replace("models/", ""))}
for m in models[:10]
]
@app.post("/api/models/{provider}")
def fetch_provider_models(provider: str, body: ModelFetchRequest):
"""각 LLM 공급자의 최신 모델 목록을 프록시로 가져옵니다."""
if provider not in ("openai", "anthropic", "gemini"):
raise HTTPException(status_code=400, detail="지원하지 않는 공급자입니다")
if not body.key or len(body.key) < 5:
raise HTTPException(status_code=400, detail="API 키가 필요합니다")
try:
if provider == "openai":
return _fetch_openai_models(body.key)
elif provider == "anthropic":
return _fetch_anthropic_models(body.key)
else:
return _fetch_gemini_models(body.key)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=502, detail=str(e))
def _prepare_extension() -> Path | None:
"""Extension 파일을 ~/.openchiken/extensions/chrome/ 에 __init__.py 없이 복사.
Chrome은 _ 접두사 파일을 허용하지 않으므로 site-packages 직접 로드 불가."""
import shutil
src = ROOT / "extensions" / "chrome"
if not (src / "manifest.json").exists():
return None
dst = OPENCHIKEN_HOME / "extensions" / "chrome"
needs_copy = not (dst / "manifest.json").exists()
if not needs_copy:
src_mtime = max(f.stat().st_mtime for f in src.rglob("*") if f.is_file() and f.name != "__init__.py")
dst_mtime = (dst / "manifest.json").stat().st_mtime
needs_copy = src_mtime > dst_mtime
if needs_copy:
if dst.exists():
shutil.rmtree(dst)
shutil.copytree(
src, dst,
ignore=shutil.ignore_patterns("__init__.py", "__pycache__", "*.pyc"),
)
return dst
@app.get("/api/extension/info")
def extension_info():
"""Chrome Extension 경로와 설치 가능 여부를 반환합니다."""
ext_path = _prepare_extension()
if ext_path and (ext_path / "manifest.json").exists():
return {"exists": True, "path": str(ext_path)}
return {"exists": False, "path": str(OPENCHIKEN_HOME / "extensions" / "chrome")}
_CHROME_PATHS = {
"darwin": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"linux": "google-chrome",
"win32": r"C:\Program Files\Google\Chrome\Application\chrome.exe",
}
_RELAY_HEALTH_URL = "https://openchiken-relay-production.up.railway.app/api/agents"
def _find_chrome() -> str | None:
import shutil as _shutil
p = _CHROME_PATHS.get(sys.platform)
if p and Path(p).exists():
return p
return _shutil.which("google-chrome") or _shutil.which("chrome") or _shutil.which("chromium")
def _poll_relay(timeout_sec: int = 30) -> str | None:
"""Relay 서버에서 Extension 연결을 폴링. 연결된 agentId 반환."""
import urllib.request as _ureq
deadline = time.time() + timeout_sec
while time.time() < deadline:
try:
req = _ureq.Request(_RELAY_HEALTH_URL, headers={"Accept": "application/json"})
with _ureq.urlopen(req, timeout=3) as resp:
data = json.loads(resp.read())
agents = data.get("agents", [])
if agents:
return agents[0].get("agentId")
except Exception:
pass
time.sleep(2)
return None
@app.post("/api/extension/install")
def extension_install():
"""Chrome Extension 반자동 설치: 파일 준비 → Chrome 종료 → 재시작 → Relay 폴링."""
ext_path = _prepare_extension()
if not ext_path or not (ext_path / "manifest.json").exists():
return {"ok": False, "status": "no_extension", "path": None}
chrome_bin = _find_chrome()
if not chrome_bin:
return {"ok": False, "status": "no_chrome", "path": str(ext_path)}
# Chrome 종료
try:
if sys.platform == "darwin":
subprocess.run(
["osascript", "-e", 'tell application "Google Chrome" to quit'],
capture_output=True, timeout=5,
)
else:
subprocess.run(["pkill", "-f", "chrome"], capture_output=True, timeout=5)
time.sleep(2)
except Exception:
pass
# --load-extension 으로 Chrome 재시작
try:
if sys.platform == "darwin":
subprocess.Popen([
"open", "-a", "Google Chrome", "--args",
f"--load-extension={ext_path}",
])
else:
subprocess.Popen([chrome_bin, f"--load-extension={ext_path}"])
except Exception as e:
return {"ok": False, "status": "launch_failed", "error": str(e), "path": str(ext_path)}
time.sleep(3)
# Relay 폴링
agent_id = _poll_relay(timeout_sec=30)
if agent_id:
return {"ok": True, "status": "connected", "agentId": agent_id, "path": str(ext_path)}
return {"ok": True, "status": "timeout", "path": str(ext_path)}
@app.post("/api/system/open-privacy-prefs")
def open_privacy_prefs():
"""macOS 전체 디스크 접근 시스템 설정 패널을 엽니다."""
import subprocess, sys
if sys.platform != "darwin":
raise HTTPException(status_code=400, detail="macOS 전용 기능입니다.")
try:
subprocess.Popen([
"open",
"x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles",
])
return {"ok": True}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/skills/reload")
def reload_skills():
"""런타임 스킬 캐시를 무효화합니다. 다음 채팅 요청 시 SKILL.md를 재스캔합니다."""
try:
import core.agent as ag
import skills as sk
ag._tools_cache = None
ag._skill_instructions_cache = None
ag._agent = None
ag._plan_graph = None
sk._loader = None
return {"ok": True, "message": "스킬 캐시가 초기화되었습니다. 다음 요청부터 새 스킬이 반영됩니다."}
except ImportError:
return {"ok": True, "message": "main.py 미실행 상태 — 재시작 시 자동 반영됩니다."}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
class EnvKeyRequest(BaseModel):
env_key: str
env_value: str
def _update_env_file(env_path: Path, key: str, value: str) -> None:
"""~/.openchiken/.env 파일에서 key를 업데이트하거나 새로 추가합니다."""
env_path.parent.mkdir(parents=True, exist_ok=True)
lines: list[str] = []
updated = False
if env_path.exists():
for line in env_path.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if stripped.startswith(f"{key}=") or stripped.startswith(f"{key} ="):
lines.append(f"{key}={value}")
updated = True
else:
lines.append(line)
if not updated:
lines.append(f"{key}={value}")
env_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
@app.post("/api/skills/{skill_id}/env")
def save_skill_env(skill_id: str, req: EnvKeyRequest):
"""스킬에 필요한 API 키(환경변수)를 ~/.openchiken/.env에 저장하고 즉시 적용합니다."""
key = req.env_key.strip()
value = req.env_value.strip()
if not key or not key.replace("_", "").isalnum():
raise HTTPException(status_code=400, detail="유효하지 않은 환경변수 이름입니다.")
if not value:
raise HTTPException(status_code=400, detail="값이 비어있습니다.")
try:
_update_env_file(ENV_FILE, key, value)
os.environ[key] = value
# 스킬 캐시 리로드 (새 환경변수 반영)
try:
import core.agent as ag
import skills as sk
ag._tools_cache = None
ag._skill_instructions_cache = None
ag._agent = None
ag._plan_graph = None
sk._loader = None
except ImportError:
pass
logger.info("Skill env saved: skill=%s, key=%s", skill_id, key)
return {
"ok": True,
"message": f"{key} 가 저장되었습니다. 스킬 '{skill_id}'이(가) 활성화됩니다.",
"skill_id": skill_id,
"env_key": key,
}
except Exception as e:
logger.error("save_skill_env failed: %s", e, exc_info=True)
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/system/start")
def start_main():
"""setup 완료 후 main.py를 백그라운드 서브프로세스로 실행합니다."""
global _main_proc
if _main_proc is not None and _main_proc.poll() is None:
return {"ok": True, "status": "already_running", "pid": _main_proc.pid}
try:
_try_start_main()
return {"ok": True, "status": "started", "pid": _main_proc.pid if _main_proc else None}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/system/stop")
def stop_main():
"""실행 중인 main.py 서브프로세스를 종료합니다."""
global _main_proc
if _main_proc is None or _main_proc.poll() is not None:
return {"ok": True, "status": "not_running"}
try:
_main_proc.terminate()
try:
_main_proc.wait(timeout=5)
except subprocess.TimeoutExpired:
_main_proc.kill()
pid = _main_proc.pid
_main_proc = None
return {"ok": True, "status": "stopped", "pid": pid}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/system/status")
def system_status():
"""main.py 실행 상태를 반환합니다."""
global _main_proc
if _main_proc is None:
return {"running": False, "pid": None}
if _main_proc.poll() is None:
return {"running": True, "pid": _main_proc.pid}
return {"running": False, "pid": None, "exit_code": _main_proc.returncode}
@app.get("/api/setup/credentials/status")
def credentials_status():
"""credentials.json 존재 여부"""
home_exists = CREDENTIALS_DST.exists()
local_exists = (ROOT / "credentials.json").exists()
return {
"exists": home_exists or local_exists,
"path": str(CREDENTIALS_DST) if home_exists else (str(ROOT / "credentials.json") if local_exists else None),
}
# ── Dashboard API ─────────────────────────────────────────────
_WEATHER_ICONS: dict[int, str] = {
0: "clear_day", 1: "partly_cloudy_day", 2: "partly_cloudy_day", 3: "cloud",
45: "foggy", 48: "foggy",
51: "rainy", 53: "rainy", 55: "rainy",
61: "rainy", 63: "rainy", 65: "rainy",
71: "weather_snowy", 73: "weather_snowy", 75: "weather_snowy", 77: "weather_snowy",
80: "rainy", 81: "rainy", 82: "rainy",
85: "weather_snowy", 86: "weather_snowy",
95: "thunderstorm", 96: "thunderstorm", 99: "thunderstorm",
}
@app.get("/api/dashboard/agent-status")
def dashboard_agent_status():
"""에이전트/모델 상태 정보 — .env를 직접 파싱해 서버 재시작 없이 최신값 반영"""
# load_dotenv()는 서버 시작 시 1회만 실행되므로, 셋업 이후 저장된 .env를
# os.environ에서 읽으면 이전 값이 반환될 수 있다. 파일 직접 파싱으로 해결.
env: dict[str, str] = {}
if ENV_FILE.exists():
for raw in ENV_FILE.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if line and not line.startswith("#") and "=" in line:
k, _, v = line.partition("=")
env[k.strip()] = v.strip()
def ev(key: str, default: str = "") -> str:
"""env 파일 → os.environ → 기본값 순으로 조회"""
return env.get(key) or os.getenv(key, default)
provider = ev("LLM_PROVIDER", "openai").lower()
model_key = {
"openai": "OPENAI_MODEL",
"anthropic": "ANTHROPIC_MODEL",
"gemini": "GEMINI_MODEL",
}.get(provider, "OPENAI_MODEL")
model = ev(model_key, "gpt-4o")
channels_raw = ev("ENABLED_CHANNELS", "telegram")
channels = [ch.strip() for ch in channels_raw.split(",") if ch.strip()]
return {
"provider": provider,
"model": model,
"assistant_name": ev("ASSISTANT_NAME", "치킨"),
"status": "active",
"enabled_skills": ev("ENABLED_SKILLS", "all"),
"enabled_channels": channels,
}
@app.get("/api/chain")
def api_chain_status():
"""Relay on-chain 상태 프록시"""
relay_url = os.getenv("RELAY_URL", "https://openchiken-relay-production.up.railway.app")
try:
req = urllib.request.Request(
f"{relay_url.rstrip('/')}/api/chain",
headers={"Accept": "application/json"},
)
with urllib.request.urlopen(req, timeout=8) as resp:
return json.loads(resp.read())
except Exception as e:
return {"ok": False, "error": str(e)}
@app.get("/api/dashboard/agents")
def dashboard_agents():
"""Relay에 연결된 에이전트 목록 + on-chain 평판 조회"""
relay_url = os.getenv("RELAY_URL", "https://openchiken-relay-production.up.railway.app")
def relay_get(path: str, timeout: int = 8) -> dict:
req = urllib.request.Request(
f"{relay_url.rstrip('/')}{path}",
headers={"Accept": "application/json"},
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read())
try:
data = relay_get("/api/agents")
agents: list[dict] = data.get("agents", [])
except Exception as e:
return {"ok": False, "agents": [], "error": f"Relay 연결 실패: {e}"}
for agent in agents:
# 연결 시각 → 상대 시간
connected_ms = agent.get("connectedAt", 0)
if connected_ms:
elapsed_s = (time.time() * 1000 - connected_ms) / 1000
if elapsed_s < 60:
agent["connectedAgo"] = "방금 전"
elif elapsed_s < 3600:
agent["connectedAgo"] = f"{int(elapsed_s // 60)}분 전"
else:
agent["connectedAgo"] = f"{int(elapsed_s // 3600)}시간 전"
else:
agent["connectedAgo"] = "—"
# on-chain 평판
if agent.get("tokenId"):
try:
rep = relay_get(f"/api/agents/{agent['agentId']}/reputation", timeout=5)
agent["reputation"] = {
"count": rep.get("count", 0),
"average": rep.get("average"),
}
except Exception:
agent["reputation"] = {"count": 0, "average": None}
else:
agent["reputation"] = {"count": 0, "average": None}
return {"ok": True, "agents": agents, "total": len(agents)}
@app.get("/api/dashboard/weather")
def dashboard_weather(city: str = "Seoul"):
"""실시간 날씨 데이터 (Open-Meteo, 무료)"""
from skills.weather.tool import _geocode, _WMO_CODES
try:
lat, lon, resolved = _geocode(city)
params = urllib.parse.urlencode({
"latitude": lat,
"longitude": lon,
"current": "temperature_2m,apparent_temperature,weathercode,windspeed_10m,relativehumidity_2m",
"daily": "temperature_2m_max,temperature_2m_min",
"timezone": "Asia/Seoul",
"forecast_days": 1,
})
url = f"https://api.open-meteo.com/v1/forecast?{params}"
with urllib.request.urlopen(url, timeout=10) as resp:
data = json.loads(resp.read())
cur = data["current"]
daily = data.get("daily", {})
code = cur.get("weathercode", 0)
return {
"city": resolved,
"condition": _WMO_CODES.get(code, f"코드 {code}"),
"icon": _WEATHER_ICONS.get(code, "cloud_queue"),
"temp": cur["temperature_2m"],
"feels_like": cur["apparent_temperature"],
"temp_max": daily.get("temperature_2m_max", [None])[0],
"temp_min": daily.get("temperature_2m_min", [None])[0],
"humidity": cur["relativehumidity_2m"],
"windspeed": cur["windspeed_10m"],
}
except Exception as e:
logger.warning("Weather API failed: %s", e)
return JSONResponse(
status_code=502,
content={"error": f"날씨 조회 실패: {e}"},
)
@app.get("/api/dashboard/calendar")
def dashboard_calendar():
"""오늘 Google Calendar 일정"""
try:
from skills.calendar.tool import _get_calendar_service
service = _get_calendar_service()
now = datetime.now(KST)
start = now.replace(hour=0, minute=0, second=0, microsecond=0).isoformat()
end = now.replace(hour=23, minute=59, second=59, microsecond=0).isoformat()
result = (
service.events()
.list(
calendarId="primary",
timeMin=start,
timeMax=end,
singleEvents=True,
orderBy="startTime",
timeZone="Asia/Seoul",
)
.execute()
)
events = []
for e in result.get("items", []):
start_dt = e["start"].get("dateTime", e["start"].get("date", ""))
time_str = start_dt.split("T")[1][:5] if "T" in start_dt else "종일"
events.append({
"time": time_str,
"title": e.get("summary", "(제목 없음)"),
"description": e.get("location") or (e.get("description", "") or "")[:50],
})
return {"events": events}
except Exception as e:
logger.warning("Calendar API unavailable: %s", e)
return {"events": [], "error": str(e)}
@app.get("/api/dashboard/gmail")
def dashboard_gmail(max_results: int = 5):
"""읽지 않은 Gmail 메시지"""
try:
from skills.gmail.tool import _get_gmail_service
service = _get_gmail_service()
results = (
service.users()
.messages()
.list(userId="me", q="is:unread", maxResults=min(max_results, 10))
.execute()
)
messages_refs = results.get("messages", [])
unread_count = results.get("resultSizeEstimate", len(messages_refs))
messages = []
for msg_ref in messages_refs:
msg = (
service.users()
.messages()
.get(
userId="me",
id=msg_ref["id"],
format="metadata",
metadataHeaders=["From", "Subject", "Date"],
)
.execute()
)
headers = {h["name"]: h["value"] for h in msg["payload"]["headers"]}
from_raw = headers.get("From", "Unknown")
from_name = from_raw.split("<")[0].strip().strip('"') if "<" in from_raw else from_raw
messages.append({
"from": from_name,
"subject": headers.get("Subject", "(제목 없음)"),
"date": headers.get("Date", ""),
})
return {"messages": messages, "unread_count": unread_count}
except Exception as e:
logger.warning("Gmail API unavailable: %s", e)
return {"messages": [], "unread_count": 0, "error": str(e)}
@app.get("/api/dashboard/memory")
def dashboard_memory(limit: int = 6):
"""최근 대화 기록 + 메모"""
try:
db_path = _db_path()
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(
"SELECT id, session_id, message FROM message_store ORDER BY id DESC LIMIT ?",
(limit * 3,),
)
rows = cursor.fetchall()
cursor.execute(
"SELECT id, title, content, created_at FROM memo_store ORDER BY id DESC LIMIT ?",
(limit,),
)
memo_rows = cursor.fetchall()
conn.close()
messages = []