Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(tasks): add scheduled task pipeline
cyhc68a7c79e04f
diff --git a/core/controller.py b/core/controller.pyindex 312493d10..cc04d4721 100644--- a/core/controller.py+++ b/core/controller.py@@ -23,6 +23,7 @@ from core.handlers import (MessageHandler,)from core.message_dispatcher import ConsolidatedMessageDispatcher+from core.scheduled_tasks import ScheduledTaskServicefrom core.update_checker import UpdateCheckerfrom vibe.i18n import get_supported_languages, t as i18n_t@@ -64,6 +65,7 @@ class Controller:# Consolidated message dispatcherself.message_dispatcher = ConsolidatedMessageDispatcher(self)+ self.scheduled_task_service = ScheduledTaskService(self)# Background task for cleanupself.cleanup_task: Optional[asyncio.Task] = None@@ -373,6 +375,11 @@ class Controller:except Exception as e:logger.error(f"Failed to start update checker: {e}", exc_info=True)+ try:+ self.scheduled_task_service.start()+ except Exception as e:+ logger.error("Failed to start scheduled task service: %s", e, exc_info=True)+# Utility methods used by handlersdef get_cwd(self, context: MessageContext) -> str:@@ -510,7 +517,7 @@ class Controller:parse_mode: Optional[str] = "markdown",):"""Backward-compatible entrypoint; delegated to message dispatcher."""- await self.message_dispatcher.emit_agent_message(+ return await self.message_dispatcher.emit_agent_message(context=context,message_type=message_type,text=text,@@ -566,6 +573,14 @@ class Controller:except Exception as e:logger.debug(f"Update checker cleanup skipped: {e}")+ try:+ loop = self._loop+ if loop and not loop.is_closed():+ future = asyncio.run_coroutine_threadsafe(self.scheduled_task_service.stop(), loop)+ future.result(timeout=5)+ except Exception as e:+ logger.debug(f"Scheduled task service cleanup skipped: {e}")+# Cancel receiver tasks without awaiting (they may belong to other loops)try:for session_id, task in list(self.receiver_tasks.items()):diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex aaa2b70df..57ab116c7 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -16,6 +16,9 @@ logger = logging.getLogger(__name__)class MessageHandler(BaseHandler):"""Handles message routing and Claude communication"""+ TURN_SOURCE_HUMAN = "human"+ TURN_SOURCE_SCHEDULED = "scheduled"+def __init__(self, controller):"""Initialize with reference to main controller"""super().__init__(controller)@@ -94,50 +97,94 @@ class MessageHandler(BaseHandler):return ack_reaction_message_id, ack_reaction_emoji, False, Noneasync def handle_user_message(self, context: MessageContext, message: str):- """Process regular user messages and route to configured agent"""+ """Process regular human-originated messages and route to configured agent."""+ await self._handle_turn(context, message, source=self.TURN_SOURCE_HUMAN)++ async def handle_scheduled_message(self, context: MessageContext, message: str, parsed_session_key=None):+ """Process a scheduler-originated turn through the shared turn pipeline."""+ if parsed_session_key is not None:+ payload = dict(context.platform_specific or {})+ payload["parsed_session_key"] = parsed_session_key+ context.platform_specific = payload+ await self._handle_turn(context, message, source=self.TURN_SOURCE_SCHEDULED)++ async def _prepare_turn_context(self, context: MessageContext, source: str) -> MessageContext:+ payload = dict(context.platform_specific or {})+ payload["turn_source"] = source+ context.platform_specific = payload+ prepared = await self._get_im_client(context).prepare_turn_context(context, source)+ prepared_payload = dict(prepared.platform_specific or {})+ prepared_payload["turn_source"] = source+ prepared.platform_specific = prepared_payload+ return prepared++ async def _handle_turn(self, context: MessageContext, message: str, *, source: str):+ """Shared turn-processing pipeline used by both human and scheduled turns."""ack_reaction_message_id = Noneack_reaction_emoji = Nonetyping_indicator_active = Falsetyping_indicator_task = Nonetry:+ is_human = source == self.TURN_SOURCE_HUMAN+# Record user activity for auto-update idle detection- if hasattr(self.controller, "update_checker"):+ if is_human and hasattr(self.controller, "update_checker"):self.controller.update_checker.record_activity()# If message is empty AND no files attached (e.g., user just @mentioned bot without text),# trigger the /start command instead of sending empty message to agenthas_files = bool(context.files)if (not message or not message.strip()) and not has_files:- await self.controller.command_handler.handle_start(context, "")+ if is_human:+ await self.controller.command_handler.handle_start(context, "")return- # Deduplication: check if this message has already been processed- # This prevents duplicate processing when vibe-remote restarts and- # Slack resends events- message_ts = context.message_id- thread_ts = context.thread_id or context.message_id- if message_ts and thread_ts:- if self.sessions.is_message_already_processed(context.channel_id, thread_ts, message_ts):- logger.info(- f"Skipping already processed message: channel={context.channel_id}, "- f"thread={thread_ts}, message={message_ts}"- )- return- # Record this message as processed immediately to prevent duplicates- # even if processing fails (we don't want to retry failed messages forever)- self.sessions.record_processed_message(context.channel_id, thread_ts, message_ts)+ if is_human:+ # Deduplication: check if this message has already been processed+ # This prevents duplicate processing when vibe-remote restarts and+ # Slack resends events+ message_ts = context.message_id+ thread_ts = context.thread_id or context.message_id+ if message_ts and thread_ts:+ if self.sessions.is_message_already_processed(context.channel_id, thread_ts, message_ts):+ logger.info(+ f"Skipping already processed message: channel={context.channel_id}, "+ f"thread={thread_ts}, message={message_ts}"+ )+ return+ # Record this message as processed immediately to prevent duplicates+ # even if processing fails (we don't want to retry failed messages forever)+ self.sessions.record_processed_message(context.channel_id, thread_ts, message_ts)# Skip automatic cleanup; receiver tasks are retained until shutdown# Allow "stop" shortcut inside Slack threads- if context.thread_id and message.strip().lower() in ["stop", "/stop"]:+ if is_human and context.thread_id and message.strip().lower() in ["stop", "/stop"]:if await self._handle_inline_stop(context):returnif not self.session_handler:raise RuntimeError("Session handler not initialized")- base_session_id, working_path, composite_key = self.session_handler.get_session_info(context)+ context = await self._prepare_turn_context(context, source)++ base_session_id, working_path, composite_key = self.session_handler.get_session_info(context, source=source)+ payload = dict(context.platform_specific or {})+ payload["turn_source"] = source+ payload["turn_base_session_id"] = base_session_id+ payload["scheduled_anchor_required"] = self.session_handler.should_allocate_scheduled_anchor(+ context, source=source+ )+ context.platform_specific = payload++ reply_anchor_base_session_id = payload.get("reply_anchor_base_session_id")+ if reply_anchor_base_session_id and reply_anchor_base_session_id != base_session_id:+ self.session_handler.alias_session_base(+ context,+ source_base_session_id=reply_anchor_base_session_id,+ alias_base_session_id=base_session_id,+ clear_source=True,+ )settings_key = self._get_settings_key(context)session_key = self._get_session_key(context)@@ -216,24 +263,25 @@ class MessageHandler(BaseHandler):composite_key = f"{base_session_id}:{working_path}"ack_message_id = None- ack_mode = getattr(self.config, "ack_mode", "typing")- effective_ack_mode = "typing" if self._get_context_platform(context) == "wechat" else ack_mode- if effective_ack_mode == "message":- ack_context = self._get_target_context(context)- ack_text = self._get_ack_text(agent_name)- try:- ack_message_id = await self._get_im_client(ack_context).send_message(ack_context, ack_text)- except Exception as ack_err:- logger.debug(f"Failed to send ack message: {ack_err}")- else:- (- ack_reaction_message_id,- ack_reaction_emoji,- typing_indicator_active,- typing_indicator_task,- ) = await self._start_processing_indicator(context)-- if subagent_name and context.message_id:+ if is_human:+ ack_mode = getattr(self.config, "ack_mode", "typing")+ effective_ack_mode = "typing" if self._get_context_platform(context) == "wechat" else ack_mode+ if effective_ack_mode == "message":+ ack_context = self._get_target_context(context)+ ack_text = self._get_ack_text(agent_name)+ try:+ ack_message_id = await self._get_im_client(ack_context).send_message(ack_context, ack_text)+ except Exception as ack_err:+ logger.debug(f"Failed to send ack message: {ack_err}")+ else:+ (+ ack_reaction_message_id,+ ack_reaction_emoji,+ typing_indicator_active,+ typing_indicator_task,+ ) = await self._start_processing_indicator(context)++ if is_human and subagent_name and context.message_id:try:reaction = ":robot_face:"await self._get_im_client(context).add_reaction(@@ -257,7 +305,7 @@ class MessageHandler(BaseHandler):logger.info(f"Processed {len(processed_files)} file attachments for message")# Prepend user identity when include_user_info is enabled- if self.config.include_user_info:+ if is_human and self.config.include_user_info:message = await self._prepend_user_info(context, message)message = self._append_attachment_errors(message, attachment_errors)diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex 53a0bec8b..6041e6e75 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -3,6 +3,7 @@import loggingimport osfrom typing import Optional, Dict, Any, Tuple+from uuid import uuid4from modules.im import MessageContextfrom modules.claude_sdk_compat import ClaudeSDKClient, ClaudeAgentOptionsfrom modules.agents.native_sessions.base import build_resume_preview@@ -23,26 +24,14 @@ class SessionHandler(BaseHandler):self.receiver_tasks = controller.receiver_tasksself.stored_session_mappings = controller.stored_session_mappings- def get_base_session_id(self, context: MessageContext) -> str:+ def get_base_session_id(self, context: MessageContext, source: str = "human") -> str:"""Get base session ID based on platform and context (without path)"""- platform = (- context.platform- or (context.platform_specific or {}).get("platform")- or getattr(self.config, "platform", "slack")- )+ platform = self._get_context_platform(context)is_dm = bool((context.platform_specific or {}).get("is_dm", False))+ if self.should_allocate_scheduled_anchor(context, source=source):+ return f"{platform}_scheduled-{uuid4().hex}"if is_dm:- use_dm_threads = False- getter = getattr(self.controller, "get_im_client_for_context", None)- if callable(getter):- try:- im_client = getter(context)- except AttributeError:- im_client = getattr(self.controller, "im_client", None)- else:- im_client = getattr(self.controller, "im_client", None)- if im_client and hasattr(im_client, "should_use_thread_for_dm_session"):- use_dm_threads = bool(im_client.should_use_thread_for_dm_session())+ use_dm_threads = self._supports_threaded_session(context, is_dm=True)if use_dm_threads:base_id = context.thread_id or context.message_id or context.channel_id or context.user_id@@ -52,6 +41,80 @@ class SessionHandler(BaseHandler):base_id = context.thread_id or context.message_id or context.channel_idreturn f"{platform}_{base_id}"+ def _get_context_platform(self, context: MessageContext) -> str:+ return (+ context.platform+ or (context.platform_specific or {}).get("platform")+ or getattr(self.config, "platform", "slack")+ )++ def should_allocate_scheduled_anchor(self, context: MessageContext, source: str = "human") -> bool:+ if source != "scheduled" or context.thread_id:+ return False+ is_dm = bool((context.platform_specific or {}).get("is_dm", False))+ return self._supports_threaded_session(context, is_dm=is_dm)++ def build_message_anchor_base(self, context: MessageContext, message_id: str) -> str:+ return f"{self._get_context_platform(context)}_{message_id}"++ def alias_session_base(+ self,+ context: MessageContext,+ *,+ source_base_session_id: str,+ alias_base_session_id: str,+ clear_source: bool = False,+ ) -> bool:+ if not source_base_session_id or not alias_base_session_id:+ return False+ session_key = self._get_session_key(context)+ changed = self.sessions.alias_session_base(+ session_key,+ source_base_session_id,+ alias_base_session_id,+ )+ if changed and clear_source and source_base_session_id != alias_base_session_id:+ self.sessions.clear_session_base(session_key, source_base_session_id)+ return changed++ def finalize_scheduled_delivery(self, context: MessageContext, sent_message_id: Optional[str]) -> None:+ payload = context.platform_specific or {}+ if payload.get("turn_source") != "scheduled":+ return+ if context.thread_id or not payload.get("scheduled_anchor_required"):+ return+ if not sent_message_id:+ return++ source_base_session_id = payload.get("turn_base_session_id") or ""+ alias_base_session_id = self.build_message_anchor_base(context, sent_message_id)+ self.alias_session_base(+ context,+ source_base_session_id=source_base_session_id,+ alias_base_session_id=alias_base_session_id,+ clear_source=True,+ )++ platform = self._get_context_platform(context)+ if platform in {"slack", "lark"}:+ self.sessions.mark_thread_active("scheduled", context.channel_id, sent_message_id)++ def _supports_threaded_session(self, context: MessageContext, *, is_dm: bool) -> bool:+ getter = getattr(self.controller, "get_im_client_for_context", None)+ if callable(getter):+ try:+ im_client = getter(context)+ except AttributeError:+ im_client = getattr(self.controller, "im_client", None)+ else:+ im_client = getattr(self.controller, "im_client", None)++ if im_client is None:+ return False+ if is_dm:+ return bool(getattr(im_client, "should_use_thread_for_dm_session", lambda: False)())+ return bool(getattr(im_client, "should_use_thread_for_reply", lambda: False)())+def get_working_path(self, context: MessageContext) -> str:"""Get working directory - delegate to controller's get_cwd"""return self.controller.get_cwd(context)@@ -111,9 +174,9 @@ class SessionHandler(BaseHandler):logger.warning(f"Agent file not found for '{agent_name}' in {search_paths}")return None- def get_session_info(self, context: MessageContext) -> Tuple[str, str, str]:+ def get_session_info(self, context: MessageContext, source: str = "human") -> Tuple[str, str, str]:"""Get session info: base_session_id, working_path, and composite_key"""- base_session_id = self.get_base_session_id(context)+ base_session_id = self.get_base_session_id(context, source=source)working_path = self.get_working_path(context) # Pass context to get user's custom_cwd# Create composite key for internal storagecomposite_key = f"{base_session_id}:{working_path}"diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex fb006980b..7a9c47996 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -144,7 +144,7 @@ class ConsolidatedMessageDispatcher:message_type: str,text: str,parse_mode: Optional[str] = "markdown",- ) -> None:+ ) -> Optional[str]:"""Centralized dispatch for agent messages.Message Types:@@ -154,7 +154,7 @@ class ConsolidatedMessageDispatcher:- Notify Message: notifications, always sent immediately."""if not text or not text.strip():- return+ return Nonesettings_manager = self.controller.get_settings_manager_for_context(context)im_client = self._get_im_client(context)@@ -165,13 +165,14 @@ class ConsolidatedMessageDispatcher:if canonical_type == "notify":target_context = self._get_target_context(context)try:- await im_client.send_message(target_context, text, parse_mode=parse_mode)+ return await im_client.send_message(target_context, text, parse_mode=parse_mode)except Exception as err:logger.error("Failed to send notify message: %s", err)- return+ return Noneif canonical_type == "result":target_context = self._get_target_context(context)+ primary_message_id: Optional[str] = None# --- Reply enhancements: extract file links & quick-reply buttons ---reply_enhancements_on = getattr(self.controller.config, "reply_enhancements", True)@@ -185,7 +186,7 @@ class ConsolidatedMessageDispatcher:if len(display_text) <= self._get_result_max_chars(context):if enhanced and enhanced.buttons and self._supports_quick_replies(context):try:- await self._send_with_quick_replies(+ primary_message_id = await self._send_with_quick_replies(im_client,target_context,display_text,@@ -195,18 +196,20 @@ class ConsolidatedMessageDispatcher:except Exception as err:logger.warning("Failed to send result with quick replies, falling back: %s", err)try:- await im_client.send_message(target_context, display_text, parse_mode=parse_mode)+ primary_message_id = await im_client.send_message(+ target_context, display_text, parse_mode=parse_mode+ )except Exception as fallback_err:logger.error("Failed to send fallback result message: %s", fallback_err)else:try:- await im_client.send_message(target_context, display_text, parse_mode=parse_mode)+ primary_message_id = await im_client.send_message(target_context, display_text, parse_mode=parse_mode)except Exception as err:logger.error("Failed to send result message: %s", err)else:summary = self._build_result_summary(display_text, self._get_result_max_chars(context))try:- await im_client.send_message(target_context, summary, parse_mode=parse_mode)+ primary_message_id = await im_client.send_message(target_context, summary, parse_mode=parse_mode)except Exception as err:logger.error("Failed to send result summary: %s", err)@@ -234,6 +237,12 @@ class ConsolidatedMessageDispatcher:if enhanced and enhanced.files:await self._upload_file_links(im_client, target_context, enhanced.files)+ if primary_message_id:+ try:+ self.controller.session_handler.finalize_scheduled_delivery(context, primary_message_id)+ except Exception as err:+ logger.warning("Failed to finalize scheduled delivery anchor: %s", err)+# Final result closes the current turn: clear consolidated# assistant/tool/system message state so the next user turn starts# a fresh log message instead of appending to the previous one.@@ -243,7 +252,7 @@ class ConsolidatedMessageDispatcher:self._consolidated_message_ids.pop(consolidated_key, None)self._consolidated_message_buffers.pop(consolidated_key, None)- return+ return primary_message_idif canonical_type not in {"system", "assistant", "toolcall"}:canonical_type = "assistant"@@ -256,7 +265,7 @@ class ConsolidatedMessageDispatcher:settings_key,preview,)- return+ return Noneconsolidated_key = self._get_consolidated_message_key(context)lock = self._get_consolidated_message_lock(consolidated_key)@@ -350,14 +359,16 @@ class ConsolidatedMessageDispatcher:logger.warning(f"Failed to edit Log Message: {err}")ok = Falseif ok:- return+ return existing_message_idself._consolidated_message_ids.pop(consolidated_key, None)try:new_id = await im_client.send_message(target_context, updated, parse_mode="markdown")self._consolidated_message_ids[consolidated_key] = new_id+ return new_idexcept Exception as err:logger.error(f"Failed to send Log Message: {err}", exc_info=True)+ return None# ------------------------------------------------------------------# Reply-enhancement helpers@@ -370,7 +381,7 @@ class ConsolidatedMessageDispatcher:text: str,buttons,parse_mode,- ) -> None:+ ) -> str:"""Send a message with quick-reply buttons appended."""from modules.im.base import InlineButton, InlineKeyboard@@ -382,7 +393,7 @@ class ConsolidatedMessageDispatcher:platform = context.platform or (context.platform_specific or {}).get("platform") or self.controller.config.platformrows = [[button] for button in row] if platform == "lark" else [row]keyboard = InlineKeyboard(buttons=rows)- await im_client.send_message_with_buttons(+ return await im_client.send_message_with_buttons(context,text,keyboard,diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pynew file mode 100644index 000000000..0f391c95d--- /dev/null+++ b/core/scheduled_tasks.py@@ -0,0 +1,365 @@+"""Scheduled task persistence, parsing, and runtime orchestration."""++from __future__ import annotations++import asyncio+import json+import logging+import tempfile+from dataclasses import asdict, dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Dict, Optional+from uuid import uuid4+from zoneinfo import ZoneInfo++from apscheduler.schedulers.asyncio import AsyncIOScheduler+from apscheduler.triggers.cron import CronTrigger+from apscheduler.triggers.date import DateTrigger++from config import paths+from modules.im import MessageContext++logger = logging.getLogger(__name__)+++def _utc_now_iso() -> str:+ return datetime.now(timezone.utc).isoformat()+++@dataclass(frozen=True)+class ParsedSessionKey:+ platform: str+ scope_type: str+ scope_id: str+ thread_id: Optional[str] = None++ @property+ def session_scope(self) -> str:+ return f"{self.platform}::{self.scope_id}"++ @property+ def is_dm(self) -> bool:+ return self.scope_type == "user"++ def to_key(self) -> str:+ base = f"{self.platform}::{self.scope_type}::{self.scope_id}"+ if self.thread_id:+ return f"{base}::thread::{self.thread_id}"+ return base+++def parse_session_key(value: str) -> ParsedSessionKey:+ raw = (value or "").strip()+ parts = raw.split("::") if raw else []+ if len(parts) not in {3, 5}:+ raise ValueError("session key must be '<platform>::<channel|user>::<id>[::thread::<thread_id>]'")++ platform, scope_type, scope_id = parts[:3]+ if not platform or not scope_id:+ raise ValueError("session key platform and scope id are required")+ if scope_type not in {"channel", "user"}:+ raise ValueError("session key scope type must be 'channel' or 'user'")++ thread_id: Optional[str] = None+ if len(parts) == 5:+ if parts[3] != "thread" or not parts[4]:+ raise ValueError("session key thread segment must be '::thread::<thread_id>'")+ thread_id = parts[4]++ return ParsedSessionKey(+ platform=platform,+ scope_type=scope_type,+ scope_id=scope_id,+ thread_id=thread_id,+ )+++@dataclass+class ScheduledTask:+ id: str+ session_key: str+ prompt: str+ schedule_type: str+ cron: Optional[str] = None+ run_at: Optional[str] = None+ timezone: str = "UTC"+ enabled: bool = True+ created_at: str = field(default_factory=_utc_now_iso)+ updated_at: str = field(default_factory=_utc_now_iso)+ last_run_at: Optional[str] = None+ last_error: Optional[str] = None++ def to_dict(self) -> Dict[str, Any]:+ return asdict(self)++ @classmethod+ def from_dict(cls, payload: Dict[str, Any]) -> "ScheduledTask":+ return cls(+ id=str(payload.get("id") or uuid4().hex[:12]),+ session_key=str(payload.get("session_key") or ""),+ prompt=str(payload.get("prompt") or ""),+ schedule_type=str(payload.get("schedule_type") or ""),+ cron=payload.get("cron"),+ run_at=payload.get("run_at"),+ timezone=str(payload.get("timezone") or "UTC"),+ enabled=bool(payload.get("enabled", True)),+ created_at=str(payload.get("created_at") or _utc_now_iso()),+ updated_at=str(payload.get("updated_at") or _utc_now_iso()),+ last_run_at=payload.get("last_run_at"),+ last_error=payload.get("last_error"),+ )+++class ScheduledTaskStore:+ def __init__(self, path: Optional[Path] = None):+ self.path = path or (paths.get_state_dir() / "scheduled_tasks.json")+ self._mtime: float = 0+ self._tasks: Dict[str, ScheduledTask] = {}+ self.load()++ def load(self) -> None:+ if not self.path.exists():+ self._tasks = {}+ return+ try:+ payload = json.loads(self.path.read_text(encoding="utf-8"))+ except Exception as exc:+ logger.error("Failed to load scheduled tasks: %s", exc)+ self._tasks = {}+ return++ raw_tasks = payload.get("tasks", []) if isinstance(payload, dict) else []+ tasks: Dict[str, ScheduledTask] = {}+ for item in raw_tasks:+ if not isinstance(item, dict):+ continue+ task = ScheduledTask.from_dict(item)+ tasks[task.id] = task+ self._tasks = tasks+ try:+ self._mtime = self.path.stat().st_mtime+ except FileNotFoundError:+ self._mtime = 0++ def maybe_reload(self) -> bool:+ try:+ mtime = self.path.stat().st_mtime+ except FileNotFoundError:+ mtime = 0+ if mtime <= self._mtime:+ return False+ self.load()+ return True++ def _save(self) -> None:+ self.path.parent.mkdir(parents=True, exist_ok=True)+ payload = {"tasks": [task.to_dict() for task in self.list_tasks()]}+ with tempfile.NamedTemporaryFile(+ mode="w",+ dir=self.path.parent,+ suffix=".tmp",+ delete=False,+ encoding="utf-8",+ ) as handle:+ json.dump(payload, handle, indent=2)+ tmp_path = Path(handle.name)+ tmp_path.replace(self.path)+ self._mtime = self.path.stat().st_mtime++ def list_tasks(self) -> list[ScheduledTask]:+ return sorted(self._tasks.values(), key=lambda item: (item.created_at, item.id))++ def get_task(self, task_id: str) -> Optional[ScheduledTask]:+ return self._tasks.get(task_id)++ def upsert_task(self, task: ScheduledTask) -> ScheduledTask:+ task.updated_at = _utc_now_iso()+ self._tasks[task.id] = task+ self._save()+ return task++ def add_task(+ self,+ *,+ session_key: str,+ prompt: str,+ schedule_type: str,+ cron: Optional[str] = None,+ run_at: Optional[str] = None,+ timezone_name: str,+ ) -> ScheduledTask:+ task = ScheduledTask(+ id=uuid4().hex[:12],+ session_key=session_key,+ prompt=prompt,+ schedule_type=schedule_type,+ cron=cron,+ run_at=run_at,+ timezone=timezone_name,+ )+ return self.upsert_task(task)++ def remove_task(self, task_id: str) -> bool:+ if task_id not in self._tasks:+ return False+ del self._tasks[task_id]+ self._save()+ return True++ def set_enabled(self, task_id: str, enabled: bool) -> ScheduledTask:+ task = self._tasks[task_id]+ task.enabled = enabled+ task.updated_at = _utc_now_iso()+ self._save()+ return task++ def mark_task_result(self, task_id: str, *, error: Optional[str]) -> None:+ task = self._tasks[task_id]+ task.last_run_at = _utc_now_iso()+ task.last_error = error+ if task.schedule_type == "at":+ task.enabled = False+ task.updated_at = _utc_now_iso()+ self._save()+++class ScheduledTaskService:+ """Controller-owned runtime that executes persisted scheduled tasks."""++ def __init__(self, controller, store: Optional[ScheduledTaskStore] = None):+ self.controller = controller+ self.store = store or ScheduledTaskStore()+ self.scheduler = AsyncIOScheduler(timezone="UTC")+ self._reconcile_task: Optional[asyncio.Task] = None+ self._job_signatures: Dict[str, tuple[Any, ...]] = {}+ self._running = False++ def start(self) -> None:+ if self._running:+ return+ self.scheduler.start()+ self._running = True+ self.reconcile_jobs()+ self._reconcile_task = asyncio.create_task(self._watch_store())++ async def stop(self) -> None:+ self._running = False+ if self._reconcile_task:+ self._reconcile_task.cancel()+ try:+ await self._reconcile_task+ except asyncio.CancelledError:+ pass+ self._reconcile_task = None+ self.scheduler.shutdown(wait=False)++ async def _watch_store(self) -> None:+ while self._running:+ try:+ if self.store.maybe_reload():+ self.reconcile_jobs()+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ logger.error("Scheduled task store watch failed: %s", exc, exc_info=True)+ await asyncio.sleep(2)++ def reconcile_jobs(self) -> None:+ desired_ids = set()+ for task in self.store.list_tasks():+ if not task.enabled:+ continue+ desired_ids.add(task.id)+ signature = (+ task.schedule_type,+ task.cron,+ task.run_at,+ task.timezone,+ task.session_key,+ task.prompt,+ task.enabled,+ )+ if self._job_signatures.get(task.id) == signature and self.scheduler.get_job(task.id):+ continue+ if self.scheduler.get_job(task.id):+ self.scheduler.remove_job(task.id)+ self.scheduler.add_job(+ self._run_task,+ trigger=self._build_trigger(task),+ id=task.id,+ replace_existing=True,+ coalesce=True,+ max_instances=1,+ args=[task.id],+ )+ self._job_signatures[task.id] = signature++ for job in list(self.scheduler.get_jobs()):+ if job.id not in desired_ids:+ self.scheduler.remove_job(job.id)+ self._job_signatures.pop(job.id, None)++ def _build_trigger(self, task: ScheduledTask):+ tz = ZoneInfo(task.timezone)+ if task.schedule_type == "cron":+ if not task.cron:+ raise ValueError(f"scheduled task {task.id} is missing cron expression")+ return CronTrigger.from_crontab(task.cron, timezone=tz)+ if task.schedule_type == "at":+ if not task.run_at:+ raise ValueError(f"scheduled task {task.id} is missing run_at timestamp")+ return DateTrigger(run_date=datetime.fromisoformat(task.run_at).astimezone(tz))+ raise ValueError(f"unknown schedule type: {task.schedule_type}")++ async def _run_task(self, task_id: str) -> None:+ self.store.maybe_reload()+ task = self.store.get_task(task_id)+ if not task or not task.enabled:+ return++ error: Optional[str] = None+ try:+ target = parse_session_key(task.session_key)+ context = await self._build_context(target)+ await self.controller.message_handler.handle_scheduled_message(+ context=context,+ message=task.prompt,+ parsed_session_key=target,+ )+ except Exception as exc:+ error = str(exc)+ logger.error("Scheduled task %s failed: %s", task_id, exc, exc_info=True)+ finally:+ self.store.mark_task_result(task_id, error=error)+ self.reconcile_jobs()++ async def _build_context(self, target: ParsedSessionKey) -> MessageContext:+ platform = target.platform+ settings_manager = self.controller.platform_settings_managers[platform]++ channel_id = target.scope_id+ user_id = "scheduled"+ if target.is_dm:+ user_id = target.scope_id+ bound_user = settings_manager.get_store().get_user(target.scope_id, platform=platform)+ if platform == "lark":+ dm_chat_id = getattr(bound_user, "dm_chat_id", "") if bound_user else ""+ if not dm_chat_id:+ raise ValueError(f"lark user {target.scope_id} is missing dm_chat_id binding")+ channel_id = dm_chat_id+ elif bound_user and getattr(bound_user, "dm_chat_id", ""):+ channel_id = bound_user.dm_chat_id++ return MessageContext(+ user_id=user_id,+ channel_id=channel_id,+ platform=platform,+ thread_id=target.thread_id,+ platform_specific={+ "platform": platform,+ "is_dm": target.is_dm,+ "turn_source": "scheduled",+ "session_key_external": target.to_key(),+ },+ )diff --git a/docs/plans/scheduled-tasks.md b/docs/plans/scheduled-tasks.mdnew file mode 100644index 000000000..20c23f383--- /dev/null+++ b/docs/plans/scheduled-tasks.md@@ -0,0 +1,230 @@+# Scheduled Tasks And Turn Pipeline++## Background+- Vibe Remote already has a mature session mapping model: `session_scope -> agent -> base_session_id -> native_session_id`.+- The current inbound path mixes two concerns inside `handle_user_message()`:+ - Session semantics: which conversation this input belongs to.+ - IM behavior: whether replies should go to a thread, a newly created Discord thread, or a flat DM channel.+- Product requirement for scheduled tasks is stricter than a generic background prompt runner:+ - A scheduled task must behave like "the user said this prompt under this session key".+ - The product logic must remain equivalent to manual usage.+ - Thread-capable and flat conversations intentionally behave differently.++## Goal+Add `vibe task ...` so users or agents can create one-off or cron-based scheduled tasks that inject prompts into existing Vibe Remote conversations without creating a parallel scheduler-only conversation model.++## Status+- Implemented in this worktree:+ - `vibe task add/list/show/pause/resume/rm`+ - persisted `scheduled_tasks.json` store+ - controller-owned `ScheduledTaskService` with cron and one-off triggers+ - shared `human` / `scheduled` turn pipeline+ - source-aware Discord turn preparation+ - scheduled top-level anchor aliasing into the existing session map+ - Slack/Lark scheduled-thread reply allowance+- Explicitly not implemented in this slice:+ - `vibe task run <id>`+ - UI management pages for scheduled tasks++## Product Rules++### External Session Key+The CLI receives one opaque `session_key` parameter. This is an external CLI contract only; it does not replace the current internal `_get_session_key()` implementation.++Recommended wire format:++```text+<platform>::channel::<channel_id>+<platform>::channel::<channel_id>::thread::<thread_id>+<platform>::user::<user_id>+<platform>::user::<user_id>::thread::<thread_id>+```++Examples:++```text+slack::channel::C123+slack::channel::C123::thread::1712345678.123+discord::user::123456789012345678+```++### Equivalent Manual Behavior+For a scheduled task with prompt `P` and session key `K`, the effect must be equivalent to the user manually sending message `P` under `K`.++That equivalence is defined by product behavior, not by blindly reusing the current webhook code path.++### Session Behavior By Surface Type+- Thread-capable surfaces without explicit thread:+ - Each scheduled trigger is a new session.+ - The bot sends results directly to the top-level channel/DM surface.+ - Future human replies to those bot messages must continue that session.+- Flat surfaces without thread support:+ - The same session key keeps using the same session across triggers.+- Explicit thread:+ - Scheduled triggers always continue that exact thread/session.++## Design++### 1. Split Turn Processing+Refactor `MessageHandler.handle_user_message()` into a shared turn-processing pipeline with explicit turn source.++Proposed source types:+- `human`+- `scheduled`++Proposed stages:+1. `ingest_human_turn()` / `ingest_scheduled_turn()`+2. `prepare_turn_context()`+3. `resolve_turn_session()`+4. `dispatch_turn_to_agent()`+5. `finalize_turn_delivery()`++The shared pipeline owns session semantics. IM-specific reply topology decisions move behind IM hooks instead of remaining hard-coded in adapters.++### 2. Move Reply Topology Out Of Discord Inbound Adapter+Today Discord eagerly creates a thread in the inbound adapter for non-thread guild messages. That is too early because the correct behavior depends on turn source.++New rule:+- IM adapters only normalize inbound context.+- IM clients may expose a hook such as `prepare_turn_context(context, source)` for source-aware reply topology.+- Discord uses that hook to create a thread only for `human` top-level guild messages.+- Scheduled top-level turns on Discord do not create a thread before agent execution.++Slack and Lark already encode top-level user messages as thread-root contexts; they can continue to do so for real user messages.++### 3. Preserve Existing Session Store, Add Alias Operations+Do not introduce a separate scheduler conversation namespace.++Instead, extend the existing session mapping facade with alias-oriented operations:+- detect whether any stored session exists for a given `session_scope + base_session_id`+- create alias mappings from one `base_session_id` prefix to another+- remove provisional aliases after final anchoring++Alias behavior must preserve suffixes used by existing backends:+- Claude subagents: `base:subagent`+- OpenCode cwd-scoped keys: `base:/abs/path`++Prefix replacement rule:+- exact match: `old_base -> new_base`+- prefixed match: `old_base:<suffix> -> new_base:<suffix>`++### 4. Scheduled Turn Anchoring+Scheduled top-level turns on thread-capable surfaces need a provisional base before the first bot message exists.++Flow:+1. Build a provisional `base_session_id` for this scheduled run.+2. Run the agent using that provisional base.+3. Every top-level bot message emitted by that run is collected as a potential reply anchor.+4. Once the backend session mapping exists, alias those emitted message IDs to the same native session in the existing store.+5. After the turn is finalized, clear the provisional aliases and keep only the real anchors.++Why:+- Slack/Lark replies will later use the bot message ID as thread root directly.+- Discord top-level replies require an extra bridge:+ - a human may reply to a scheduled bot message in-channel+ - the system creates a new Discord thread for that human turn+ - if the replied-to message ID is already aliased, the new thread ID can inherit that session++### 5. Scheduled Turn Delivery+Scheduled turns without explicit thread should deliver top-level messages on thread-capable surfaces.++That is intentionally different from real human top-level messages, where some platforms create or use a thread automatically.++To support this, outbound targeting must become source-aware instead of assuming `context.thread_id` alone defines the correct reply location.++### 6. Session-Key Resolution+Add a resolver that parses the external CLI session key into:+- platform+- scope type: `channel` or `user`+- scope ID+- optional explicit thread ID++Then resolve it into an execution context:+- `session_scope`: current internal scope key used by settings/session maps+- `delivery_channel_id`: actual channel/chat ID used to send messages+- `context.user_id`: actual DM user ID for user-scoped conversations, synthetic scheduler user for channel-scoped turns+- `is_dm`+- `thread_id`++DM resolution requirements:+- Slack / Discord can open or send to DM by user ID.+- Lark must resolve the bound user's `dm_chat_id`.+- WeChat stays flat and uses the chat/user target already persisted by current settings.++### 7. Mention-Gating Compatibility+Scheduled-created sessions must remain replyable in channels where mention gating is enabled.++Implemented approach:+- mark scheduled-created Slack/Lark thread roots under synthetic user `scheduled`+- allow thread replies when either the real user or `scheduled` has an active thread mark+- for Discord guild channels, treat a reply to a known scheduled anchor as a valid conversation continuation even without a mention+- once Discord creates or reuses the thread for that reply, alias the scheduled anchor base onto the real thread base++## CLI Scope+Initial subcommands:+- `vibe task add`+- `vibe task list`+- `vibe task show <id>`+- `vibe task pause <id>`+- `vibe task resume <id>`+- `vibe task rm <id>`+- `vibe task run <id>`++Initial scheduling modes:+- `--cron "<expr>"`+- `--at "<iso8601>"`++Task inputs:+- `--session-key "<key>"`+- `--prompt "..."`+- `--prompt-file path`+- `--timezone Asia/Shanghai` (default: local timezone)++## Persistence And Runtime+- Persist scheduled tasks in `~/.vibe_remote/state/scheduled_tasks.json`.+- Introduce a `ScheduledTaskStore` with atomic writes and `maybe_reload()` support.+- Introduce a controller-owned `ScheduledTaskService` started after IM readiness.+- Use a scheduler library for cron support and task reconciliation on store changes.++## Planned Code Changes+- `core/handlers/message_handler.py`+ - split turn ingestion and shared processing+ - add scheduled turn entrypoint+- `core/handlers/session_handler.py`+ - source-aware base session resolution+- `core/controller.py`+ - wire scheduled task service and top-level turn entrypoints+- `core/message_dispatcher.py`+ - expose sent message IDs to scheduled anchor tracking+- `modules/im/base.py`+ - add source-aware turn-context preparation hook+- `modules/im/discord.py`+ - remove eager thread creation from raw inbound adapter+ - move Discord thread creation into the new hook+ - bridge replied-to scheduled bot message -> new thread session alias+- `modules/im/slack.py`+ - mention-gating fallback for stored session anchors+- `modules/im/feishu.py`+ - mention-gating fallback if needed for scheduled thread roots+- `modules/sessions_facade.py`+ - alias helpers and stored-session existence helpers+- `vibe/cli.py`+ - `task` command group+- `config/` or `core/`+ - scheduled task store / session key parsing module+- `tests/`+ - session-key parsing+ - scheduled turn session behavior+ - Discord source-aware thread behavior+ - alias migration and mention-gating fallback++## Implementation Todos+- [x] Add scheduled-task persistence and session-key parser.+- [x] Introduce source-aware turn pipeline and scheduled turn entrypoint.+- [x] Move Discord eager thread creation into handler-driven preprocessing.+- [x] Add alias operations to existing session facade.+- [x] Add scheduled anchor tracking and alias finalization.+- [x] Add `vibe task` CLI.+- [x] Add scheduled runtime service with cron and one-off triggers.+- [x] Add focused tests.+- [x] Run relevant lint/tests/build checks.diff --git a/modules/im/base.py b/modules/im/base.pyindex 0beb44047..9d30bc138 100644--- a/modules/im/base.py+++ b/modules/im/base.py@@ -146,6 +146,14 @@ class BaseIMClient(ABC):"""return False+ async def prepare_turn_context(self, context: MessageContext, source: str) -> MessageContext:+ """Allow IM adapters to adjust reply topology for a turn source.++ `source` is one of the higher-level inbound turn types such as+ ``human`` or ``scheduled``.+ """+ return context+@staticmethoddef extract_command_action(text: str, allow_plain_bind: bool = False) -> str:"""Extract command action name from slash command text.diff --git a/modules/im/discord.py b/modules/im/discord.pyindex 96edf8b95..01c5ae209 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -198,6 +198,85 @@ class DiscordBot(BaseIMClient):return await self._run_on_client_loop(_impl())+ async def prepare_turn_context(self, context: MessageContext, source: str) -> MessageContext:+ if source != "human" or context.thread_id:+ return context+ payload = context.platform_specific or {}+ if payload.get("is_dm"):+ return context+ message = payload.get("message")+ if message is None or getattr(message, "guild", None) is None:+ return context++ reply_anchor_message_id = self._get_reference_message_id(message)+ reply_anchor_base_session_id = self._get_reply_anchor_base(context.channel_id, reply_anchor_message_id)+ if reply_anchor_base_session_id:+ async def _reply_impl() -> MessageContext:+ channel = await self._fetch_channel(context.channel_id)+ if channel is None or not hasattr(channel, "fetch_message"):+ return context+ try:+ anchor_message = await channel.fetch_message(int(reply_anchor_message_id))+ except Exception as err:+ logger.warning(+ "Failed to fetch Discord reply anchor %s: %s",+ reply_anchor_message_id,+ err,+ )+ return context++ thread = getattr(anchor_message, "thread", None)+ if thread is None:+ thread = await self._maybe_create_thread(anchor_message)+ if thread is None:+ return context++ next_payload = dict(context.platform_specific or {})+ next_payload["reply_anchor_base_session_id"] = reply_anchor_base_session_id+ next_payload["reply_anchor_message_id"] = reply_anchor_message_id+ return MessageContext(+ user_id=context.user_id,+ channel_id=context.channel_id,+ platform=context.platform,+ thread_id=str(thread.id),+ message_id=context.message_id,+ platform_specific=next_payload,+ files=context.files,+ )++ return await self._run_on_client_loop(_reply_impl())++ async def _impl() -> MessageContext:+ thread = await self._maybe_create_thread(message)+ if thread is None:+ return context+ return MessageContext(+ user_id=context.user_id,+ channel_id=context.channel_id,+ platform=context.platform,+ thread_id=str(thread.id),+ message_id=context.message_id,+ platform_specific=context.platform_specific,+ files=context.files,+ )++ return await self._run_on_client_loop(_impl())++ @staticmethod+ def _get_reference_message_id(message: discord.Message) -> Optional[str]:+ reference = getattr(message, "reference", None)+ message_id = getattr(reference, "message_id", None) if reference is not None else None+ return str(message_id) if message_id is not None else None++ def _get_reply_anchor_base(self, channel_id: str, message_id: Optional[str]) -> Optional[str]:+ if not self.sessions or not channel_id or not message_id:+ return None+ session_key = f"discord::{channel_id}"+ base_session_id = f"discord_{message_id}"+ if self.sessions.has_any_agent_session_base(session_key, base_session_id):+ return base_session_id+ return None+def format_markdown(self, text: str) -> str:return text@@ -803,6 +882,7 @@ class DiscordBot(BaseIMClient):# Determine if this is a DMis_dm = isinstance(channel, discord.DMChannel) or message.guild is None+ referenced_anchor_base = None if is_dm else self._get_reply_anchor_base(channel_id, self._get_reference_message_id(message))auth_result = self.check_authorization(user_id=str(message.author.id),@@ -837,7 +917,9 @@ class DiscordBot(BaseIMClient):else:returnelse:- if not message.mentions or (self.client.user and self.client.user not in message.mentions):+ if referenced_anchor_base:+ pass+ elif not message.mentions or (self.client.user and self.client.user not in message.mentions):return# Strip bot mention from content@@ -877,12 +959,6 @@ class DiscordBot(BaseIMClient):await self.on_message_callback(context, "")return- # For non-thread guild messages, create a real thread- if not isinstance(channel, discord.Thread) and message.guild is not None:- thread = await self._maybe_create_thread(message)- if thread is not None:- thread_id = str(thread.id)-context = MessageContext(user_id=str(message.author.id),channel_id=channel_id,diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex fca6f84bc..c730e01bc 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -1496,10 +1496,11 @@ class FeishuBot(BaseIMClient):returnelse:if self.settings_manager:- thread_active = (- self.sessions.is_thread_active(user_id, chat_id, root_id) if self.sessions else False+ thread_active = self.sessions.is_thread_active(user_id, chat_id, root_id) if self.sessions else False+ scheduled_thread_active = (+ self.sessions.is_thread_active("scheduled", chat_id, root_id) if self.sessions else False)- if not thread_active:+ if not thread_active and not scheduled_thread_active:logger.debug("Ignoring message in inactive thread %s", root_id)returnelse:diff --git a/modules/im/slack.py b/modules/im/slack.pyindex 716c82e76..a29f63c6b 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -1252,10 +1252,11 @@ class SlackBot(BaseIMClient):thread_ts = event.get("thread_ts")# If we have settings_manager, check if thread is activeif self.settings_manager:- thread_active = (- self.sessions.is_thread_active(user_id, channel_id, thread_ts) if self.sessions else False+ thread_active = self.sessions.is_thread_active(user_id, channel_id, thread_ts) if self.sessions else False+ scheduled_thread_active = (+ self.sessions.is_thread_active("scheduled", channel_id, thread_ts) if self.sessions else False)- if not thread_active:+ if not thread_active and not scheduled_thread_active:logger.debug(f"Ignoring message in inactive thread {thread_ts}: '{text}'")returnelse:diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex 9468111b6..cccfc9d39 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -91,6 +91,84 @@ class SessionsFacade:agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})return {agent: dict(mapping) for agent, mapping in agent_maps.items()}+ @staticmethod+ def _matches_base_prefix(mapping_key: str, base_session_id: str) -> bool:+ return mapping_key == base_session_id or mapping_key.startswith(f"{base_session_id}:")++ def has_any_agent_session_base(self, user_id: Union[int, str], base_session_id: str) -> bool:+ user_key = self._normalize_user_id(user_id)+ self.sessions_store._ensure_user_namespace(user_key)+ agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})+ for agent_map in agent_maps.values():+ for mapping_key in agent_map.keys():+ if self._matches_base_prefix(mapping_key, base_session_id):+ return True+ return False++ def alias_session_base(+ self,+ user_id: Union[int, str],+ source_base_session_id: str,+ alias_base_session_id: str,+ ) -> bool:+ user_key = self._normalize_user_id(user_id)+ self.sessions_store._ensure_user_namespace(user_key)+ agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})+ changed = False++ for agent_name, agent_map in agent_maps.items():+ additions: Dict[str, str] = {}+ for mapping_key, native_session_id in list(agent_map.items()):+ if not self._matches_base_prefix(mapping_key, source_base_session_id):+ continue+ suffix = mapping_key[len(source_base_session_id) :]+ alias_key = f"{alias_base_session_id}{suffix}"+ if alias_key in agent_map or alias_key in additions:+ continue+ additions[alias_key] = native_session_id+ if additions:+ agent_map.update(additions)+ changed = True+ logger.info(+ "Aliased %s session base for %s: %s -> %s (%s keys)",+ agent_name,+ user_key,+ source_base_session_id,+ alias_base_session_id,+ len(additions),+ )++ if changed:+ self.sessions_store.save()+ return changed++ def clear_session_base(self, user_id: Union[int, str], base_session_id: str) -> int:+ user_key = self._normalize_user_id(user_id)+ self.sessions_store._ensure_user_namespace(user_key)+ agent_maps = self.sessions_store.state.session_mappings.get(user_key, {})+ cleared = 0++ for agent_name, agent_map in agent_maps.items():+ keys_to_remove = [+ mapping_key for mapping_key in list(agent_map.keys()) if self._matches_base_prefix(mapping_key, base_session_id)+ ]+ if not keys_to_remove:+ continue+ for mapping_key in keys_to_remove:+ del agent_map[mapping_key]+ cleared += 1+ logger.info(+ "Cleared %s session base for %s: %s (%s keys)",+ agent_name,+ user_key,+ base_session_id,+ len(keys_to_remove),+ )++ if cleared:+ self.sessions_store.save()+ return cleared+def get_all_session_mappings(self) -> Dict[str, Dict[str, Dict[str, str]]]:"""Return all persisted session mappings grouped by user and agent."""mappings = self.sessions_store.state.session_mappingsdiff --git a/pyproject.toml b/pyproject.tomlindex 5d95879d4..c8e41927a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -29,6 +29,7 @@ classifiers = [dependencies = ["claude-agent-sdk>=0.1.23","anyio>=4.0.0",+ "APScheduler>=3.10.4","slack-sdk>=3.26.0","discord.py>=2.4.0","aiohttp>=3.8.0",diff --git a/tests/test_discord_reply_anchor.py b/tests/test_discord_reply_anchor.pynew file mode 100644index 000000000..760bd48aa--- /dev/null+++ b/tests/test_discord_reply_anchor.py@@ -0,0 +1,53 @@+from __future__ import annotations++import sys+import unittest+from pathlib import Path+from types import SimpleNamespace++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from modules.im import MessageContext+from modules.im.discord import DiscordBot+++class _FakeSessions:+ def has_any_agent_session_base(self, user_id, base_session_id):+ return user_id == "discord::C123" and base_session_id == "discord_555"+++class _FakeChannel:+ async def fetch_message(self, message_id):+ return SimpleNamespace(id=message_id, thread=SimpleNamespace(id=777))+++class DiscordReplyAnchorTests(unittest.IsolatedAsyncioTestCase):+ async def test_prepare_turn_context_uses_reply_anchor_thread_when_known_session_exists(self):+ bot = object.__new__(DiscordBot)+ bot.sessions = _FakeSessions()+ bot._loop = None++ async def _fetch_channel(channel_id):+ self.assertEqual(channel_id, "C123")+ return _FakeChannel()++ async def _maybe_create_thread(message):+ raise AssertionError("existing thread should be reused")++ bot._fetch_channel = _fetch_channel+ bot._maybe_create_thread = _maybe_create_thread++ message = SimpleNamespace(guild=object(), reference=SimpleNamespace(message_id=555))+ context = MessageContext(+ user_id="U123",+ channel_id="C123",+ platform="discord",+ message_id="999",+ platform_specific={"message": message, "is_dm": False},+ )++ prepared = await DiscordBot.prepare_turn_context(bot, context, "human")++ self.assertEqual(prepared.thread_id, "777")+ self.assertEqual(prepared.platform_specific["reply_anchor_base_session_id"], "discord_555")+ self.assertEqual(prepared.platform_specific["reply_anchor_message_id"], "555")diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.pynew file mode 100644index 000000000..ea980b326--- /dev/null+++ b/tests/test_message_dispatcher_scheduled.py@@ -0,0 +1,76 @@+from __future__ import annotations++import sys+import unittest+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.message_dispatcher import ConsolidatedMessageDispatcher+from modules.im import MessageContext+++class _StubIMClient:+ def should_use_thread_for_reply(self):+ return False++ async def send_message(self, context, text, parse_mode=None, reply_to=None):+ return "bot-msg-1"++ async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):+ return "bot-msg-1"+++class _StubSettingsManager:+ def _canonicalize_message_type(self, message_type):+ return message_type++ def is_message_type_hidden(self, settings_key, canonical_type):+ return False+++class _StubSessionHandler:+ def __init__(self):+ self.calls = []++ def finalize_scheduled_delivery(self, context, sent_message_id):+ self.calls.append((context.channel_id, sent_message_id))+++class _StubController:+ def __init__(self):+ self.config = type("Config", (), {"platform": "slack", "reply_enhancements": False})()+ self.session_handler = _StubSessionHandler()++ def _get_settings_key(self, context):+ return context.channel_id++ def _get_session_key(self, context):+ return f"slack::{context.channel_id}"++ def get_settings_manager_for_context(self, context):+ return _StubSettingsManager()++ def get_im_client_for_context(self, context):+ return _StubIMClient()+++class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):+ async def test_result_message_finalizes_scheduled_delivery(self):+ controller = _StubController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "turn_source": "scheduled",+ "turn_base_session_id": "slack_scheduled-1",+ "scheduled_anchor_required": True,+ },+ )++ message_id = await dispatcher.emit_agent_message(context, "result", "hello")++ self.assertEqual(message_id, "bot-msg-1")+ self.assertEqual(controller.session_handler.calls, [("C123", "bot-msg-1")])diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex dc7926d76..55559977c 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -96,11 +96,14 @@ class _StubIMClient:self.reactions = []self.sent_messages = []self.removed_keyboards = []- self.formatter = None+ self.formatter = type("Formatter", (), {"format_error": staticmethod(lambda text: text)})()def should_use_thread_for_reply(self):return False+ async def prepare_turn_context(self, context, source):+ return context+async def get_user_info(self, user_id):return {"display_name": f"user:{user_id}"}@@ -181,9 +184,17 @@ class _StubController:class _StubSessionHandler:@staticmethod- def get_session_info(context):+ def get_session_info(context, source="human"):return ("base-session", "/tmp", "base-session:/tmp")+ @staticmethod+ def should_allocate_scheduled_anchor(context, source="human"):+ return False++ @staticmethod+ def alias_session_base(context, *, source_base_session_id, alias_base_session_id, clear_source=False):+ return False+class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):async def test_wechat_forces_typing_even_when_ack_mode_is_message(self):diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pynew file mode 100644index 000000000..2e56b4d29--- /dev/null+++ b/tests/test_scheduled_tasks.py@@ -0,0 +1,45 @@+from __future__ import annotations++import json+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.scheduled_tasks import ScheduledTaskStore, parse_session_key+++def test_parse_session_key_accepts_channel_and_thread() -> None:+ parsed = parse_session_key("slack::channel::C123::thread::171717.123")++ assert parsed.platform == "slack"+ assert parsed.scope_type == "channel"+ assert parsed.scope_id == "C123"+ assert parsed.thread_id == "171717.123"+++def test_parse_session_key_rejects_invalid_scope_type() -> None:+ try:+ parse_session_key("slack::room::C123")+ except ValueError as exc:+ assert "scope type" in str(exc)+ else:+ raise AssertionError("expected invalid scope type to raise ValueError")+++def test_store_round_trip_persists_task(tmp_path: Path) -> None:+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")+ task = store.add_task(+ session_key="discord::channel::123",+ prompt="send digest",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="Asia/Shanghai",+ )++ reloaded = ScheduledTaskStore(store.path)+ payload = json.loads(store.path.read_text(encoding="utf-8"))++ assert payload["tasks"][0]["id"] == task.id+ assert reloaded.get_task(task.id) is not None+ assert reloaded.get_task(task.id).session_key == "discord::channel::123"diff --git a/tests/test_session_handler_base_id.py b/tests/test_session_handler_base_id.pyindex 5ce628771..b33321d6b 100644--- a/tests/test_session_handler_base_id.py+++ b/tests/test_session_handler_base_id.py@@ -15,14 +15,37 @@ class _Config:platform: str = "discord"+class _FakeSessions:+ def __init__(self) -> None:+ self.alias_calls = []+ self.clear_calls = []+ self.thread_marks = []++ def alias_session_base(self, user_id, source_base_session_id, alias_base_session_id):+ self.alias_calls.append((user_id, source_base_session_id, alias_base_session_id))+ return True++ def clear_session_base(self, user_id, base_session_id):+ self.clear_calls.append((user_id, base_session_id))+ return 1++ def mark_thread_active(self, user_id, channel_id, thread_ts):+ self.thread_marks.append((user_id, channel_id, thread_ts))++class _Controller:def __init__(self, *, platform: str = "discord", dm_threads: bool = False) -> None:self.config = _Config()self.config.platform = platform+ self.sessions = _FakeSessions()self.im_client = type("IM",(),- {"formatter": None, "should_use_thread_for_dm_session": lambda self: dm_threads},+ {+ "formatter": None,+ "should_use_thread_for_dm_session": lambda self: dm_threads,+ "should_use_thread_for_reply": lambda self: platform in {"discord", "slack", "lark"},+ },)()self.settings_manager = type("Settings", (), {"sessions": None})()self.session_manager = object()@@ -105,3 +128,53 @@ def test_channel_session_base_id_keeps_thread_or_message_behavior() -> None:)assert handler.get_base_session_id(context) == "discord_msg-999"+++def test_scheduled_channel_session_uses_provisional_anchor_on_threaded_surfaces() -> None:+ controller = _Controller(platform="slack", dm_threads=False)+ handler = SessionHandler(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={"is_dm": False, "turn_source": "scheduled"},+ )++ base_session_id = handler.get_base_session_id(context, source="scheduled")++ assert base_session_id.startswith("slack_scheduled-")+++def test_scheduled_dm_session_reuses_flat_session_scope() -> None:+ controller = _Controller(platform="discord", dm_threads=False)+ handler = SessionHandler(controller)+ context = MessageContext(+ user_id="u-1",+ channel_id="dm-123",+ platform="discord",+ platform_specific={"is_dm": True, "turn_source": "scheduled"},+ )++ assert handler.get_base_session_id(context, source="scheduled") == "discord_dm-123"+++def test_finalize_scheduled_delivery_aliases_provisional_base_and_marks_thread() -> None:+ controller = _Controller(platform="slack", dm_threads=False)+ handler = SessionHandler(controller)+ context = MessageContext(+ user_id="scheduled",+ channel_id="C123",+ platform="slack",+ platform_specific={+ "is_dm": False,+ "turn_source": "scheduled",+ "turn_base_session_id": "slack_scheduled-abc",+ "scheduled_anchor_required": True,+ },+ )++ handler.finalize_scheduled_delivery(context, "171717.123")++ assert controller.sessions.alias_calls == [("slack::C123", "slack_scheduled-abc", "slack_171717.123")]+ assert controller.sessions.clear_calls == [("slack::C123", "slack_scheduled-abc")]+ assert controller.sessions.thread_marks == [("scheduled", "C123", "171717.123")]diff --git a/uv.lock b/uv.lockindex 1e88ae6ef..54eeb87b2 100644--- a/uv.lock+++ b/uv.lock@@ -184,6 +184,18 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/38/0e/27be9fdef66e72d64c0cdc3cc2823101b80585f8119b5c112c2e8f5f7dab/anyio-4.12.1-py3-none-any.whl", hash = "sha256:d405828884fc140aa80a3c667b8beed277f1dfedec42ba031bd6ac3db606ab6c", size = 113592, upload-time = "2026-01-06T11:45:19.497Z" },]+[[package]]+name = "apscheduler"+version = "3.11.2"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "tzlocal" },+]+sdist = { url = "https://files.pythonhosted.org/packages/07/12/3e4389e5920b4c1763390c6d371162f3784f86f85cd6d6c1bfe68eef14e2/apscheduler-3.11.2.tar.gz", hash = "sha256:2a9966b052ec805f020c8c4c3ae6e6a06e24b1bf19f2e11d91d8cca0473eef41", size = 108683, upload-time = "2025-12-22T00:39:34.884Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/9f/64/2e54428beba8d9992aa478bb8f6de9e4ecaa5f8f513bcfd567ed7fb0262d/apscheduler-3.11.2-py3-none-any.whl", hash = "sha256:ce005177f741409db4e4dd40a7431b76feb856b9dd69d57e0da49d6715bfd26d", size = 64439, upload-time = "2025-12-22T00:39:33.303Z" },+]+[[package]]name = "async-timeout"version = "5.0.1"@@ -1757,6 +1769,27 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" },]+[[package]]+name = "tzdata"+version = "2025.3"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/5e/a7/c202b344c5ca7daf398f3b8a477eeb205cf3b6f32e7ec3a6bac0629ca975/tzdata-2025.3.tar.gz", hash = "sha256:de39c2ca5dc7b0344f2eba86f49d614019d29f060fc4ebc8a417896a620b56a7", size = 196772, upload-time = "2025-12-13T17:45:35.667Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c7/b0/003792df09decd6849a5e39c28b513c06e84436a54440380862b5aeff25d/tzdata-2025.3-py2.py3-none-any.whl", hash = "sha256:06a47e5700f3081aab02b2e513160914ff0694bce9947d6b76ebd6bf57cfc5d1", size = 348521, upload-time = "2025-12-13T17:45:33.889Z" },+]++[[package]]+name = "tzlocal"+version = "5.3.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "tzdata", marker = "sys_platform == 'win32'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/8b/2e/c14812d3d4d9cd1773c6be938f89e5735a1f11a9f184ac3639b93cef35d5/tzlocal-5.3.1.tar.gz", hash = "sha256:cceffc7edecefea1f595541dbd6e990cb1ea3d19bf01b2809f362a03dd7921fd", size = 30761, upload-time = "2025-03-05T21:17:41.549Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/c2/14/e2a54fabd4f08cd7af1c07030603c3356b74da07f7cc056e600436edfa17/tzlocal-5.3.1-py3-none-any.whl", hash = "sha256:eb1a66c3ef5847adf7a834f1be0800581b683b5608e74f86ecbcef8ab91bb85d", size = 18026, upload-time = "2025-03-05T21:17:39.857Z" },+]+[[package]]name = "urllib3"version = "2.6.3"@@ -1787,6 +1820,7 @@ dependencies = [{ name = "aiohttp" },{ name = "aiohttp-socks" },{ name = "anyio" },+ { name = "apscheduler" },{ name = "claude-agent-sdk" },{ name = "discord-py" },{ name = "flask" },@@ -1804,6 +1838,7 @@ requires-dist = [{ name = "aiohttp", specifier = ">=3.8.0" },{ name = "aiohttp-socks", specifier = ">=0.8.0" },{ name = "anyio", specifier = ">=4.0.0" },+ { name = "apscheduler", specifier = ">=3.10.4" },{ name = "claude-agent-sdk", specifier = ">=0.1.23" },{ name = "discord-py", specifier = ">=2.4.0" },{ name = "flask", specifier = ">=3.0.0" },diff --git a/vibe/cli.py b/vibe/cli.pyindex 8b6486b7e..5f0e39e60 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -7,7 +7,12 @@ import signalimport subprocessimport sysimport time+from datetime import datetimefrom pathlib import Path+from zoneinfo import ZoneInfo++from apscheduler.triggers.cron import CronTrigger+from tzlocal import get_localzone_namefrom config import pathsfrom config.v2_config import (@@ -19,6 +24,7 @@ from config.v2_config import (SlackConfig,V2Config,)+from core.scheduled_tasks import ScheduledTaskStore, parse_session_keyfrom vibe import __version__, api, runtimefrom vibe.upgrade import build_upgrade_plan, cache_running_vibe_path, get_latest_version_info, get_safe_cwd@@ -143,6 +149,117 @@ def _render_status():return json.dumps(status, indent=2)+def _default_timezone_name() -> str:+ try:+ return get_localzone_name()+ except Exception:+ tz = datetime.now().astimezone().tzinfo+ key = getattr(tz, "key", None)+ if key:+ return str(key)+ return "UTC"+++def _resolve_task_prompt(args) -> str:+ prompt = (getattr(args, "prompt", None) or "").strip()+ prompt_file = getattr(args, "prompt_file", None)+ if prompt and prompt_file:+ raise ValueError("use either --prompt or --prompt-file")+ if prompt:+ return prompt+ if prompt_file:+ return Path(prompt_file).read_text(encoding="utf-8").strip()+ raise ValueError("one of --prompt or --prompt-file is required")+++def _normalize_run_at(value: str, timezone_name: str) -> str:+ dt = datetime.fromisoformat(value)+ tz = ZoneInfo(timezone_name)+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=tz)+ else:+ dt = dt.astimezone(tz)+ return dt.isoformat()+++def _task_payload(task):+ return task.to_dict()+++def _task_store() -> ScheduledTaskStore:+ return ScheduledTaskStore()+++def cmd_task_add(args):+ try:+ parse_session_key(args.session_key)+ prompt = _resolve_task_prompt(args)+ timezone_name = args.timezone or _default_timezone_name()+ ZoneInfo(timezone_name)+ store = _task_store()++ if args.cron:+ CronTrigger.from_crontab(args.cron, timezone=ZoneInfo(timezone_name))+ task = store.add_task(+ session_key=args.session_key,+ prompt=prompt,+ schedule_type="cron",+ cron=args.cron,+ timezone_name=timezone_name,+ )+ else:+ run_at = _normalize_run_at(args.at, timezone_name)+ task = store.add_task(+ session_key=args.session_key,+ prompt=prompt,+ schedule_type="at",+ run_at=run_at,+ timezone_name=timezone_name,+ )+ print(json.dumps({"ok": True, "task": _task_payload(task)}, indent=2))+ return 0+ except Exception as exc:+ print(json.dumps({"ok": False, "error": str(exc)}), file=sys.stderr)+ return 1+++def cmd_task_list():+ store = _task_store()+ print(json.dumps({"tasks": [_task_payload(task) for task in store.list_tasks()]}, indent=2))+ return 0+++def cmd_task_show(task_id: str):+ store = _task_store()+ task = store.get_task(task_id)+ if task is None:+ print(json.dumps({"ok": False, "error": f"task '{task_id}' not found"}), file=sys.stderr)+ return 1+ print(json.dumps({"ok": True, "task": _task_payload(task)}, indent=2))+ return 0+++def cmd_task_set_enabled(task_id: str, enabled: bool):+ store = _task_store()+ task = store.get_task(task_id)+ if task is None:+ print(json.dumps({"ok": False, "error": f"task '{task_id}' not found"}), file=sys.stderr)+ return 1+ updated = store.set_enabled(task_id, enabled)+ print(json.dumps({"ok": True, "task": _task_payload(updated)}, indent=2))+ return 0+++def cmd_task_remove(task_id: str):+ store = _task_store()+ removed = store.remove_task(task_id)+ if not removed:+ print(json.dumps({"ok": False, "error": f"task '{task_id}' not found"}), file=sys.stderr)+ return 1+ print(json.dumps({"ok": True, "removed_id": task_id}, indent=2))+ return 0++def _doctor():"""Run diagnostic checks and return results in UI-compatible format.@@ -669,6 +786,33 @@ def build_parser():subparsers.add_parser("version", help="Show version")subparsers.add_parser("check-update", help="Check for updates")subparsers.add_parser("upgrade", help="Upgrade to latest version")++ task_parser = subparsers.add_parser("task", help="Manage scheduled tasks")+ task_subparsers = task_parser.add_subparsers(dest="task_command")++ task_add_parser = task_subparsers.add_parser("add", help="Create a scheduled task")+ task_add_parser.add_argument("--session-key", required=True, help="Target session key")+ schedule_group = task_add_parser.add_mutually_exclusive_group(required=True)+ schedule_group.add_argument("--cron", help="Cron expression in crontab format")+ schedule_group.add_argument("--at", help="One-shot timestamp in ISO 8601 format")+ prompt_group = task_add_parser.add_mutually_exclusive_group(required=True)+ prompt_group.add_argument("--prompt", help="Prompt text to send")+ prompt_group.add_argument("--prompt-file", help="Read prompt text from a file")+ task_add_parser.add_argument("--timezone", help="IANA timezone name")++ task_subparsers.add_parser("list", help="List scheduled tasks")++ task_show_parser = task_subparsers.add_parser("show", help="Show a scheduled task")+ task_show_parser.add_argument("task_id")++ task_pause_parser = task_subparsers.add_parser("pause", help="Pause a scheduled task")+ task_pause_parser.add_argument("task_id")++ task_resume_parser = task_subparsers.add_parser("resume", help="Resume a scheduled task")+ task_resume_parser.add_argument("task_id")++ task_rm_parser = task_subparsers.add_parser("rm", help="Remove a scheduled task")+ task_rm_parser.add_argument("task_id")return parser@@ -691,4 +835,18 @@ def main():sys.exit(cmd_check_update())if args.command == "upgrade":sys.exit(cmd_upgrade())+ if args.command == "task":+ if args.task_command == "add":+ sys.exit(cmd_task_add(args))+ if args.task_command == "list":+ sys.exit(cmd_task_list())+ if args.task_command == "show":+ sys.exit(cmd_task_show(args.task_id))+ if args.task_command == "pause":+ sys.exit(cmd_task_set_enabled(args.task_id, False))+ if args.task_command == "resume":+ sys.exit(cmd_task_set_enabled(args.task_id, True))+ if args.task_command == "rm":+ sys.exit(cmd_task_remove(args.task_id))+ parser.error("task command is required")sys.exit(cmd_vibe())