forked from WooHyucks/claw-log
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.py
More file actions
324 lines (274 loc) · 14.4 KB
/
engine.py
File metadata and controls
324 lines (274 loc) · 14.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
from abc import ABC, abstractmethod
from openai import OpenAI
import os
import sys
import json
import time
import re
import subprocess as sp
import urllib.request
import urllib.parse
import urllib.error
from pathlib import Path
try:
import google.genai as genai
except ImportError:
print("❌ [Import Error] 필수 라이브러리 로드 실패.")
print(" 'google-generativeai'와 'google-genai' 간의 충돌일 수 있습니다.")
print(" 👉 아래 명령어로 의존성을 재설치해주세요:")
print(" pipx install claw-log --force")
sys.exit(1)
# --- 프롬프트 정의 ---
SYSTEM_PROMPT = """
당신은 수석 테크니컬 라이터이자 기술 채용 전문가입니다.
아래 Git 데이터를 분석하여, 경력기술서에 즉시 반영 가능한 수준의 **[성과 중심 데일리 리포트]**를 작성하세요.
[핵심 작성 원칙]
1. **언어 규칙**: 모든 설명은 **한국어**로 작성하세요. 단, 기술 용어(API, 라이브러리, 클래스명 등)는 원어(영어)를 그대로 사용해도 됩니다.
2. **전문적 어휘**: 단순한 서술 대신 '구현함', '최적화함', '설계함', '해결함' 등 전문적인 태도로 문장을 끝맺으세요.
3. **Context 통합**: 이미 커밋된 내용(Past Commits)과 수정 중인 내용(Uncommitted)을 하나의 연속된 작업으로 간주하여 '기능 단위'로 통합 요약하세요.
4. **데이터 기반**: 가능한 경우 구체적인 파일명, 함수명, 라이브러리, 디자인 패턴을 명시하여 기술적 실체를 드러내세요.
5. **분량 제한**: 전체 리포트는 공백 포함 2,000자 이내로 작성하세요.
[출력 형식]
### 📂 [Project Name]
> **핵심 성과**: (오늘 이룬 가장 중요한 기술적 진보를 비즈니스/사용자 가치 관점에서 1문장 요약 - 한국어)
- **🛠 상세 내역**
- **기능 구현 및 통합**: (주요 파일/클래스명을 포함하여 오늘 완성하거나 진행한 핵심 로직 요약 - 한국어)
- **기술적 의사결정**: (적용한 라이브러리, 패턴, 혹은 직면한 기술적 문제를 해결한 구체적인 방법 - 한국어)
- **💡 Career Insight**
- (이 작업을 통해 증명된 본인의 핵심 역량 - 예: 유지보수성 향상, 보안 강화, 확장성 고려 등 - 한국어)
- **📝 Resume Bullet Point**
- (성과와 기술 스택이 포함된 경력기술서용 핵심 문장. 예: "GitHub Actions 기반의 CI/CD 파이프라인 구축으로 배포 시간 50% 단축")
---
"""
class BaseSummarizer(ABC):
@abstractmethod
def summarize(self, text_data):
pass
class GeminiSummarizer(BaseSummarizer):
def __init__(self, api_key):
self.client = genai.Client(api_key=api_key)
self.model_name = 'gemini-2.5-flash' # 최신 모델 사용
def summarize(self, text_data):
try:
response = self.client.models.generate_content(
model=self.model_name,
contents=f"{SYSTEM_PROMPT}\n\n[전체 개발 내역 데이터]\n{text_data}"
)
return response.text
except Exception as e:
error_msg = str(e)
if "400" in error_msg or "API_KEY_INVALID" in error_msg:
return (
"❌ [API Key Error] 유효하지 않은 API 키입니다.\n"
" 👉 'claw-log --reset' 명령어로 키를 다시 설정하거나,\n"
" Google AI Studio(https://aistudio.google.com/app/apikey)에서 키 상태를 확인해주세요."
)
elif "429" in error_msg or "RESOURCE_EXHAUSTED" in error_msg:
return (
"🌐 [Quota Error] API 사용량이 초과되었습니다.\n"
" 👉 잠시 후 다시 시도하거나, 할당량을 확인해주세요."
)
elif "404" in error_msg:
return (
"⚠️ [Model Error] 모델을 찾을 수 없습니다.\n"
" 👉 지원되지 않는 리전이거나 모델명이 변경되었을 수 있습니다."
)
else:
return f"❌ [Unknown Error] Gemini 요약 실패:\n {error_msg}\n 👉 네트워크 연결을 확인해주세요."
class GeminiOAuthSummarizer(BaseSummarizer):
"""Gemini CLI의 OAuth 인증 정보(~/.gemini/oauth_creds.json)를 사용하는 Summarizer.
google-genai SDK는 OAuth 단독 인증을 지원하지 않으므로 REST API를 직접 호출합니다."""
GEMINI_CREDS_PATH = Path.home() / ".gemini" / "oauth_creds.json"
GEMINI_PROJECT_CACHE = Path.home() / ".gemini" / "claw_log_project.json"
TOKEN_URI = "https://oauth2.googleapis.com/token"
API_BASE = "https://cloudcode-pa.googleapis.com/v1internal"
def __init__(self):
self.model_name = "gemini-3-flash-preview"
self.access_token = self._load_and_refresh_token()
self.project_id = self._get_project_id()
@staticmethod
def _read_oauth_config_from_cli():
"""Gemini CLI 설치 경로에서 OAuth client_id/secret을 동적으로 읽어옵니다."""
try:
npm_root = sp.check_output(["npm", "root", "-g"], stderr=sp.DEVNULL).decode().strip()
except Exception:
return None, None
oauth2_path = Path(npm_root) / "@google" / "gemini-cli" / "node_modules" / "@google" / "gemini-cli-core" / "dist" / "src" / "code_assist" / "oauth2.js"
if not oauth2_path.exists():
return None, None
content = oauth2_path.read_text()
client_id_match = re.search(r"OAUTH_CLIENT_ID\s*=\s*['\"](.+?)['\"]", content)
client_secret_match = re.search(r"OAUTH_CLIENT_SECRET\s*=\s*['\"](.+?)['\"]", content)
client_id = client_id_match.group(1) if client_id_match else None
client_secret = client_secret_match.group(1) if client_secret_match else None
return client_id, client_secret
def _load_and_refresh_token(self):
if not self.GEMINI_CREDS_PATH.exists():
print("❌ Gemini CLI OAuth 인증 정보를 찾을 수 없습니다.")
print(" 👉 'gemini' 명령어를 실행하여 먼저 OAuth 로그인을 완료해주세요.")
sys.exit(1)
creds_data = json.loads(self.GEMINI_CREDS_PATH.read_text())
# 토큰이 유효하면 그대로 사용
expiry_ms = creds_data.get("expiry_date", 0)
if time.time() * 1000 < expiry_ms:
return creds_data["access_token"]
# 만료된 경우 refresh_token으로 갱신
client_id, client_secret = self._read_oauth_config_from_cli()
if not client_id or not client_secret:
print("❌ Gemini CLI 설치를 찾을 수 없거나 OAuth 설정을 읽지 못했습니다.")
print(" 👉 'npm install -g @google/gemini-cli' 로 Gemini CLI를 설치해주세요.")
sys.exit(1)
refresh_token = creds_data.get("refresh_token")
if not refresh_token:
print("❌ refresh_token이 없습니다. 'gemini' 명령어로 다시 로그인해주세요.")
sys.exit(1)
try:
body = urllib.parse.urlencode({
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh_token,
"grant_type": "refresh_token",
}).encode()
req = urllib.request.Request(self.TOKEN_URI, data=body, method="POST")
req.add_header("Content-Type", "application/x-www-form-urlencoded")
with urllib.request.urlopen(req) as resp:
token_data = json.loads(resp.read().decode())
new_access_token = token_data["access_token"]
expires_in = token_data.get("expires_in", 3600)
# 갱신된 토큰 저장
creds_data["access_token"] = new_access_token
creds_data["expiry_date"] = int((time.time() + expires_in) * 1000)
self.GEMINI_CREDS_PATH.write_text(json.dumps(creds_data, indent=2))
print("🔄 OAuth 토큰이 자동으로 갱신되었습니다.")
return new_access_token
except Exception as e:
print(f"⚠️ 토큰 갱신 실패: {e}")
print(" 👉 'gemini' 명령어로 다시 로그인해주세요.")
sys.exit(1)
def _get_project_id(self):
# 캐시된 프로젝트 ID 확인
if self.GEMINI_PROJECT_CACHE.exists():
try:
cached = json.loads(self.GEMINI_PROJECT_CACHE.read_text())
if cached.get("project_id"):
return cached["project_id"]
except Exception:
pass
# loadCodeAssist 호출로 프로젝트 ID 조회
url = f"{self.API_BASE}:loadCodeAssist"
payload = json.dumps({
"metadata": {
"ideType": "IDE_UNSPECIFIED",
"platform": "PLATFORM_UNSPECIFIED",
"pluginType": "GEMINI",
},
})
req = urllib.request.Request(url, data=payload.encode(), method="POST")
req.add_header("Authorization", f"Bearer {self.access_token}")
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req) as resp:
result = json.loads(resp.read().decode())
project_id = result.get("cloudaicompanionProject")
if project_id:
self.GEMINI_PROJECT_CACHE.write_text(json.dumps({"project_id": project_id}))
return project_id
# 온보딩 필요
return self._onboard_user()
except Exception as e:
print(f"⚠️ 프로젝트 조회 실패: {e}")
print(" 👉 'gemini' 명령어로 다시 로그인해주세요.")
sys.exit(1)
def _onboard_user(self):
url = f"{self.API_BASE}:onboardUser"
payload = json.dumps({
"tierId": 1, # FREE tier
"metadata": {
"ideType": "IDE_UNSPECIFIED",
"platform": "PLATFORM_UNSPECIFIED",
"pluginType": "GEMINI",
},
})
req = urllib.request.Request(url, data=payload.encode(), method="POST")
req.add_header("Authorization", f"Bearer {self.access_token}")
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req) as resp:
result = json.loads(resp.read().decode())
project_id = result.get("response", {}).get("cloudaicompanionProject", {}).get("id")
if project_id:
self.GEMINI_PROJECT_CACHE.write_text(json.dumps({"project_id": project_id}))
return project_id
print("❌ 온보딩 후에도 프로젝트 ID를 얻지 못했습니다.")
sys.exit(1)
except Exception as e:
print(f"⚠️ 온보딩 실패: {e}")
sys.exit(1)
def summarize(self, text_data):
url = f"{self.API_BASE}:generateContent"
payload = json.dumps({
"model": self.model_name,
"project": self.project_id,
"request": {
"contents": [{"role": "user", "parts": [{"text": f"{SYSTEM_PROMPT}\n\n[전체 개발 내역 데이터]\n{text_data}"}]}],
},
})
req = urllib.request.Request(url, data=payload.encode(), method="POST")
req.add_header("Authorization", f"Bearer {self.access_token}")
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req) as resp:
result = json.loads(resp.read().decode())
return result["response"]["candidates"][0]["content"]["parts"][0]["text"]
except urllib.error.HTTPError as e:
status = e.code
error_body = e.read().decode() if e.fp else ""
if status == 401:
return (
"❌ [Auth Error] OAuth 인증이 만료되었습니다.\n"
" 👉 'gemini' 명령어로 다시 로그인 후 재시도해주세요."
)
elif status == 429:
return (
"🌐 [Quota Error] API 사용량이 초과되었습니다.\n"
" 👉 잠시 후 다시 시도하거나, 할당량을 확인해주세요."
)
elif status == 403:
return (
"🔒 [Permission Error] Gemini API 접근 권한이 없습니다.\n"
" 👉 Google Cloud 프로젝트에서 Generative Language API가 활성화되어 있는지 확인해주세요."
)
else:
return f"❌ [HTTP {status}] Gemini OAuth 요약 실패:\n {error_body[:300]}\n 👉 'gemini' 명령어로 재로그인을 시도해주세요."
except Exception as e:
return f"❌ [Unknown Error] Gemini OAuth 요약 실패:\n {str(e)}\n 👉 네트워크 연결을 확인해주세요."
class OpenAISummarizer(BaseSummarizer):
def __init__(self, api_key):
self.client = OpenAI(api_key=api_key)
self.model_name = "gpt-4o-mini"
def summarize(self, text_data):
try:
response = self.client.chat.completions.create(
model=self.model_name,
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": f"[전체 개발 내역 데이터]\n{text_data}"}
],
temperature=0.7
)
return response.choices[0].message.content
except Exception as e:
error_msg = str(e)
if "AuthenticationError" in error_msg or "401" in error_msg:
return (
"❌ [API Key Error] 유효하지 않은 API 키입니다.\n"
" 👉 'claw-log --reset' 명령어로 키를 다시 설정하거나,\n"
" OpenAI Platform(https://platform.openai.com/api-keys)에서 키를 확인해주세요."
)
elif "RateLimitError" in error_msg or "429" in error_msg:
return (
"🌐 [Quota Error] API 사용량이 초과되었거나 너무 많은 요청이 발생했습니다.\n"
" 👉 잠시 후 다시 시도하거나, 크레딧 잔액을 확인해주세요."
)
else:
return f"❌ [Unknown Error] OpenAI 요약 실패:\n {error_msg}\n 👉 네트워크 상태를 확인해주세요."