omnispindle 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- Omnispindle/__init__.py +187 -0
- Omnispindle/__main__.py +121 -0
- Omnispindle/ai_assistant.py +422 -0
- Omnispindle/api_client.py +275 -0
- Omnispindle/api_tools.py +395 -0
- Omnispindle/auth.py +117 -0
- Omnispindle/auth0_actions/custom_token_exchange.js +78 -0
- Omnispindle/auth_flow.py +173 -0
- Omnispindle/auth_setup.py +240 -0
- Omnispindle/auth_utils.py +80 -0
- Omnispindle/chat-to-create-todos-from-work.txt +2018 -0
- Omnispindle/context.py +16 -0
- Omnispindle/database.py +164 -0
- Omnispindle/http_server.py +99 -0
- Omnispindle/hybrid_tools.py +407 -0
- Omnispindle/mcp_handler.py +60 -0
- Omnispindle/middleware.py +194 -0
- Omnispindle/models/__init__.py +1 -0
- Omnispindle/models/config.py +11 -0
- Omnispindle/mqtt.py +80 -0
- Omnispindle/patches.py +233 -0
- Omnispindle/requirements.txt +371 -0
- Omnispindle/scheduler.py +756 -0
- Omnispindle/server.py +282 -0
- Omnispindle/sse_handler.py +169 -0
- Omnispindle/stdio_http_server.py +73 -0
- Omnispindle/stdio_server.py +528 -0
- Omnispindle/todo_log_service.py +423 -0
- Omnispindle/token_exchange.py +174 -0
- Omnispindle/tools.py +1166 -0
- Omnispindle/utils.py +258 -0
- Omnispindle/verify_token.py +43 -0
- omnispindle-1.0.0.dist-info/METADATA +291 -0
- omnispindle-1.0.0.dist-info/RECORD +36 -0
- omnispindle-1.0.0.dist-info/WHEEL +4 -0
- omnispindle-1.0.0.dist-info/entry_points.txt +4 -0
Omnispindle/scheduler.py
ADDED
|
@@ -0,0 +1,756 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Task Auto-Scheduling Module for FastMCP Todo Server
|
|
3
|
+
|
|
4
|
+
This module provides intelligent task scheduling capabilities including:
|
|
5
|
+
- Deadline suggestions based on task priority and estimated completion time
|
|
6
|
+
- Work pattern analysis to find optimal time slots for tasks
|
|
7
|
+
- Calendar integration for scheduling suggestions
|
|
8
|
+
- Workload balancing to prevent overallocation
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import os
|
|
14
|
+
from datetime import datetime, timedelta, UTC, time
|
|
15
|
+
from typing import Dict, List, Optional, Tuple, Any
|
|
16
|
+
import random
|
|
17
|
+
import calendar
|
|
18
|
+
from collections import defaultdict
|
|
19
|
+
|
|
20
|
+
from pymongo import MongoClient
|
|
21
|
+
from .ai_assistant import assistant as todo_assistant
|
|
22
|
+
from .utils import mqtt_publish
|
|
23
|
+
|
|
24
|
+
# Configure logger
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
# Load MongoDB connection from environment
|
|
28
|
+
MONGODB_URI = os.getenv("MONGODB_URI", "mongodb://localhost:27017")
|
|
29
|
+
MONGODB_DB = os.getenv("MONGODB_DB", "swarmonomicon")
|
|
30
|
+
MONGODB_COLLECTION = os.getenv("MONGODB_COLLECTION", "todos")
|
|
31
|
+
|
|
32
|
+
# Create MongoDB connection
|
|
33
|
+
mongo_client = MongoClient(MONGODB_URI)
|
|
34
|
+
db = mongo_client[MONGODB_DB]
|
|
35
|
+
collection = db[MONGODB_COLLECTION]
|
|
36
|
+
|
|
37
|
+
# Constants for scheduling
|
|
38
|
+
WORKING_HOURS = {
|
|
39
|
+
# Weekday: [(start_hour, start_minute), (end_hour, end_minute)]
|
|
40
|
+
0: [(9, 0), (17, 0)], # Monday
|
|
41
|
+
1: [(9, 0), (17, 0)], # Tuesday
|
|
42
|
+
2: [(9, 0), (17, 0)], # Wednesday
|
|
43
|
+
3: [(9, 0), (17, 0)], # Thursday
|
|
44
|
+
4: [(9, 0), (17, 0)], # Friday
|
|
45
|
+
5: [(10, 0), (14, 0)], # Saturday (reduced hours)
|
|
46
|
+
6: [], # Sunday (no hours)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
# Priority to deadline mapping (in days)
|
|
50
|
+
PRIORITY_DEADLINES = {
|
|
51
|
+
"high": 2,
|
|
52
|
+
"medium": 5,
|
|
53
|
+
"low": 10,
|
|
54
|
+
"initial": 7,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
# Priority to time slot duration mapping (in minutes)
|
|
58
|
+
PRIORITY_DURATION = {
|
|
59
|
+
"high": 120, # 2 hours
|
|
60
|
+
"medium": 90, # 1.5 hours
|
|
61
|
+
"low": 60, # 1 hour
|
|
62
|
+
"initial": 90, # 1.5 hours
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# @register_tool_once
|
|
68
|
+
# async def get_todo_suggestions_tool() -> str:
|
|
69
|
+
# """
|
|
70
|
+
# Get AI-powered suggestions for todos based on pattern analysis.
|
|
71
|
+
|
|
72
|
+
# This tool analyzes completed todos to identify patterns and makes suggestions for:
|
|
73
|
+
# 1. Task automation opportunities
|
|
74
|
+
# 2. Priority recommendations for pending todos
|
|
75
|
+
# 3. Insights about task patterns
|
|
76
|
+
|
|
77
|
+
# Returns:
|
|
78
|
+
# A JSON string containing suggestions and analysis results
|
|
79
|
+
# """
|
|
80
|
+
# return await get_todo_suggestions()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# @register_tool_once
|
|
84
|
+
# async def get_specific_todo_suggestions_tool(todo_id: str) -> str:
|
|
85
|
+
# """
|
|
86
|
+
# Get AI-powered suggestions for a specific todo.
|
|
87
|
+
|
|
88
|
+
# This tool analyzes a specific todo and compares it with completed todos to provide:
|
|
89
|
+
# 1. Priority recommendations based on similar completed todos
|
|
90
|
+
# 2. Estimated completion time based on similar tasks
|
|
91
|
+
# 3. List of similar completed todos for reference
|
|
92
|
+
|
|
93
|
+
# Args:
|
|
94
|
+
# todo_id: ID of the todo to get suggestions for
|
|
95
|
+
|
|
96
|
+
# Returns:
|
|
97
|
+
# A JSON string containing suggestions specific to the todo
|
|
98
|
+
# """
|
|
99
|
+
# return await get_specific_suggestions(todo_id)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# @register_tool_once
|
|
103
|
+
# async def suggest_deadline_tool(todo_id: str) -> str:
|
|
104
|
+
# """
|
|
105
|
+
# Suggest an optimal deadline for a specific todo based on priority and content analysis.
|
|
106
|
+
|
|
107
|
+
# This tool analyzes a todo's priority and description to suggest a reasonable deadline:
|
|
108
|
+
# 1. High priority tasks get shorter deadlines
|
|
109
|
+
# 2. Keywords like "urgent" or "tomorrow" influence the suggestion
|
|
110
|
+
# 3. The deadline always falls on a working day
|
|
111
|
+
|
|
112
|
+
# The returned data includes:
|
|
113
|
+
# - Suggested deadline date with reasoning
|
|
114
|
+
# - Adjustment factors that were considered
|
|
115
|
+
# - Possible next actions after setting a deadline
|
|
116
|
+
|
|
117
|
+
# Args:
|
|
118
|
+
# todo_id: ID of the todo to suggest a deadline for
|
|
119
|
+
|
|
120
|
+
# Returns:
|
|
121
|
+
# A JSON string containing the deadline suggestion with detailed reasoning
|
|
122
|
+
# """
|
|
123
|
+
# result = await suggest_deadline(todo_id)
|
|
124
|
+
|
|
125
|
+
# # Add tool-specific hints for AI agents to better understand response format
|
|
126
|
+
# try:
|
|
127
|
+
# data = json.loads(result)
|
|
128
|
+
# if data.get("success") and "data" in data:
|
|
129
|
+
# deadline_data = data["data"]
|
|
130
|
+
# # Add usage examples if not already present
|
|
131
|
+
# if "ai_agent_hints" not in deadline_data:
|
|
132
|
+
# deadline_data["ai_agent_hints"] = {
|
|
133
|
+
# "explanation": "This suggests a deadline of " +
|
|
134
|
+
# deadline_data.get("suggested_deadline", {}).get("date", "unknown") +
|
|
135
|
+
# " for the todo item, based on its priority and content analysis.",
|
|
136
|
+
# "reasoning_breakdown": "The reasoning field explains how the deadline was determined, including base priority rules, keyword modifiers, and weekend adjustments.",
|
|
137
|
+
# "response_formats": [
|
|
138
|
+
# "I suggest completing this task by {suggested_deadline.date} ({suggested_deadline.day_of_week}), which is {suggested_deadline.days_from_now} days from now.",
|
|
139
|
+
# "Based on this being a {todo_priority} priority task, I recommend a deadline of {suggested_deadline.date}.",
|
|
140
|
+
# "The deadline of {suggested_deadline.date} was chosen because: {reasoning.summary}"
|
|
141
|
+
# ]
|
|
142
|
+
# }
|
|
143
|
+
# data["data"] = deadline_data
|
|
144
|
+
# result = json.dumps(data)
|
|
145
|
+
# except Exception as e:
|
|
146
|
+
# print(f"Error enhancing deadline response: {str(e)}")
|
|
147
|
+
|
|
148
|
+
# return result
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
# @register_tool_once
|
|
152
|
+
# async def suggest_time_slot_tool(todo_id: str, date: Optional[str] = None) -> str:
|
|
153
|
+
# """
|
|
154
|
+
# Suggest an optimal time slot for completing a specific todo.
|
|
155
|
+
|
|
156
|
+
# This tool analyzes completed todos to find patterns in when similar tasks
|
|
157
|
+
# are typically completed, then suggests an optimal time slot:
|
|
158
|
+
# 1. Based on historical completion patterns for similar tasks
|
|
159
|
+
# 2. Considering the priority of the task (high priority = morning slots)
|
|
160
|
+
# 3. Using appropriate duration based on task priority
|
|
161
|
+
|
|
162
|
+
# Args:
|
|
163
|
+
# todo_id: ID of the todo to schedule
|
|
164
|
+
# date: Optional specific date in YYYY-MM-DD format
|
|
165
|
+
|
|
166
|
+
# Returns:
|
|
167
|
+
# A JSON string containing the time slot suggestion with reasoning
|
|
168
|
+
# """
|
|
169
|
+
# return await suggest_time_slot(todo_id, date)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# @register_tool_once
|
|
173
|
+
# async def generate_daily_schedule_tool(date: Optional[str] = None) -> str:
|
|
174
|
+
# """
|
|
175
|
+
# Generate an optimized daily schedule based on pending todos.
|
|
176
|
+
|
|
177
|
+
# This tool creates a complete daily schedule by:
|
|
178
|
+
# 1. Prioritizing tasks based on their importance
|
|
179
|
+
# 2. Allocating appropriate time slots with breaks between tasks
|
|
180
|
+
# 3. Ensuring the schedule respects working hours
|
|
181
|
+
# 4. Limiting the number of tasks to a reasonable amount per day
|
|
182
|
+
|
|
183
|
+
# Args:
|
|
184
|
+
# date: Optional specific date in YYYY-MM-DD format (defaults to tomorrow)
|
|
185
|
+
|
|
186
|
+
# Returns:
|
|
187
|
+
# A JSON string containing the complete suggested schedule
|
|
188
|
+
# """
|
|
189
|
+
# return await generate_daily_schedule(date)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class TodoScheduler:
|
|
194
|
+
"""AI-powered Todo Scheduler that suggests optimal times for tasks"""
|
|
195
|
+
|
|
196
|
+
def __init__(self):
|
|
197
|
+
"""Initialize the Todo Scheduler"""
|
|
198
|
+
self.completed_todos = []
|
|
199
|
+
self.pending_todos = []
|
|
200
|
+
self.completion_patterns = {}
|
|
201
|
+
self.scheduled_slots = []
|
|
202
|
+
self.last_refresh = None
|
|
203
|
+
logger.info("Todo Scheduler initialized")
|
|
204
|
+
|
|
205
|
+
def refresh_data(self) -> None:
|
|
206
|
+
"""Fetch fresh todo data from the database"""
|
|
207
|
+
# Use the assistant to get todo data since it already has the logic
|
|
208
|
+
todo_assistant.refresh_data()
|
|
209
|
+
self.completed_todos = todo_assistant.completed_todos
|
|
210
|
+
self.pending_todos = todo_assistant.pending_todos
|
|
211
|
+
self.analyze_completion_patterns()
|
|
212
|
+
self.last_refresh = datetime.now(UTC)
|
|
213
|
+
logger.info("Scheduler refreshed data from Todo Assistant")
|
|
214
|
+
|
|
215
|
+
def analyze_completion_patterns(self) -> Dict[int, List[int]]:
|
|
216
|
+
"""
|
|
217
|
+
Analyze when todos are typically completed to identify optimal work times
|
|
218
|
+
|
|
219
|
+
Returns:
|
|
220
|
+
Dictionary mapping weekdays to hour frequencies
|
|
221
|
+
"""
|
|
222
|
+
patterns = defaultdict(lambda: defaultdict(int))
|
|
223
|
+
|
|
224
|
+
# Analyze completion times from completed todos
|
|
225
|
+
for todo in self.completed_todos:
|
|
226
|
+
if todo.get("completed_at"):
|
|
227
|
+
# Convert timestamp to datetime
|
|
228
|
+
try:
|
|
229
|
+
completed_time = datetime.fromtimestamp(todo.get("completed_at"), UTC)
|
|
230
|
+
weekday = completed_time.weekday() # 0-6 (Monday is 0)
|
|
231
|
+
hour = completed_time.hour
|
|
232
|
+
|
|
233
|
+
# Increment count for this weekday+hour
|
|
234
|
+
patterns[weekday][hour] += 1
|
|
235
|
+
except (TypeError, ValueError) as e:
|
|
236
|
+
logger.warning(f"Invalid timestamp in todo {todo.get('id')}: {e}")
|
|
237
|
+
|
|
238
|
+
# Store the results
|
|
239
|
+
self.completion_patterns = dict(patterns)
|
|
240
|
+
|
|
241
|
+
logger.info(f"Analyzed completion patterns across {len(self.completed_todos)} todos")
|
|
242
|
+
return self.completion_patterns
|
|
243
|
+
|
|
244
|
+
def suggest_deadline(self, todo_id: str) -> Dict[str, Any]:
|
|
245
|
+
"""
|
|
246
|
+
Suggest a deadline for a specific todo
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
todo_id: ID of the todo to suggest deadline for
|
|
250
|
+
|
|
251
|
+
Returns:
|
|
252
|
+
Dictionary with deadline suggestion and reasoning
|
|
253
|
+
"""
|
|
254
|
+
if not self.pending_todos or self.last_refresh is None or (datetime.now(UTC) - self.last_refresh) > timedelta(minutes=30):
|
|
255
|
+
self.refresh_data()
|
|
256
|
+
|
|
257
|
+
# Find the specific todo
|
|
258
|
+
todo = next((t for t in self.pending_todos if t.get("id") == todo_id), None)
|
|
259
|
+
if not todo:
|
|
260
|
+
# Try to get it directly from the database
|
|
261
|
+
todo = collection.find_one({"id": todo_id})
|
|
262
|
+
if not todo:
|
|
263
|
+
logger.warning(f"Todo {todo_id} not found for deadline suggestion")
|
|
264
|
+
return {
|
|
265
|
+
"status": "error",
|
|
266
|
+
"message": "Todo not found"
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
priority = todo.get("priority", "medium")
|
|
270
|
+
description = todo.get("description", "")
|
|
271
|
+
|
|
272
|
+
# Get estimated completion time from AI assistant if available
|
|
273
|
+
completion_estimate = None
|
|
274
|
+
try:
|
|
275
|
+
# Find similar completed todos
|
|
276
|
+
similar_todos = todo_assistant.recommend_priorities()
|
|
277
|
+
for rec in similar_todos:
|
|
278
|
+
if rec.get("todo_id") == todo_id:
|
|
279
|
+
# This todo has similar completed todos
|
|
280
|
+
completion_estimate = True
|
|
281
|
+
break
|
|
282
|
+
except Exception as e:
|
|
283
|
+
logger.warning(f"Error getting similar todos: {e}")
|
|
284
|
+
|
|
285
|
+
# Base deadline on priority
|
|
286
|
+
deadline_days = PRIORITY_DEADLINES.get(priority, 7)
|
|
287
|
+
|
|
288
|
+
# Adjust deadline based on various factors
|
|
289
|
+
if "urgent" in description.lower() or "asap" in description.lower():
|
|
290
|
+
deadline_days = max(1, deadline_days - 1)
|
|
291
|
+
reason = "urgent language in description"
|
|
292
|
+
elif "next week" in description.lower():
|
|
293
|
+
deadline_days = 7
|
|
294
|
+
reason = "explicit 'next week' in description"
|
|
295
|
+
elif "tomorrow" in description.lower():
|
|
296
|
+
deadline_days = 1
|
|
297
|
+
reason = "explicit 'tomorrow' in description"
|
|
298
|
+
else:
|
|
299
|
+
reason = f"standard deadline for {priority} priority"
|
|
300
|
+
|
|
301
|
+
# Calculate the deadline date
|
|
302
|
+
now = datetime.now(UTC)
|
|
303
|
+
deadline_date = now + timedelta(days=deadline_days)
|
|
304
|
+
|
|
305
|
+
# Ensure deadline falls on a working day
|
|
306
|
+
while deadline_date.weekday() > 4: # If it's a weekend
|
|
307
|
+
deadline_date += timedelta(days=1) # Move to next day
|
|
308
|
+
|
|
309
|
+
# Format for response
|
|
310
|
+
formatted_deadline = deadline_date.strftime("%Y-%m-%d")
|
|
311
|
+
timestamp_deadline = int(deadline_date.timestamp())
|
|
312
|
+
|
|
313
|
+
result = {
|
|
314
|
+
"status": "success",
|
|
315
|
+
"todo_id": todo_id,
|
|
316
|
+
"suggested_deadline": {
|
|
317
|
+
"date": formatted_deadline,
|
|
318
|
+
"timestamp": timestamp_deadline,
|
|
319
|
+
"days_from_now": deadline_days
|
|
320
|
+
},
|
|
321
|
+
"reasoning": reason,
|
|
322
|
+
"priority": priority
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
logger.info(f"Suggested deadline for todo {todo_id}: {formatted_deadline} ({reason})")
|
|
326
|
+
return result
|
|
327
|
+
|
|
328
|
+
def suggest_time_slot(self, todo_id: str, date: Optional[str] = None) -> Dict[str, Any]:
|
|
329
|
+
"""
|
|
330
|
+
Suggest an optimal time slot for completing a todo
|
|
331
|
+
|
|
332
|
+
Args:
|
|
333
|
+
todo_id: ID of the todo to schedule
|
|
334
|
+
date: Optional specific date in YYYY-MM-DD format
|
|
335
|
+
|
|
336
|
+
Returns:
|
|
337
|
+
Dictionary with time slot suggestion and reasoning
|
|
338
|
+
"""
|
|
339
|
+
if not self.pending_todos or not self.completion_patterns:
|
|
340
|
+
self.refresh_data()
|
|
341
|
+
|
|
342
|
+
# Find the specific todo
|
|
343
|
+
todo = next((t for t in self.pending_todos if t.get("id") == todo_id), None)
|
|
344
|
+
if not todo:
|
|
345
|
+
# Try to get it directly from the database
|
|
346
|
+
todo = collection.find_one({"id": todo_id})
|
|
347
|
+
if not todo:
|
|
348
|
+
logger.warning(f"Todo {todo_id} not found for time slot suggestion")
|
|
349
|
+
return {
|
|
350
|
+
"status": "error",
|
|
351
|
+
"message": "Todo not found"
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
priority = todo.get("priority", "medium")
|
|
355
|
+
|
|
356
|
+
# Parse date if provided, otherwise use tomorrow
|
|
357
|
+
try:
|
|
358
|
+
if date:
|
|
359
|
+
target_date = datetime.strptime(date, "%Y-%m-%d").replace(tzinfo=UTC)
|
|
360
|
+
else:
|
|
361
|
+
# Default to tomorrow
|
|
362
|
+
target_date = (datetime.now(UTC) + timedelta(days=1))
|
|
363
|
+
# Ensure it's set to midnight for consistency
|
|
364
|
+
target_date = target_date.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
365
|
+
except ValueError:
|
|
366
|
+
logger.warning(f"Invalid date format: {date}")
|
|
367
|
+
return {
|
|
368
|
+
"status": "error",
|
|
369
|
+
"message": "Invalid date format. Use YYYY-MM-DD."
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
weekday = target_date.weekday()
|
|
373
|
+
|
|
374
|
+
# Check if this is a working day
|
|
375
|
+
working_hours = WORKING_HOURS.get(weekday, [])
|
|
376
|
+
if not working_hours:
|
|
377
|
+
return {
|
|
378
|
+
"status": "error",
|
|
379
|
+
"message": f"The selected date ({target_date.strftime('%Y-%m-%d')}) is not a working day."
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
# Determine task duration based on priority
|
|
383
|
+
duration_minutes = PRIORITY_DURATION.get(priority, 90)
|
|
384
|
+
|
|
385
|
+
# Find the optimal time slot based on completion patterns
|
|
386
|
+
weekday_patterns = self.completion_patterns.get(weekday, {})
|
|
387
|
+
|
|
388
|
+
# Default working hours for this day
|
|
389
|
+
start_time = time(working_hours[0][0], working_hours[0][1])
|
|
390
|
+
end_time = time(working_hours[1][0], working_hours[1][1])
|
|
391
|
+
|
|
392
|
+
# Convert to datetime objects for the target date
|
|
393
|
+
start_datetime = datetime.combine(target_date.date(), start_time).replace(tzinfo=UTC)
|
|
394
|
+
end_datetime = datetime.combine(target_date.date(), end_time).replace(tzinfo=UTC)
|
|
395
|
+
|
|
396
|
+
# If we have completion patterns, use them to find optimal time
|
|
397
|
+
if weekday_patterns:
|
|
398
|
+
# Find the hour with the most completions
|
|
399
|
+
best_hour = max(weekday_patterns.items(), key=lambda x: x[1])[0]
|
|
400
|
+
|
|
401
|
+
# Create a time slot at this hour
|
|
402
|
+
slot_start = datetime.combine(target_date.date(), time(best_hour, 0)).replace(tzinfo=UTC)
|
|
403
|
+
|
|
404
|
+
# Ensure the slot is within working hours
|
|
405
|
+
if slot_start < start_datetime:
|
|
406
|
+
slot_start = start_datetime
|
|
407
|
+
elif slot_start > end_datetime - timedelta(minutes=duration_minutes):
|
|
408
|
+
# If the best hour is too late, use an earlier time
|
|
409
|
+
slot_start = end_datetime - timedelta(minutes=duration_minutes)
|
|
410
|
+
|
|
411
|
+
reason = f"historically productive time on {calendar.day_name[weekday]}s"
|
|
412
|
+
else:
|
|
413
|
+
# Without patterns, suggest morning for high priority, afternoon for others
|
|
414
|
+
if priority == "high":
|
|
415
|
+
# Morning slot
|
|
416
|
+
slot_start = start_datetime + timedelta(hours=1) # 1 hour after start
|
|
417
|
+
reason = "high priority tasks are best done in the morning"
|
|
418
|
+
else:
|
|
419
|
+
# Afternoon slot
|
|
420
|
+
slot_start = start_datetime + timedelta(hours=(end_datetime.hour - start_datetime.hour) // 2)
|
|
421
|
+
reason = f"balanced time slot for {priority} priority tasks"
|
|
422
|
+
|
|
423
|
+
# Calculate end time
|
|
424
|
+
slot_end = slot_start + timedelta(minutes=duration_minutes)
|
|
425
|
+
|
|
426
|
+
# Format times for response
|
|
427
|
+
formatted_start = slot_start.strftime("%Y-%m-%d %H:%M")
|
|
428
|
+
formatted_end = slot_end.strftime("%Y-%m-%d %H:%M")
|
|
429
|
+
|
|
430
|
+
result = {
|
|
431
|
+
"status": "success",
|
|
432
|
+
"todo_id": todo_id,
|
|
433
|
+
"suggested_time_slot": {
|
|
434
|
+
"date": target_date.strftime("%Y-%m-%d"),
|
|
435
|
+
"start_time": formatted_start,
|
|
436
|
+
"end_time": formatted_end,
|
|
437
|
+
"duration_minutes": duration_minutes
|
|
438
|
+
},
|
|
439
|
+
"reasoning": reason,
|
|
440
|
+
"priority": priority
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
logger.info(f"Suggested time slot for todo {todo_id}: {formatted_start} - {formatted_end} ({reason})")
|
|
444
|
+
return result
|
|
445
|
+
|
|
446
|
+
def generate_daily_schedule(self, target_date: Optional[str] = None) -> Dict[str, Any]:
|
|
447
|
+
"""
|
|
448
|
+
Generate a suggested daily schedule with optimal task ordering
|
|
449
|
+
|
|
450
|
+
Args:
|
|
451
|
+
target_date: Optional specific date in YYYY-MM-DD format
|
|
452
|
+
|
|
453
|
+
Returns:
|
|
454
|
+
Dictionary with suggested schedule
|
|
455
|
+
"""
|
|
456
|
+
if not self.pending_todos:
|
|
457
|
+
self.refresh_data()
|
|
458
|
+
|
|
459
|
+
# Parse date if provided, otherwise use tomorrow
|
|
460
|
+
try:
|
|
461
|
+
if target_date:
|
|
462
|
+
date_obj = datetime.strptime(target_date, "%Y-%m-%d").replace(tzinfo=UTC)
|
|
463
|
+
else:
|
|
464
|
+
# Default to tomorrow
|
|
465
|
+
date_obj = (datetime.now(UTC) + timedelta(days=1))
|
|
466
|
+
# Ensure it's set to midnight for consistency
|
|
467
|
+
date_obj = date_obj.replace(hour=0, minute=0, second=0, microsecond=0)
|
|
468
|
+
except ValueError:
|
|
469
|
+
logger.warning(f"Invalid date format: {target_date}")
|
|
470
|
+
return {
|
|
471
|
+
"status": "error",
|
|
472
|
+
"message": "Invalid date format. Use YYYY-MM-DD."
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
weekday = date_obj.weekday()
|
|
476
|
+
date_str = date_obj.strftime("%Y-%m-%d")
|
|
477
|
+
|
|
478
|
+
# Check if this is a working day
|
|
479
|
+
working_hours = WORKING_HOURS.get(weekday, [])
|
|
480
|
+
if not working_hours:
|
|
481
|
+
return {
|
|
482
|
+
"status": "error",
|
|
483
|
+
"message": f"The selected date ({date_str}) is not a working day."
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
# Start and end times for the workday
|
|
487
|
+
start_time = time(working_hours[0][0], working_hours[0][1])
|
|
488
|
+
end_time = time(working_hours[1][0], working_hours[1][1])
|
|
489
|
+
|
|
490
|
+
# Convert to datetime objects for the target date
|
|
491
|
+
start_datetime = datetime.combine(date_obj.date(), start_time).replace(tzinfo=UTC)
|
|
492
|
+
end_datetime = datetime.combine(date_obj.date(), end_time).replace(tzinfo=UTC)
|
|
493
|
+
|
|
494
|
+
# Calculate total available minutes
|
|
495
|
+
available_minutes = (end_datetime - start_datetime).seconds // 60
|
|
496
|
+
|
|
497
|
+
# Sort pending todos by priority
|
|
498
|
+
priority_rank = {"high": 0, "medium": 1, "low": 2, "initial": 1}
|
|
499
|
+
sorted_todos = sorted(
|
|
500
|
+
self.pending_todos,
|
|
501
|
+
key=lambda x: priority_rank.get(x.get("priority", "medium"), 999)
|
|
502
|
+
)
|
|
503
|
+
|
|
504
|
+
# Limit to a reasonable number of tasks per day
|
|
505
|
+
max_todos = min(5, len(sorted_todos))
|
|
506
|
+
selected_todos = sorted_todos[:max_todos]
|
|
507
|
+
|
|
508
|
+
# Build the schedule
|
|
509
|
+
schedule = []
|
|
510
|
+
current_time = start_datetime
|
|
511
|
+
total_scheduled_minutes = 0
|
|
512
|
+
|
|
513
|
+
for todo in selected_todos:
|
|
514
|
+
todo_id = todo.get("id")
|
|
515
|
+
priority = todo.get("priority", "medium")
|
|
516
|
+
description = todo.get("description", "")
|
|
517
|
+
|
|
518
|
+
# Determine task duration
|
|
519
|
+
duration_minutes = PRIORITY_DURATION.get(priority, 90)
|
|
520
|
+
|
|
521
|
+
# Check if we have enough time left
|
|
522
|
+
if total_scheduled_minutes + duration_minutes > available_minutes:
|
|
523
|
+
# Not enough time left today
|
|
524
|
+
continue
|
|
525
|
+
|
|
526
|
+
# Add a 15-minute break between tasks
|
|
527
|
+
if schedule: # if not the first task
|
|
528
|
+
current_time += timedelta(minutes=15)
|
|
529
|
+
total_scheduled_minutes += 15
|
|
530
|
+
|
|
531
|
+
# Calculate end time
|
|
532
|
+
end_time = current_time + timedelta(minutes=duration_minutes)
|
|
533
|
+
|
|
534
|
+
# Add to schedule
|
|
535
|
+
schedule.append({
|
|
536
|
+
"todo_id": todo_id,
|
|
537
|
+
"description": description,
|
|
538
|
+
"priority": priority,
|
|
539
|
+
"start_time": current_time.strftime("%H:%M"),
|
|
540
|
+
"end_time": end_time.strftime("%H:%M"),
|
|
541
|
+
"duration_minutes": duration_minutes
|
|
542
|
+
})
|
|
543
|
+
|
|
544
|
+
# Update current time and total scheduled minutes
|
|
545
|
+
current_time = end_time
|
|
546
|
+
total_scheduled_minutes += duration_minutes
|
|
547
|
+
|
|
548
|
+
result = {
|
|
549
|
+
"status": "success",
|
|
550
|
+
"date": date_str,
|
|
551
|
+
"weekday": calendar.day_name[weekday],
|
|
552
|
+
"working_hours": {
|
|
553
|
+
"start": start_time.strftime("%H:%M"),
|
|
554
|
+
"end": end_time.strftime("%H:%M")
|
|
555
|
+
},
|
|
556
|
+
"schedule": schedule,
|
|
557
|
+
"total_tasks": len(schedule),
|
|
558
|
+
"total_scheduled_minutes": total_scheduled_minutes,
|
|
559
|
+
"available_minutes": available_minutes,
|
|
560
|
+
"utilization_percentage": round((total_scheduled_minutes / available_minutes) * 100, 1) if available_minutes else 0
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
logger.info(f"Generated daily schedule for {date_str} with {len(schedule)} tasks")
|
|
564
|
+
return result
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
# Create singleton instance
|
|
568
|
+
scheduler = TodoScheduler()
|
|
569
|
+
|
|
570
|
+
# async def suggest_deadline(todo_id: str) -> str:
|
|
571
|
+
# """
|
|
572
|
+
# Suggest an optimal deadline for a specific todo based on priority and content analysis.
|
|
573
|
+
#
|
|
574
|
+
# This tool analyzes a todo's priority and description to suggest a reasonable deadline:
|
|
575
|
+
# 1. High priority tasks get shorter deadlines
|
|
576
|
+
# 2. Keywords like "urgent" or "tomorrow" influence the suggestion
|
|
577
|
+
# 3. The deadline always falls on a working day
|
|
578
|
+
#
|
|
579
|
+
# Args:
|
|
580
|
+
# todo_id: ID of the todo to suggest a deadline for
|
|
581
|
+
#
|
|
582
|
+
# Returns:
|
|
583
|
+
# A JSON string containing the deadline suggestion with reasoning
|
|
584
|
+
# """
|
|
585
|
+
# # First get the todo
|
|
586
|
+
# todo_response = await get_todo(todo_id)
|
|
587
|
+
# todo_data = json.loads(todo_response)
|
|
588
|
+
#
|
|
589
|
+
# if not todo_data.get("success"):
|
|
590
|
+
# return create_response(False, message=f"Failed to get todo: {todo_data.get('message', 'Unknown error')}")
|
|
591
|
+
#
|
|
592
|
+
# todo = todo_data.get("data", {})
|
|
593
|
+
#
|
|
594
|
+
# # Define deadline recommendations based on priority
|
|
595
|
+
# priority_deadlines = {
|
|
596
|
+
# "high": {"days": 2, "explanation": "High priority tasks should be completed quickly"},
|
|
597
|
+
# "medium": {"days": 5, "explanation": "Medium priority tasks can be scheduled within a week"},
|
|
598
|
+
# "low": {"days": 10, "explanation": "Low priority tasks can be scheduled within two weeks"},
|
|
599
|
+
# "initial": {"days": 7, "explanation": "Tasks with initial priority are assumed to be medium importance"}
|
|
600
|
+
# }
|
|
601
|
+
#
|
|
602
|
+
# # Extract relevant information
|
|
603
|
+
# priority = todo.get("priority", "initial")
|
|
604
|
+
# description = todo.get("description", "")
|
|
605
|
+
#
|
|
606
|
+
# # Start with the base deadline from priority
|
|
607
|
+
# base_days = priority_deadlines.get(priority, {"days": 7, "explanation": "Default deadline for unknown priority"})
|
|
608
|
+
# deadline_days = base_days["days"]
|
|
609
|
+
# reasoning = [base_days["explanation"]]
|
|
610
|
+
#
|
|
611
|
+
# # Analyze description for keywords that might affect deadline
|
|
612
|
+
# deadline_modifiers = []
|
|
613
|
+
#
|
|
614
|
+
# # Check for urgency indicators
|
|
615
|
+
# urgency_keywords = {
|
|
616
|
+
# "urgent": {"modifier": -1, "explanation": "Task description indicates urgency"},
|
|
617
|
+
# "asap": {"modifier": -2, "explanation": "ASAP indicator suggests highest urgency"},
|
|
618
|
+
# "emergency": {"modifier": -3, "explanation": "Emergency tasks require immediate attention"},
|
|
619
|
+
# "critical": {"modifier": -2, "explanation": "Critical tasks need prompt attention"},
|
|
620
|
+
# "immediate": {"modifier": -2, "explanation": "Immediate action required"}
|
|
621
|
+
# }
|
|
622
|
+
#
|
|
623
|
+
# for keyword, info in urgency_keywords.items():
|
|
624
|
+
# if keyword in description.lower():
|
|
625
|
+
# deadline_days = max(1, deadline_days + info["modifier"])
|
|
626
|
+
# deadline_modifiers.append({"type": "urgency", "keyword": keyword, "days_changed": info["modifier"]})
|
|
627
|
+
# reasoning.append(info["explanation"])
|
|
628
|
+
#
|
|
629
|
+
# # Check for explicit timeframes
|
|
630
|
+
# timeframe_patterns = {
|
|
631
|
+
# "tomorrow": {"days": 1, "explanation": "Task explicitly mentions it's needed tomorrow"},
|
|
632
|
+
# "next week": {"days": 7, "explanation": "Task is specifically scheduled for next week"},
|
|
633
|
+
# "next month": {"days": 30, "explanation": "Task is scheduled for next month"},
|
|
634
|
+
# "by end of week": {"days": 5, "explanation": "Task needs to be completed by the end of this week"},
|
|
635
|
+
# "by end of day": {"days": 1, "explanation": "Task must be completed today"}
|
|
636
|
+
# }
|
|
637
|
+
#
|
|
638
|
+
# for phrase, info in timeframe_patterns.items():
|
|
639
|
+
# if phrase in description.lower():
|
|
640
|
+
# original_days = deadline_days
|
|
641
|
+
# deadline_days = info["days"]
|
|
642
|
+
# deadline_modifiers.append({
|
|
643
|
+
# "type": "explicit_timeframe",
|
|
644
|
+
# "keyword": phrase,
|
|
645
|
+
# "days_changed": deadline_days - original_days
|
|
646
|
+
# })
|
|
647
|
+
# reasoning.append(info["explanation"])
|
|
648
|
+
# # If we find an explicit timeframe, it overrides other considerations
|
|
649
|
+
# break
|
|
650
|
+
#
|
|
651
|
+
# # Calculate the deadline date
|
|
652
|
+
# now = datetime.now(UTC)
|
|
653
|
+
# deadline_date = now + timedelta(days=deadline_days)
|
|
654
|
+
#
|
|
655
|
+
# # Ensure deadline falls on a working day (Mon-Fri)
|
|
656
|
+
# weekend_adjustment = 0
|
|
657
|
+
# if deadline_date.weekday() > 4: # If it's a weekend
|
|
658
|
+
# # Move to next Monday
|
|
659
|
+
# days_to_monday = 7 - deadline_date.weekday()
|
|
660
|
+
# deadline_date += timedelta(days=days_to_monday)
|
|
661
|
+
# weekend_adjustment = days_to_monday
|
|
662
|
+
# reasoning.append(f"Adjusted deadline to next business day (moved {days_to_monday} days forward)")
|
|
663
|
+
#
|
|
664
|
+
# # Format for response
|
|
665
|
+
# formatted_deadline = deadline_date.strftime("%Y-%m-%d")
|
|
666
|
+
# timestamp_deadline = int(deadline_date.timestamp())
|
|
667
|
+
#
|
|
668
|
+
# result = {
|
|
669
|
+
# "todo_id": todo_id,
|
|
670
|
+
# "todo_description": description[:100] + ("..." if len(description) > 100 else ""),
|
|
671
|
+
# "todo_priority": priority,
|
|
672
|
+
# "suggested_deadline": {
|
|
673
|
+
# "date": formatted_deadline,
|
|
674
|
+
# "day_of_week": deadline_date.strftime("%A"),
|
|
675
|
+
# "timestamp": timestamp_deadline,
|
|
676
|
+
# "days_from_now": deadline_days + weekend_adjustment
|
|
677
|
+
# },
|
|
678
|
+
# "reasoning": {
|
|
679
|
+
# "summary": "; ".join(reasoning),
|
|
680
|
+
# "base_deadline": {
|
|
681
|
+
# "days": base_days["days"],
|
|
682
|
+
# "explanation": base_days["explanation"]
|
|
683
|
+
# },
|
|
684
|
+
# "modifiers": deadline_modifiers,
|
|
685
|
+
# "weekend_adjustment": weekend_adjustment
|
|
686
|
+
# },
|
|
687
|
+
# "possible_next_actions": ["update_todo", "mark_todo_complete", "suggest_time_slot"]
|
|
688
|
+
# }
|
|
689
|
+
#
|
|
690
|
+
# # MQTT publish as confirmation after generating a deadline suggestion
|
|
691
|
+
# try:
|
|
692
|
+
# mqtt_message = f"todo_id: {todo_id}, deadline: {formatted_deadline}"
|
|
693
|
+
# await mqtt_publish(f"status/{os.getenv('DeNa')}/omnispindle/suggest_deadline", mqtt_message)
|
|
694
|
+
# except Exception as e:
|
|
695
|
+
# # Log the error but don't fail the entire operation
|
|
696
|
+
# print(f"MQTT publish error (non-fatal): {str(e)}")
|
|
697
|
+
#
|
|
698
|
+
# return create_response(True, result)
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
async def suggest_deadline(todo_id: str) -> str:
|
|
702
|
+
"""
|
|
703
|
+
Suggest a deadline for a specific todo
|
|
704
|
+
|
|
705
|
+
Args:
|
|
706
|
+
todo_id: ID of the todo to suggest deadline for
|
|
707
|
+
|
|
708
|
+
Returns:
|
|
709
|
+
JSON string with deadline suggestion
|
|
710
|
+
"""
|
|
711
|
+
try:
|
|
712
|
+
result = scheduler.suggest_deadline(todo_id)
|
|
713
|
+
await mqtt_publish(f"status/{os.getenv('DeNa')}/suggest_deadline", json.dumps({"todo_id": todo_id, "result": result}))
|
|
714
|
+
return json.dumps(result)
|
|
715
|
+
except Exception as e:
|
|
716
|
+
logger.error(f"Error suggesting deadline for todo {todo_id}: {e}")
|
|
717
|
+
return json.dumps({"status": "error", "message": str(e)})
|
|
718
|
+
|
|
719
|
+
|
|
720
|
+
async def suggest_time_slot(todo_id: str, date: Optional[str] = None) -> str:
|
|
721
|
+
"""
|
|
722
|
+
Suggest an optimal time slot for completing a todo
|
|
723
|
+
|
|
724
|
+
Args:
|
|
725
|
+
todo_id: ID of the todo to schedule
|
|
726
|
+
date: Optional specific date in YYYY-MM-DD format
|
|
727
|
+
|
|
728
|
+
Returns:
|
|
729
|
+
JSON string with time slot suggestion
|
|
730
|
+
"""
|
|
731
|
+
try:
|
|
732
|
+
result = scheduler.suggest_time_slot(todo_id, date)
|
|
733
|
+
await mqtt_publish(f"status/{os.getenv('DeNa')}/suggest_time_slot", json.dumps({"todo_id": todo_id, "date": date, "result": result}))
|
|
734
|
+
return json.dumps(result)
|
|
735
|
+
except Exception as e:
|
|
736
|
+
logger.error(f"Error suggesting time slot for todo {todo_id}: {e}")
|
|
737
|
+
return json.dumps({"status": "error", "message": str(e)})
|
|
738
|
+
|
|
739
|
+
|
|
740
|
+
async def generate_daily_schedule(date: Optional[str] = None) -> str:
|
|
741
|
+
"""
|
|
742
|
+
Generate a suggested daily schedule with optimal task ordering
|
|
743
|
+
|
|
744
|
+
Args:
|
|
745
|
+
date: Optional specific date in YYYY-MM-DD format
|
|
746
|
+
|
|
747
|
+
Returns:
|
|
748
|
+
JSON string with suggested schedule
|
|
749
|
+
"""
|
|
750
|
+
try:
|
|
751
|
+
result = scheduler.generate_daily_schedule(date)
|
|
752
|
+
await mqtt_publish(f"status/{os.getenv('DeNa')}/generate_daily_schedule", json.dumps({"date": date, "result": result}))
|
|
753
|
+
return json.dumps(result)
|
|
754
|
+
except Exception as e:
|
|
755
|
+
logger.error(f"Error generating daily schedule: {e}")
|
|
756
|
+
return json.dumps({"status": "error", "message": str(e)})
|