File size: 17,611 Bytes
0491e54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
AI Focus Agent with OpenAI/Claude integration and personality system.
"""
import os
from typing import Dict, List, Optional, Union
from datetime import datetime
import json


class FocusAgent:
    """AI agent that monitors focus and provides Duolingo-style nudges."""

    def __init__(self, provider: str = "openai", api_key: Optional[str] = None,
                 base_url: Optional[str] = None, model: Optional[str] = None):
        """Initialize the focus agent with AI provider."""
        self.provider = provider.lower()
        self.last_verdict: Optional[str] = None
        self.idle_count = 0
        self.distracted_count = 0
        self.connection_healthy = False

        if self.provider == "openai":
            from openai import OpenAI
            self.api_key = api_key or os.getenv("OPENAI_API_KEY")
            self.client = OpenAI(api_key=self.api_key) if self.api_key else None
            self.model = model or "gpt-4o"
            self.connection_healthy = bool(self.api_key)
        elif self.provider == "anthropic":
            from anthropic import Anthropic
            self.api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
            self.client = Anthropic(api_key=self.api_key) if self.api_key else None
            self.model = model or "claude-haiku-4-5-20251001"
            self.connection_healthy = bool(self.api_key)
        elif self.provider == "gemini":
            import google.generativeai as genai
            self.api_key = api_key or os.getenv("GEMINI_API_KEY")
            if self.api_key:
                genai.configure(api_key=self.api_key)
                self.client = genai.GenerativeModel(model or "gemini-2.0-flash-exp")
                self.model = model or "gemini-2.0-flash-exp"
                self.connection_healthy = True
            else:
                self.client = None
                self.connection_healthy = False
        elif self.provider == "vllm":
            from openai import OpenAI
            import httpx
            self.api_key = api_key or os.getenv("VLLM_API_KEY", "EMPTY")
            self.base_url = base_url or os.getenv("VLLM_BASE_URL", "http://localhost:8000/v1")
            self.model = model or os.getenv("VLLM_MODEL", "ibm-granite/granite-4.0-h-1b")

            try:
                timeout = httpx.Timeout(5.0, connect=2.0)
                self.client = OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=timeout)
                test_response = self.client.models.list()
                self.connection_healthy = True
            except Exception as e:
                print(f"⚠️ vLLM connection failed: {e}")
                print(f"   Make sure vLLM server is running at {self.base_url}")
                self.client = None
                self.connection_healthy = False
        else:
            raise ValueError(f"Unsupported provider: {provider}. Supported: openai, anthropic, gemini, vllm")

    def _create_analysis_prompt(self, active_task: Dict, recent_activity: List[Dict]) -> str:
        """Create the analysis prompt for the LLM."""
        if not recent_activity:
            return f"""You are FocusFlow, a Duolingo-style accountability buddy for developers.

**Current Task:**
- Title: {active_task.get('title', 'No task')}
- Description: {active_task.get('description', 'No description')}

**Recent Activity:** No file changes detected in the last 60 seconds.

**Your Job:** Analyze the situation and respond with ONE of these verdicts:
1. "On Track" - If there's activity related to the task
2. "Distracted" - If files unrelated to the task are being edited
3. "Idle" - If there's no activity

Respond in JSON format:
{{
  "verdict": "On Track" | "Distracted" | "Idle",
  "message": "Your encouraging/sassy/nudging message (1-2 sentences, Duolingo style)",
  "reasoning": "Brief explanation of your analysis"
}}"""

        activity_summary = []
        for event in recent_activity[-5:]:
            activity_summary.append(
                f"- {event['type'].upper()}: {event['filename']}\n  Content: {event.get('content', 'N/A')[:200]}"
            )

        activity_text = "\n".join(activity_summary)

        return f"""You are FocusFlow, a Duolingo-style accountability buddy for developers.

**Current Task:**
- Title: {active_task.get('title', 'No task')}
- Description: {active_task.get('description', 'No description')}

**Recent File Activity (last 60 seconds):**
{activity_text}

**Your Job:** Analyze if the file changes are related to the current task.

**Personality Guidelines:**
- "On Track": Be encouraging and specific (e.g., "Great job! I see you're working on the login form!")
- "Distracted": Be playfully sassy (e.g., "Wait, why are you editing random_file.py? We're building a Snake game! 🀨")
- "Idle": Be gently nudging (e.g., "Files won't write themselves. *Hoot hoot.* πŸ¦‰")

Respond in JSON format:
{{
  "verdict": "On Track" | "Distracted" | "Idle",
  "message": "Your message (1-2 sentences)",
  "reasoning": "Brief explanation"
}}"""

    def _call_llm(self, prompt: str) -> Dict:
        """Call the LLM and parse the response."""
        try:
            if self.provider in ["openai", "vllm"]:
                if not self.client:
                    return {"verdict": "On Track", "message": "API client not initialized", "reasoning": "No client"}
                response = self.client.chat.completions.create(
                    model=self.model,
                    messages=[{"role": "user", "content": prompt}],
                    temperature=0.7,
                    max_tokens=300
                )
                content = response.choices[0].message.content
            elif self.provider == "gemini":
                if not self.client:
                    return {"verdict": "On Track", "message": "API client not initialized", "reasoning": "No client"}
                response = self.client.generate_content(
                    prompt,
                    generation_config={
                        "temperature": 0.7,
                        "max_output_tokens": 300,
                    }
                )
                content = response.text
            else:  # anthropic
                if not self.client:
                    return {"verdict": "On Track", "message": "API client not initialized", "reasoning": "No client"}
                response = self.client.messages.create(
                    model=self.model,
                    max_tokens=300,
                    temperature=0.7,
                    messages=[{"role": "user", "content": prompt}]
                )
                content = response.content[0].text

            if not content:
                return {"verdict": "On Track", "message": "Empty response from API", "reasoning": "No content"}

            # Try to parse JSON from the response
            content = content.strip()
            if "```json" in content:
                content = content.split("```json")[1].split("```")[0].strip()
            elif "```" in content:
                content = content.split("```")[1].split("```")[0].strip()

            result = json.loads(content)
            return result

        except json.JSONDecodeError:
            # Fallback if JSON parsing fails
            return {
                "verdict": "On Track",
                "message": content[:200],
                "reasoning": "AI response parsing fallback"
            }
        except Exception as e:
            return {
                "verdict": "On Track",
                "message": f"Error analyzing activity: {str(e)}",
                "reasoning": "Error occurred"
            }

    def analyze(self, active_task: Optional[Dict], recent_activity: List[Dict]) -> Dict:
        """Analyze current activity and return verdict."""
        if not active_task:
            return {
                "verdict": "Idle",
                "message": "No active task selected. Pick a task to get started! 🎯",
                "reasoning": "No active task",
                "timestamp": datetime.now().isoformat()
            }

        if not self.connection_healthy or not self.client:
            provider_name = self.provider.upper()
            if self.provider == "vllm":
                msg = f"⚠️ vLLM server not reachable. Make sure it's running at {self.base_url}"
            else:
                msg = f"⚠️ {provider_name} API key not configured. Add your API key to enable AI monitoring."
            return {
                "verdict": "On Track",
                "message": msg,
                "reasoning": "No connection",
                "timestamp": datetime.now().isoformat()
            }

        prompt = self._create_analysis_prompt(active_task, recent_activity)
        result = self._call_llm(prompt)
        result["timestamp"] = datetime.now().isoformat()

        # Track consecutive idle/distracted states
        verdict = result.get("verdict", "On Track")
        if verdict == "Idle":
            self.idle_count += 1
            self.distracted_count = 0
        elif verdict == "Distracted":
            self.distracted_count += 1
            self.idle_count = 0
        else:
            self.idle_count = 0
            self.distracted_count = 0

        result["should_alert"] = (self.idle_count >= 2 or self.distracted_count >= 2)
        self.last_verdict = verdict

        return result

    def get_onboarding_tasks(self, project_description: str) -> List[Dict]:
        """Generate micro-tasks from project description."""
        if not self.connection_healthy or not self.client:
            return []

        prompt = f"""You are FocusFlow, an AI project planner.

The user wants to build: "{project_description}"

Break this down into 5-8 concrete, actionable micro-tasks. Each task should be:
- Specific and achievable in 15-30 minutes
- Ordered logically (setup β†’ core features β†’ polish)
- Clearly described

Respond in JSON format:
{{
  "tasks": [
    {{"title": "Task 1 title", "description": "Detailed description", "estimated_duration": "15 min"}},
    {{"title": "Task 2 title", "description": "Detailed description", "estimated_duration": "20 min"}}
  ]
}}"""

        try:
            if self.provider in ["openai", "vllm"]:
                if not self.client:
                    return []
                response = self.client.chat.completions.create(
                    model=self.model,
                    messages=[{"role": "user", "content": prompt}],
                    temperature=0.7,
                    max_tokens=800
                )
                content = response.choices[0].message.content
            elif self.provider == "gemini":
                if not self.client:
                    return []
                response = self.client.generate_content(
                    prompt,
                    generation_config={
                        "temperature": 0.7,
                        "max_output_tokens": 800,
                    }
                )
                content = response.text
            else:  # anthropic
                if not self.client:
                    return []
                response = self.client.messages.create(
                    model=self.model,
                    max_tokens=800,
                    temperature=0.7,
                    messages=[{"role": "user", "content": prompt}]
                )
                content = response.content[0].text

            if not content:
                return []

            # Parse JSON
            content = content.strip()
            if "```json" in content:
                content = content.split("```json")[1].split("```")[0].strip()
            elif "```" in content:
                content = content.split("```")[1].split("```")[0].strip()

            result = json.loads(content)
            return result.get("tasks", [])

        except Exception as e:
            print(f"Error generating tasks: {e}")
            return []


class MockFocusAgent(FocusAgent):
    """Mock agent for demo mode without API keys. Returns predefined responses."""

    def __init__(self):
        """Initialize mock agent without any API dependencies."""
        self.provider = "mock"
        self.last_verdict = None
        self.idle_count = 0
        self.distracted_count = 0
        self.connection_healthy = True
        self.client = None
        self.api_key = None
        self.check_counter = 0

        self.verdicts_cycle = ["On Track", "On Track", "Distracted", "On Track", "Idle"]
        self.messages = {
            "On Track": [
                "Great work! You're making solid progress! 🎯",
                "Keep it up! I see you're focused on the task. πŸ’ͺ",
                "Looking good! You're on the right track! ✨",
                "Nice! Your workflow is looking productive! πŸš€"
            ],
            "Distracted": [
                "Wait, what are you working on? That doesn't look like the task! 🀨",
                "Hmm, spotted some wandering there. Let's refocus! πŸ‘€",
                "Getting a bit sidetracked? Back to the task! 🎯",
                "I see you there! Time to get back on track! πŸ¦‰"
            ],
            "Idle": [
                "Files won't write themselves. *Hoot hoot.* πŸ¦‰",
                "Hey! Time to make some progress! ⏰",
                "No activity detected. Let's get moving! πŸ’€",
                "Your task is waiting! Let's code! πŸ”₯"
            ]
        }

    def analyze(self, active_task: Optional[Dict], recent_activity: List[Dict]) -> Dict:
        """Return mock analysis results."""
        if not active_task:
            return {
                "verdict": "Idle",
                "message": "No active task selected. Pick a task to get started! 🎯",
                "reasoning": "No active task (mock mode)",
                "timestamp": datetime.now().isoformat()
            }

        # Cycle through verdicts
        verdict = self.verdicts_cycle[self.check_counter % len(self.verdicts_cycle)]
        self.check_counter += 1

        # Get message for this verdict
        import random
        message = random.choice(self.messages[verdict])

        # Track consecutive states
        if verdict == "Idle":
            self.idle_count += 1
            self.distracted_count = 0
        elif verdict == "Distracted":
            self.distracted_count += 1
            self.idle_count = 0
        else:
            self.idle_count = 0
            self.distracted_count = 0

        self.last_verdict = verdict

        return {
            "verdict": verdict,
            "message": message,
            "reasoning": f"Mock analysis for task: {active_task.get('title', 'Unknown')}",
            "timestamp": datetime.now().isoformat(),
            "should_alert": (self.idle_count >= 2 or self.distracted_count >= 2)
        }

    def get_onboarding_tasks(self, project_description: str) -> List[Dict]:
        """Generate mock tasks based on project description."""
        # Simple keyword-based task generation
        description_lower = project_description.lower()

        if any(word in description_lower for word in ["web", "website", "app", "frontend"]):
            return [
                {"title": "Set up project structure", "description": "Create folders and initial files", "estimated_duration": "15 min"},
                {"title": "Design UI mockup", "description": "Sketch out the main interface", "estimated_duration": "20 min"},
                {"title": "Build homepage", "description": "Create the landing page HTML/CSS", "estimated_duration": "30 min"},
                {"title": "Add navigation", "description": "Implement menu and routing", "estimated_duration": "25 min"},
                {"title": "Connect backend", "description": "Set up API integration", "estimated_duration": "30 min"},
                {"title": "Test and debug", "description": "Fix bugs and test functionality", "estimated_duration": "20 min"}
            ]
        elif any(word in description_lower for word in ["api", "backend", "server"]):
            return [
                {"title": "Set up project structure", "description": "Initialize project and dependencies", "estimated_duration": "15 min"},
                {"title": "Design database schema", "description": "Plan data models and relationships", "estimated_duration": "20 min"},
                {"title": "Create API endpoints", "description": "Build REST routes", "estimated_duration": "30 min"},
                {"title": "Add authentication", "description": "Implement user auth", "estimated_duration": "25 min"},
                {"title": "Write tests", "description": "Create unit and integration tests", "estimated_duration": "30 min"}
            ]
        else:
            # Generic tasks
            return [
                {"title": "Research and planning", "description": "Gather requirements and plan approach", "estimated_duration": "20 min"},
                {"title": "Set up environment", "description": "Install dependencies and tools", "estimated_duration": "15 min"},
                {"title": "Build core feature #1", "description": "Implement main functionality", "estimated_duration": "30 min"},
                {"title": "Build core feature #2", "description": "Add secondary features", "estimated_duration": "25 min"},
                {"title": "Testing and debugging", "description": "Test and fix issues", "estimated_duration": "20 min"},
                {"title": "Documentation", "description": "Write README and comments", "estimated_duration": "15 min"}
            ]