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): target background work by agent session id
cyh7b6a5c9d971a
diff --git a/config/v2_sessions.py b/config/v2_sessions.pyindex 301e45628..a227b4985 100644--- a/config/v2_sessions.py+++ b/config/v2_sessions.py@@ -316,6 +316,14 @@ class SessionsStore:self.state.session_mappings[user_id][agent_name] = agent_mapreturn agent_map+ def get_agent_session_row_id(self, user_id: str, agent_name: str, thread_id: str) -> Optional[str]:+ self._ensure_service()+ return self._service.get_agent_session_row_id(+ scope_key=user_id,+ agent_name=agent_name,+ session_anchor=thread_id,+ )+def get_thread_map(self, user_id: str, channel_id: str) -> Dict[str, float]:self._ensure_user_namespace(user_id)channel_map = self.state.active_slack_threads[user_id].get(channel_id)diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex 1320ea227..5ddae7e98 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -989,6 +989,26 @@ class SessionHandler(BaseHandler):self.sessions.set_session_mapping(session_key, base_session_id, claude_session_id)logger.info(f"Captured Claude session_id: {claude_session_id} for {base_session_id}")+ return self.sessions.get_agent_session_row_id(session_key, base_session_id, "claude")++ def attach_agent_session_id(+ self,+ context: MessageContext,+ *,+ session_key: str,+ agent_name: str,+ session_anchor: str,+ ) -> Optional[str]:+ getter = getattr(self.sessions, "get_agent_session_row_id", None)+ if not callable(getter):+ return None+ agent_session_id = getter(session_key, session_anchor, agent_name)+ if not agent_session_id:+ return None+ payload = dict(context.platform_specific or {})+ payload["agent_session_id"] = agent_session_id+ context.platform_specific = payload+ return agent_session_iddef restore_session_mappings(self):"""Restore session mappings from settings on startup"""diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex c3823a473..db7bf5c66 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -16,9 +16,14 @@ from zoneinfo import ZoneInfofrom apscheduler.schedulers.asyncio import AsyncIOSchedulerfrom apscheduler.triggers.cron import CronTriggerfrom apscheduler.triggers.date import DateTrigger+from sqlalchemy import select+from sqlalchemy.exc import SQLAlchemyErrorfrom config import pathsfrom modules.im import MessageContext+from storage.db import create_sqlite_engine+from storage.background import SQLiteBackgroundTaskStore+from storage.models import agent_sessions, scopeslogger = logging.getLogger(__name__)@@ -83,6 +88,84 @@ def parse_session_key(value: str) -> ParsedSessionKey:)+@dataclass(frozen=True)+class ResolvedSessionIdTarget:+ session_id: str+ session_key: ParsedSessionKey+ agent_backend: str+ agent_variant: str+ native_session_id: str+ workdir: Optional[str] = None+++def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None) -> ResolvedSessionIdTarget:+ raw = (session_id or "").strip()+ if not raw:+ raise ValueError("session id is required")++ engine = create_sqlite_engine(db_path or paths.get_sqlite_state_path())+ try:+ with engine.connect() as conn:+ row = conn.execute(+ select(+ agent_sessions.c.id,+ agent_sessions.c.agent_backend,+ agent_sessions.c.agent_variant,+ agent_sessions.c.session_anchor,+ agent_sessions.c.workdir,+ agent_sessions.c.native_session_id,+ scopes.c.platform,+ scopes.c.scope_type,+ scopes.c.native_id,+ )+ .join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True)+ .where(agent_sessions.c.id == raw)+ .limit(1)+ ).mappings().first()+ except SQLAlchemyError as exc:+ raise ValueError(f"agent session id not found: {raw}") from exc+ finally:+ engine.dispose()++ if row is None:+ raise ValueError(f"agent session id not found: {raw}")+ platform = str(row["platform"] or "")+ scope_type = str(row["scope_type"] or "")+ scope_id = str(row["native_id"] or "")+ if not platform or scope_type not in {"channel", "user"} or not scope_id:+ raise ValueError(f"agent session id cannot be used as a task target: {raw}")++ anchor = str(row["session_anchor"] or "")+ thread_id = _thread_id_from_session_anchor(anchor, platform=platform, scope_id=scope_id)+ return ResolvedSessionIdTarget(+ session_id=raw,+ session_key=ParsedSessionKey(+ platform=platform,+ scope_type=scope_type,+ scope_id=scope_id,+ thread_id=thread_id,+ ),+ agent_backend=str(row["agent_backend"] or ""),+ agent_variant=str(row["agent_variant"] or ""),+ native_session_id=str(row["native_session_id"] or ""),+ workdir=row["workdir"],+ )+++def _thread_id_from_session_anchor(anchor: str, *, platform: str, scope_id: str) -> Optional[str]:+ if not anchor:+ return None+ base_anchor = anchor+ if ":" in base_anchor:+ base_anchor = base_anchor.split(":", 1)[0]+ prefix = f"{platform}_"+ if base_anchor.startswith(prefix):+ base_anchor = base_anchor[len(prefix) :]+ if base_anchor and base_anchor != scope_id:+ return base_anchor+ return None++def build_session_key_for_context(context: MessageContext,*,@@ -109,6 +192,7 @@ class ScheduledTask:session_key: strprompt: strschedule_type: str+ session_id: Optional[str] = Nonepost_to: Optional[str] = Nonedeliver_key: Optional[str] = Nonecron: Optional[str] = None@@ -131,6 +215,7 @@ class ScheduledTask:session_key=str(payload.get("session_key") or ""),prompt=str(payload.get("prompt") or ""),schedule_type=str(payload.get("schedule_type") or ""),+ session_id=(str(payload["session_id"]).strip() if payload.get("session_id") else None),post_to=payload.get("post_to"),deliver_key=payload.get("deliver_key"),cron=payload.get("cron"),@@ -151,6 +236,7 @@ class TaskExecutionRequest:created_at: str = field(default_factory=_utc_now_iso)task_id: Optional[str] = Nonesession_key: Optional[str] = None+ session_id: Optional[str] = Nonepost_to: Optional[str] = Nonedeliver_key: Optional[str] = Noneprompt: Optional[str] = None@@ -166,6 +252,7 @@ class TaskExecutionRequest:created_at=str(payload.get("created_at") or _utc_now_iso()),task_id=payload.get("task_id"),session_key=payload.get("session_key"),+ session_id=payload.get("session_id"),post_to=payload.get("post_to"),deliver_key=payload.get("deliver_key"),prompt=payload.get("prompt"),@@ -175,11 +262,18 @@ class TaskExecutionRequest:class ScheduledTaskStore:def __init__(self, path: Optional[Path] = None):self.path = path or (paths.get_state_dir() / "scheduled_tasks.json")+ self._sqlite = SQLiteBackgroundTaskStore() if path is None else Noneself._signature: Optional[tuple[int, int, int]] = Noneself._tasks: Dict[str, ScheduledTask] = {}self.load()def load(self) -> None:+ if self._sqlite is not None:+ self._tasks = {+ item["id"]: ScheduledTask.from_dict(item)+ for item in self._sqlite.list_scheduled_tasks()+ }+ returnif not self.path.exists():self._tasks = {}self._signature = None@@ -203,6 +297,11 @@ class ScheduledTaskStore:self._signature = _path_signature(self.path)def maybe_reload(self) -> bool:+ if self._sqlite is not None:+ changed = self._sqlite.maybe_reload()+ if changed:+ self.load()+ return changedsignature = _path_signature(self.path)if signature == self._signature:return False@@ -210,6 +309,8 @@ class ScheduledTaskStore:return Truedef _save(self) -> None:+ if self._sqlite is not None:+ returnself.path.parent.mkdir(parents=True, exist_ok=True)payload = {"tasks": [task.to_dict() for task in self.list_tasks()]}with tempfile.NamedTemporaryFile(@@ -233,6 +334,9 @@ class ScheduledTaskStore:def upsert_task(self, task: ScheduledTask) -> ScheduledTask:task.updated_at = _utc_now_iso()self._tasks[task.id] = task+ if self._sqlite is not None:+ self._sqlite.upsert_scheduled_task(task.to_dict())+ return taskself._save()return task@@ -241,6 +345,7 @@ class ScheduledTaskStore:*,name: Optional[str] = None,session_key: str,+ session_id: Optional[str] = None,prompt: str,schedule_type: str,post_to: Optional[str] = None,@@ -253,6 +358,7 @@ class ScheduledTaskStore:id=uuid4().hex[:12],name=name,session_key=session_key,+ session_id=session_id,prompt=prompt,schedule_type=schedule_type,post_to=post_to,@@ -267,6 +373,9 @@ class ScheduledTaskStore:if task_id not in self._tasks:return Falsedel self._tasks[task_id]+ if self._sqlite is not None:+ self._sqlite.remove_task(task_id)+ return Trueself._save()return True@@ -274,6 +383,9 @@ class ScheduledTaskStore:task = self._tasks[task_id]task.enabled = enabledtask.updated_at = _utc_now_iso()+ if self._sqlite is not None:+ self._sqlite.upsert_scheduled_task(task.to_dict())+ return taskself._save()return task@@ -290,10 +402,12 @@ class ScheduledTaskStore:cron: Optional[str],run_at: Optional[str],timezone_name: str,+ session_id: Optional[str] = None,) -> ScheduledTask:task = self._tasks[task_id]task.name = nametask.session_key = session_key+ task.session_id = session_idtask.prompt = prompttask.schedule_type = schedule_typetask.post_to = post_to@@ -315,6 +429,9 @@ class ScheduledTaskStore:if disable_one_shot and task.schedule_type == "at":task.enabled = Falsetask.updated_at = _utc_now_iso()+ if self._sqlite is not None:+ self._sqlite.upsert_scheduled_task(task.to_dict())+ return Trueself._save()return True@@ -322,12 +439,15 @@ class ScheduledTaskStore:class TaskExecutionStore:def __init__(self, root: Optional[Path] = None):self.root = root or (paths.get_state_dir() / "task_requests")+ self._sqlite = SQLiteBackgroundTaskStore() if root is None else Noneself.pending_dir = self.root / "pending"self.processing_dir = self.root / "processing"self.completed_dir = self.root / "completed"self._ensure_dirs()def _ensure_dirs(self) -> None:+ if self._sqlite is not None:+ returnself.pending_dir.mkdir(parents=True, exist_ok=True)self.processing_dir.mkdir(parents=True, exist_ok=True)self.completed_dir.mkdir(parents=True, exist_ok=True)@@ -341,6 +461,9 @@ class TaskExecutionStore:return directory / f"{request_id}.json"def recover_processing(self) -> None:+ if self._sqlite is not None:+ self._sqlite.recover_processing_runs()+ returnself._ensure_dirs()for path in self.processing_dir.glob("*.json"):pending_path = self.pending_dir / path.name@@ -354,6 +477,12 @@ class TaskExecutionStore:path.replace(pending_path)def enqueue(self, request: TaskExecutionRequest) -> TaskExecutionRequest:+ if self._sqlite is not None:+ payload = request.to_dict()+ payload["status"] = "pending"+ payload["updated_at"] = request.created_at+ self._sqlite.enqueue_run(payload)+ return requestself._ensure_dirs()path = self._request_path(request.id, state="pending")with tempfile.NamedTemporaryFile(@@ -375,6 +504,7 @@ class TaskExecutionStore:self,*,session_key: str,+ session_id: Optional[str] = None,prompt: str,post_to: Optional[str] = None,deliver_key: Optional[str] = None,@@ -384,6 +514,7 @@ class TaskExecutionStore:id=uuid4().hex[:12],request_type="hook_send",session_key=session_key,+ session_id=session_id,post_to=post_to,deliver_key=deliver_key,prompt=prompt,@@ -391,6 +522,12 @@ class TaskExecutionStore:)def list_pending(self) -> list[TaskExecutionRequest]:+ if self._sqlite is not None:+ return [+ TaskExecutionRequest.from_dict(item)+ for item in self._sqlite.list_runs(status="pending")+ if item.get("request_type") in {"task_run", "hook_send"}+ ]self._ensure_dirs()requests: list[TaskExecutionRequest] = []for path in self.pending_dir.glob("*.json"):@@ -405,6 +542,15 @@ class TaskExecutionStore:return sorted(requests, key=lambda item: (item.created_at, item.id))def claim(self, request_id: str) -> Optional[TaskExecutionRequest]:+ if self._sqlite is not None:+ payload = self._sqlite.get_run(request_id)+ if not payload or payload.get("status") != "pending":+ return None+ now = _utc_now_iso()+ self._sqlite.update_run_status(request_id, status="processing", started_at=now, updated_at=now)+ payload["status"] = "processing"+ payload["started_at"] = now+ return TaskExecutionRequest.from_dict(payload)pending_path = self._request_path(request_id, state="pending")processing_path = self._request_path(request_id, state="processing")if not pending_path.exists():@@ -414,6 +560,9 @@ class TaskExecutionStore:return TaskExecutionRequest.from_dict(payload)def requeue(self, request_id: str) -> None:+ if self._sqlite is not None:+ self._sqlite.update_run_status(request_id, status="pending", updated_at=_utc_now_iso())+ returnprocessing_path = self._request_path(request_id, state="processing")pending_path = self._request_path(request_id, state="pending")if not processing_path.exists():@@ -431,7 +580,18 @@ class TaskExecutionStore:error: Optional[str] = None,task_id: Optional[str] = None,session_key: Optional[str] = None,+ session_id: Optional[str] = None,) -> None:+ if self._sqlite is not None:+ self._sqlite.update_run_status(+ request.id,+ status="completed" if ok else "failed",+ error=error,+ completed_at=_utc_now_iso(),+ updated_at=_utc_now_iso(),+ metadata={"ok": ok},+ )+ returnprocessing_path = self._request_path(request.id, state="processing")completed_path = self._request_path(request.id, state="completed")payload = request.to_dict()@@ -442,6 +602,7 @@ class TaskExecutionStore:"completed_at": _utc_now_iso(),"task_id": task_id if task_id is not None else request.task_id,"session_key": session_key if session_key is not None else request.session_key,+ "session_id": session_id if session_id is not None else request.session_id,})with tempfile.NamedTemporaryFile(@@ -551,6 +712,7 @@ class ScheduledTaskService:task.cron,task.run_at,task.timezone,+ task.session_id,task.session_key,task.prompt,task.enabled,@@ -612,6 +774,7 @@ class ScheduledTaskService:should_complete = Truetask_id = request.task_idsession_key = request.session_key+ session_id = request.session_idtry:if request.request_type == "task_run":self.store.maybe_reload()@@ -620,12 +783,14 @@ class ScheduledTaskService:raise ValueError(f"task '{request.task_id}' not found")task_id = task.idsession_key = task.session_key+ session_id = task.session_iderror = await self._execute_task(task, execution_id=request.id, disable_one_shot=False)elif request.request_type == "hook_send":- if not request.session_key or not request.prompt:- raise ValueError("hook request requires both session_key and prompt")+ if not (request.session_id or request.session_key) or not request.prompt:+ raise ValueError("hook request requires session_id or session_key, plus prompt")error = await self._execute_request(session_key=request.session_key,+ session_id=request.session_id,post_to=request.post_to,deliver_key=request.deliver_key,prompt=request.prompt,@@ -649,6 +814,7 @@ class ScheduledTaskService:error=error,task_id=task_id,session_key=session_key,+ session_id=session_id,)async def _execute_task(@@ -662,6 +828,7 @@ class ScheduledTaskService:try:error = await self._execute_request(session_key=task.session_key,+ session_id=task.session_id,post_to=task.post_to,deliver_key=task.deliver_key,prompt=task.prompt,@@ -683,15 +850,17 @@ class ScheduledTaskService:async def _execute_request(self,*,- session_key: str,+ session_key: Optional[str],post_to: Optional[str],deliver_key: Optional[str],prompt: str,execution_id: str,task_id: Optional[str] = None,trigger_kind: str,+ session_id: Optional[str] = None,) -> Optional[str]:- target = parse_session_key(session_key)+ target_info = resolve_session_id_target(session_id) if session_id else None+ target = target_info.session_key if target_info else parse_session_key(session_key or "")delivery_target = self._resolve_delivery_target(session_target=target,post_to=post_to,@@ -703,6 +872,8 @@ class ScheduledTaskService:execution_id=execution_id,task_id=task_id,trigger_kind=trigger_kind,+ session_id=session_id,+ target_info=target_info,)return await self.controller.message_handler.handle_scheduled_message(context=context,@@ -718,6 +889,8 @@ class ScheduledTaskService:execution_id: str,task_id: Optional[str] = None,trigger_kind: str = "scheduled",+ session_id: Optional[str] = None,+ target_info: Optional[ResolvedSessionIdTarget] = None,) -> MessageContext:platform = target.platformself.validate_platform(platform)@@ -745,6 +918,7 @@ class ScheduledTaskService:"platform": platform,"is_dm": target.is_dm,"turn_source": "scheduled",+ "agent_session_id": session_id,"session_key_external": target.to_key(),"delivery_key_external": delivery_target.to_key(),"delivery_scope_session_key": delivery_target.session_scope,@@ -758,6 +932,17 @@ class ScheduledTaskService:"scheduled_delivery_alias": delivery_strategy,"task_execution_id": execution_id,"task_trigger_kind": trigger_kind,+ "agent_session_target": (+ {+ "id": target_info.session_id,+ "agent_backend": target_info.agent_backend,+ "agent_variant": target_info.agent_variant,+ "native_session_id": target_info.native_session_id,+ "workdir": target_info.workdir,+ }+ if target_info+ else None+ ),},)@@ -793,7 +978,7 @@ class ScheduledTaskService:if deliver_key:delivery_target = parse_session_key(deliver_key)if delivery_target.platform != session_target.platform:- raise ValueError("--deliver-key must stay on the same platform as --session-key")+ raise ValueError("--deliver-key must stay on the same platform as the session target")return delivery_targetif post_to == "channel":return ParsedSessionKey(@@ -804,7 +989,7 @@ class ScheduledTaskService:)if post_to == "thread":if not session_target.thread_id:- raise ValueError("--post-to thread requires a thread-bound --session-key or an explicit --deliver-key")+ raise ValueError("--post-to thread requires a thread-bound session target or an explicit --deliver-key")return session_targetreturn session_targetdiff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex 2fe678446..ed23ecba8 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -73,13 +73,14 @@ _SCHEDULED_TASKS_PROMPT = """\## 3. Scheduled tasks, watches, and hooksUse `vibe task add` for saved work that should run later on a schedule or at one exact time.Use `vibe watch add` for managed background waiters that should keep running until a condition is met and then send a follow-up.-Use `vibe hook send --session-key ... --prompt ...` for one-shot asynchronous sends without saving a task or watch.+Use `vibe hook send --session-id ... --prompt ...` for one-shot asynchronous sends without saving a task or watch.Current conversation targeting:-- Current session key: `{default_session_key}`+- Current session id: `{default_session_id}`Rules:-- `session_key` controls the conversation scope that Vibe Remote will continue using.+- Use `--session-id {default_session_id}` when scheduling work; it targets the exact Vibe Remote agent session to continue.+- If the current session id is not available yet, do not guess a target; ask the user to retry from an active Vibe Remote session.- `--post-to` changes the delivery target, not the session scope. Use `--post-to channel` when the session should stay thread-scoped but the follow-up message should be posted to the parent channel.- Use `--cron "<expr>"` for recurring tasks or `--at "<ISO-8601>"` for one-off stored tasks.- Use `vibe watch list`, `vibe watch show`, `vibe watch pause`, `vibe watch resume`, and `vibe watch remove` to manage background work after creation.@@ -107,31 +108,11 @@ Keep entries short, deduplicated, and free of secrets unless the user explicitly"""-def _build_prompt_session_key(- context: MessageContext,- *,- include_thread: bool,- fallback_platform: Optional[str] = None,-) -> str:- platform_specific = context.platform_specific or {}- platform = context.platform or platform_specific.get("platform") or fallback_platform or "<platform>"- is_dm = bool(platform_specific.get("is_dm", False))- scope_type = "user" if is_dm else "channel"- scope_id = context.user_id if is_dm else context.channel_id- base = f"{platform}::{scope_type}::{scope_id}"- if include_thread and context.thread_id:- return f"{base}::thread::{context.thread_id}"- return base--def _build_scheduled_tasks_prompt(context: MessageContext, *, fallback_platform: Optional[str] = None) -> str:- default_key = _build_prompt_session_key(- context,- include_thread=True,- fallback_platform=fallback_platform,- )+ platform_specific = context.platform_specific or {}+ default_session_id = str(platform_specific.get("agent_session_id") or "<not available yet>")return _SCHEDULED_TASKS_PROMPT.format(- default_session_key=default_key,+ default_session_id=default_session_id,)diff --git a/core/watches.py b/core/watches.pyindex ed601ae49..323b4222e 100644--- a/core/watches.py+++ b/core/watches.py@@ -15,6 +15,7 @@ from uuid import uuid4from config import pathsfrom core.process_isolation import isolated_subprocess_kwargs, terminate_and_communicatefrom core.scheduled_tasks import TaskExecutionStore+from storage.background import SQLiteBackgroundTaskStorelogger = logging.getLogger(__name__)@@ -45,6 +46,7 @@ class ManagedWatch:id: strname: Optional[str]session_key: str+ session_id: Optional[str] = Nonecommand: list[str] = field(default_factory=list)shell_command: Optional[str] = Noneprefix: Optional[str] = None@@ -74,6 +76,7 @@ class ManagedWatch:id=str(payload.get("id") or uuid4().hex[:12]),name=(str(payload["name"]).strip() if payload.get("name") is not None else None) or None,session_key=str(payload.get("session_key") or ""),+ session_id=(str(payload["session_id"]).strip() if payload.get("session_id") else None),command=list(payload.get("command") or []),shell_command=(str(payload["shell_command"]).strip() if payload.get("shell_command") else None) or None,prefix=(str(payload["prefix"]).strip() if payload.get("prefix") else None) or None,@@ -99,11 +102,18 @@ class ManagedWatch:class ManagedWatchStore:def __init__(self, path: Optional[Path] = None):self.path = path or paths.get_watches_path()+ self._sqlite = SQLiteBackgroundTaskStore() if path is None else Noneself._signature: Optional[tuple[int, int, int]] = Noneself._watches: dict[str, ManagedWatch] = {}self.load()def load(self) -> None:+ if self._sqlite is not None:+ self._watches = {+ item["id"]: ManagedWatch.from_dict(item)+ for item in self._sqlite.list_watches()+ }+ returnif not self.path.exists():self._watches = {}self._signature = None@@ -127,6 +137,11 @@ class ManagedWatchStore:self._signature = _path_signature(self.path)def maybe_reload(self) -> bool:+ if self._sqlite is not None:+ changed = self._sqlite.maybe_reload()+ if changed:+ self.load()+ return changedsignature = _path_signature(self.path)if signature == self._signature:return False@@ -134,6 +149,8 @@ class ManagedWatchStore:return Truedef _save(self) -> None:+ if self._sqlite is not None:+ returnself.path.parent.mkdir(parents=True, exist_ok=True)payload = {"watches": [watch.to_dict() for watch in self.list_watches()]}with tempfile.NamedTemporaryFile(@@ -157,6 +174,9 @@ class ManagedWatchStore:def upsert_watch(self, watch: ManagedWatch) -> ManagedWatch:watch.updated_at = _utc_now_iso()self._watches[watch.id] = watch+ if self._sqlite is not None:+ self._sqlite.upsert_watch(watch.to_dict())+ return watchself._save()return watch@@ -176,11 +196,13 @@ class ManagedWatchStore:retry_delay_seconds: float,post_to: Optional[str],deliver_key: Optional[str],+ session_id: Optional[str] = None,) -> ManagedWatch:watch = ManagedWatch(id=uuid4().hex[:12],name=name,session_key=session_key,+ session_id=session_id,command=command,shell_command=shell_command,prefix=prefix,@@ -199,6 +221,9 @@ class ManagedWatchStore:if watch_id not in self._watches:return Falsedel self._watches[watch_id]+ if self._sqlite is not None:+ self._sqlite.remove_task(watch_id)+ return Trueself._save()return True@@ -206,6 +231,9 @@ class ManagedWatchStore:watch = self._watches[watch_id]watch.enabled = enabledwatch.updated_at = _utc_now_iso()+ if self._sqlite is not None:+ self._sqlite.upsert_watch(watch.to_dict())+ return watchself._save()return watch@@ -217,6 +245,9 @@ class ManagedWatchStore:watch.last_started_at = _utc_now_iso()watch.last_error = Nonewatch.updated_at = _utc_now_iso()+ if self._sqlite is not None:+ self._sqlite.upsert_watch(watch.to_dict())+ return Trueself._save()return True@@ -241,6 +272,9 @@ class ManagedWatchStore:if disable:watch.enabled = Falsewatch.updated_at = _utc_now_iso()+ if self._sqlite is not None:+ self._sqlite.upsert_watch(watch.to_dict())+ return Trueself._save()return True@@ -248,8 +282,12 @@ class ManagedWatchStore:class WatchRuntimeStateStore:def __init__(self, path: Optional[Path] = None):self.path = path or paths.get_watch_runtime_path()+ self._sqlite = SQLiteBackgroundTaskStore() if path is None else Nonedef write(self, payload: dict[str, Any]) -> None:+ if self._sqlite is not None:+ self._sqlite.write_watch_runtime(payload, updated_at=_utc_now_iso())+ returnself.path.parent.mkdir(parents=True, exist_ok=True)with tempfile.NamedTemporaryFile(mode="w",@@ -263,6 +301,8 @@ class WatchRuntimeStateStore:tmp_path.replace(self.path)def load(self) -> dict[str, Any]:+ if self._sqlite is not None:+ return self._sqlite.load_watch_runtime()if not self.path.exists():return {"watches": {}}try:@@ -516,6 +556,7 @@ class ManagedWatchService:returnself.request_store.enqueue_hook_send(session_key=watch.session_key,+ session_id=watch.session_id,post_to=watch.post_to,deliver_key=watch.deliver_key,prompt=final_prompt,diff --git a/docs/CLI.md b/docs/CLI.mdindex 69d784b0b..8b9fa69d4 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -161,7 +161,7 @@ vibe screenshot --jsonCreate, inspect, update, run, pause, resume, or remove scheduled tasks.```bash-vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *' --prompt 'Share the hourly summary.'+vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --prompt 'Share the hourly summary.'vibe task list --briefvibe task update <task-id> --cron '*/30 * * * *'vibe task run <task-id>@@ -170,19 +170,22 @@ vibe task remove <task-id>Use `vibe task add --help` and `vibe task update --help` for the full command surface, including:-- `--session-key` for session continuity+- `--session-id` for Agent Session continuity- `--post-to channel` to publish into the parent channel while keeping thread context- `--deliver-key` for an explicit delivery target- `--cron` and `--at` scheduling- `--name`, `--timezone`, and prompt file support+`--session-key` remains accepted for older scripts, but new tasks should use+the Agent Session ID shown in the active Vibe Remote prompt.+### `vibe hook send`Queue one asynchronous turn without storing a scheduled task definition.```bash-vibe hook send --session-key 'slack::channel::C123' --prompt 'The export finished. Share the summary.'-vibe hook send --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --prompt 'Share the benchmark result in the channel.'+vibe hook send --session-id sesk8m4q2p7x --prompt 'The export finished. Share the summary.'+vibe hook send --session-id sesk8m4q2p7x --post-to channel --prompt 'Share the benchmark result in the channel.'```Use this when you want one delayed or background follow-up without persisting a task in `scheduled_tasks.json`.@@ -196,13 +199,13 @@ stdout and delivers it through the chosen session as a follow-up message.```bashvibe watch add \- --session-key 'slack::channel::C123' \+ --session-id sesk8m4q2p7x \--prefix 'Test run finished. Summarize the failures and propose next steps.' \-- ./scripts/run_tests.sh# Alternative: pass the command through a shell with --shellvibe watch add \- --session-key 'slack::channel::C123' \+ --session-id sesk8m4q2p7x \--prefix 'Build done. Summarize.' \--shell 'make build && ./scripts/post_build.sh'@@ -218,7 +221,7 @@ string via `--shell`). Use `vibe watch add --help` for the full surface,including `--timeout` (per-cycle timeout in seconds), `--lifetime-timeout`(total wall-clock limit), `--forever`, `--retry-exit-code`, `--retry-delay`,`--post-to channel`, `--deliver-key`, and `--name`. Watches share-`--session-key`, `--post-to`, and `--deliver-key` semantics with `vibe task`+`--session-id`, `--post-to`, and `--deliver-key` semantics with `vibe task`and `vibe hook send`. Prefer `vibe watch` over ad-hoc `nohup` jobs when theuser wants a managed background task with a guaranteed follow-up message.@@ -348,12 +351,12 @@ The web UI (`http://127.0.0.1:5123`) provides the same controls:| Path | Description ||------|-------------|| `~/.vibe_remote/config/config.json` | Main configuration |-| `~/.vibe_remote/state/vibe.sqlite` | Internal database managed by Vibe Remote — opaque; manage state through the Web UI or `vibe` CLI, never read or write this file directly |+| `~/.vibe_remote/state/vibe.sqlite` | Internal database managed by Vibe Remote; stores settings, sessions, scheduled tasks, watches, and background run records || `~/.vibe_remote/state/discovered_chats.json` | Discovered IM chats/channels surfaced by platform adapters || `~/.vibe_remote/state/settings.json` | Legacy JSON snapshot of channel routing settings |-| `~/.vibe_remote/state/scheduled_tasks.json` | Persisted scheduled task definitions |-| `~/.vibe_remote/state/watches.json` | Persisted managed watch definitions |-| `~/.vibe_remote/state/task_requests/` | Queued task run and hook execution requests |+| `~/.vibe_remote/state/scheduled_tasks.json` | Legacy scheduled task definitions imported into SQLite on startup |+| `~/.vibe_remote/state/watches.json` | Legacy managed watch definitions imported into SQLite on startup |+| `~/.vibe_remote/state/task_requests/` | Legacy queued task/hook requests imported into SQLite on startup || `~/.vibe_remote/state/user_preferences.md` | Shared long-term user preference notes || `~/.vibe_remote/state/backups/` | Automatic state backups taken before migrations || `~/.vibe_remote/runtime/remote-access-cloudflared.pid` | cloudflared tunnel PID for Vibe Cloud remote access |diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex af0e2bb96..a0949ab45 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -146,7 +146,7 @@ vibe screenshot --json创建、查看、更新、立即执行、暂停、恢复或删除定时任务。```bash-vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *' --prompt 'Share the hourly summary.'+vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --prompt 'Share the hourly summary.'vibe task list --briefvibe task update <task-id> --cron '*/30 * * * *'vibe task run <task-id>@@ -155,19 +155,22 @@ vibe task remove <task-id>更完整的参数说明请直接看 `vibe task add --help` 和 `vibe task update --help`。其中重点包括:-- 用 `--session-key` 指定会话连续性+- 用 `--session-id` 指定要延续的 Agent Session- 用 `--post-to channel` 在保留 thread 上下文的同时把消息发到父频道- 用 `--deliver-key` 指定显式投递目标- 用 `--cron` / `--at` 控制定时方式- 以及 `--name`、`--timezone`、`--prompt-file` 等参数+`--session-key` 仍兼容旧脚本,但新任务应使用当前 Vibe Remote prompt+里展示的 Agent Session ID。+### `vibe hook send`队列化一次异步 turn,不会把任务定义持久化到 `scheduled_tasks.json`。```bash-vibe hook send --session-key 'slack::channel::C123' --prompt 'The export finished. Share the summary.'-vibe hook send --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --prompt 'Share the benchmark result in the channel.'+vibe hook send --session-id sesk8m4q2p7x --prompt 'The export finished. Share the summary.'+vibe hook send --session-id sesk8m4q2p7x --post-to channel --prompt 'Share the benchmark result in the channel.'```适合“只异步补发一次消息,不想保存成定时任务”的场景。diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex a44275d1e..4712819a9 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -693,13 +693,13 @@ vibe upgrade### `vibe task add````bash-vibe task add --session-key <key> (--cron <expr> | --at <timestamp>) (--prompt <text> | --prompt-file <file>) [options]+vibe task add --session-id <session_id> (--cron <expr> | --at <timestamp>) (--prompt <text> | --prompt-file <file>) [options]```Important options:- `--name`-- `--session-key` required+- `--session-id` required for new tasks- `--post-to {thread,channel}`- `--deliver-key`- `--cron`@@ -718,7 +718,7 @@ Important options:- `--name`- `--clear-name`-- `--session-key`+- `--session-id`- `--post-to {thread,channel}`- `--deliver-key`- `--reset-delivery`@@ -771,12 +771,12 @@ Queue one asynchronous turn without creating a stored task definition.### Syntax```bash-vibe hook send --session-key <key> (--prompt <text> | --prompt-file <file>) [options]+vibe hook send --session-id <session_id> (--prompt <text> | --prompt-file <file>) [options]```Important options:-- `--session-key` required+- `--session-id` required for new hooks- `--post-to {thread,channel}`- `--deliver-key`- `--prompt`@@ -816,5 +816,5 @@ vibevibe statusvibe doctorvibe task list --brief-vibe hook send --session-key 'slack::channel::C123' --prompt 'Share the latest build summary.'+vibe hook send --session-id sesk8m4q2p7x --prompt 'Share the latest build summary.'```diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.mdindex 6055638a6..a802c5559 100644--- a/docs/COMMANDS_ZH.md+++ b/docs/COMMANDS_ZH.md@@ -672,13 +672,13 @@ vibe upgrade### `vibe task add````bash-vibe task add --session-key <key> (--cron <表达式> | --at <时间戳>) (--prompt <文本> | --prompt-file <文件>) [options]+vibe task add --session-id <session_id> (--cron <表达式> | --at <时间戳>) (--prompt <文本> | --prompt-file <文件>) [options]```重要参数:- `--name`-- `--session-key` 必填+- `--session-id`,新任务应使用 Agent Session ID- `--post-to {thread,channel}`- `--deliver-key`- `--cron`@@ -697,7 +697,7 @@ vibe task update <task_id> [options]- `--name`- `--clear-name`-- `--session-key`+- `--session-id`- `--post-to {thread,channel}`- `--deliver-key`- `--reset-delivery`@@ -750,12 +750,12 @@ vibe task remove <task_id>### 语法```bash-vibe hook send --session-key <key> (--prompt <文本> | --prompt-file <文件>) [options]+vibe hook send --session-id <session_id> (--prompt <文本> | --prompt-file <文件>) [options]```重要参数:-- `--session-key` 必填+- `--session-id`,新 hook 应使用 Agent Session ID- `--post-to {thread,channel}`- `--deliver-key`- `--prompt`@@ -795,5 +795,5 @@ vibevibe statusvibe doctorvibe task list --brief-vibe hook send --session-key 'slack::channel::C123' --prompt 'Share the latest build summary.'+vibe hook send --session-id sesk8m4q2p7x --prompt 'Share the latest build summary.'```diff --git a/docs/plans/background-session-id-tasks.md b/docs/plans/background-session-id-tasks.mdnew file mode 100644index 000000000..3fe7da9ee--- /dev/null+++ b/docs/plans/background-session-id-tasks.md@@ -0,0 +1,237 @@+# Background Tasks With Stable Agent Sessions++## Background++Scheduled tasks, hooks, and watches currently target conversations through an+external `session_key` such as:++```text+slack::channel::C123::thread::171717.123+```++That key is useful for bootstrapping a turn from an IM surface, but it is not+the durable identity of the agent session. Vibe Remote already has an+`agent_sessions` table whose `id` was explicitly designed as the short handle+that can be shown to agents, passed to CLI commands, and referenced by future+Web UI task management.++The intended `agent_sessions.id` format is:++```text+ses + 10 lowercase base32-like characters+```++Example:++```text+sesk8m4q2p7x+```++It is short, symbol-free, non-numeric, and copyable in chat. The current+implementation has a critical bug: `SQLiteSessionsService.save_state()` rebuilds+`agent_sessions` from the legacy in-memory session mappings and generates new+row IDs on every save. That breaks the original contract. Before any task/watch+feature references `agent_sessions.id`, the ID must become stable.++## Goals++- Make `agent_sessions.id` stable across saves and service restarts.+- Inject the current `session_id` into agent prompts as the primary target for+ background commands.+- Add `--session-id` to `vibe task`, `vibe hook`, and `vibe watch`.+- Keep `--session-key` as a compatibility path for old scripts and persisted+ tasks, but do not teach it in new agent-facing prompt text.+- Design the future SQLite background task tables around `session_id`, not+ external `session_key`.++## Non-Goals++- Do not solve the future "create a brand-new session on each run" product+ model in this change. That will get a separate design.+- Do not remove `--session-key` yet.+- Do not require the Web UI to manage tasks in this first slice.++## Session Identity Rules++### Stable Agent Session IDs++`agent_sessions.id` is the user-facing Vibe Remote session handle. It must not+change when:++- a session mapping is saved again;+- active thread/poll/dedup runtime state changes;+- the service restarts;+- task/watch state is updated.++The persistence layer should preserve existing IDs by matching the durable+business identity of a session:++| Component | Meaning |+| --- | --- |+| `scope_id` | IM scope resolved from the legacy session scope key |+| `agent_variant` | agent or subagent namespace |+| `session_anchor` | conversation anchor / base session id / composite key |+| `native_session_id` | backend-native session/thread id |++`workdir` is still stored and indexed, but is not sufficient by itself as a+unique identity. OpenCode already embeds workdir in the `session_anchor`, while+Claude/Codex use backend-native session ids to distinguish resumed sessions.++### Prompt Injection++The prompt should use `session_id` as the primary background target:++```text+Current conversation targeting:+- Current session id: sesk8m4q2p7x+```++Rules shown to agents should prefer:++```bash+vibe task add --session-id sesk8m4q2p7x ...+vibe hook send --session-id sesk8m4q2p7x ...+vibe watch add --session-id sesk8m4q2p7x ...+```++The injected prompt must not mention the legacy session key or show+`--session-key` examples. Old targeting belongs only in compatibility code and+low-prominence CLI/help text for existing scripts.++## CLI Compatibility++The new public flag is `--session-id`.++| Command | New primary flag | Legacy flag |+| --- | --- | --- |+| `vibe task add` | `--session-id` | `--session-key` |+| `vibe task update` | `--session-id` | `--session-key` |+| `vibe hook send` | `--session-id` | `--session-key` |+| `vibe watch add` | `--session-id` | `--session-key` |++Validation:++- Require exactly one of `--session-id` or `--session-key` for new add/send+ commands.+- Reject commands that pass both.+- Keep `--deliver-key` and `--post-to` for explicit delivery overrides.+- When a stored object has `session_id`, resolve through `agent_sessions`.+- When a stored object only has `session_key`, use the legacy resolver.++## Resolving `--session-id`++Resolving a session id should load the `agent_sessions` row and its `scope`.++| Target field | Source |+| --- | --- |+| platform | `scopes.platform` |+| scope type | `scopes.scope_type` |+| scope native id | `scopes.native_id` |+| session anchor | `agent_sessions.session_anchor` |+| agent backend | `agent_sessions.agent_backend` |+| agent variant | `agent_sessions.agent_variant` |+| native session id | `agent_sessions.native_session_id` |+| workdir | `agent_sessions.workdir` |++The execution path should reconstruct a scheduled `MessageContext` that routes+to the same scope and anchor that the session row represents. The agent backend+then resumes the same native session through the normal session mapping.++## Background Tables++Keep the schema small: two tables cover persisted definitions, queued work,+runtime snapshots, and execution history.++### `background_tasks`++| Field | Type | Purpose |+| --- | --- | --- |+| `id` | TEXT PK | background task id |+| `task_type` | TEXT | `scheduled` or `watch` |+| `session_id` | TEXT | primary Agent Session target |+| `legacy_session_key` | TEXT | compatibility target for old tasks and old CLI |+| `name` | TEXT | user-visible name |+| `enabled` | INTEGER | enabled flag |+| `post_to` | TEXT | delivery shortcut |+| `deliver_key` | TEXT | explicit delivery override |+| `prompt` | TEXT | scheduled task prompt |+| `schedule_type` | TEXT | `cron` or `at` |+| `cron` | TEXT | cron expression |+| `run_at` | TEXT | one-off run timestamp |+| `timezone` | TEXT | schedule timezone |+| `command_json` | TEXT | watch argv array |+| `shell_command` | TEXT | watch shell command |+| `prefix` | TEXT | watch follow-up instruction prefix |+| `cwd` | TEXT | watch working directory |+| `mode` | TEXT | `once` or `forever` |+| `timeout_seconds` | REAL | per-cycle timeout |+| `lifetime_timeout_seconds` | REAL | overall forever-watch timeout |+| `retry_exit_codes_json` | TEXT | retryable exit codes |+| `retry_delay_seconds` | REAL | retry delay |+| `last_started_at` | TEXT | latest start time |+| `last_finished_at` | TEXT | latest finish time |+| `last_event_at` | TEXT | latest detected event time |+| `last_run_at` | TEXT | latest scheduled-task run time |+| `last_error` | TEXT | latest error |+| `last_exit_code` | INTEGER | latest exit code |+| `metadata_json` | TEXT | extension payload |+| `created_at` | TEXT | create time |+| `updated_at` | TEXT | update time |++### `background_runs`++| Field | Type | Purpose |+| --- | --- | --- |+| `id` | TEXT PK | run id |+| `task_id` | TEXT | optional `background_tasks.id` |+| `run_type` | TEXT | `scheduled`, `task_run`, `hook_send`, or `watch_runtime` |+| `status` | TEXT | `pending`, `processing`, `completed`, `failed`, or `running` |+| `session_id` | TEXT | actual target session |+| `legacy_session_key` | TEXT | compatibility target |+| `post_to` | TEXT | delivery shortcut snapshot |+| `deliver_key` | TEXT | explicit delivery snapshot |+| `prompt` | TEXT | actual prompt sent |+| `pid` | INTEGER | running process id for watch runtime rows |+| `started_at` | TEXT | start time |+| `completed_at` | TEXT | finish time |+| `exit_code` | INTEGER | process exit code |+| `error` | TEXT | error summary |+| `stdout` | TEXT | bounded stdout when recorded |+| `stderr` | TEXT | bounded stderr when recorded |+| `metadata_json` | TEXT | extension result/runtime payload |+| `created_at` | TEXT | create time |+| `updated_at` | TEXT | update time |++## Migration Strategy++1. Fix `agent_sessions.id` stability first.+2. Add `--session-id` while keeping `--session-key`.+3. Update prompt injection to prefer `--session-id`.+4. Add SQLite background tables and import old JSON state once.+5. Switch task/watch stores to SQLite as the source of truth while preserving+ explicit-path JSON stores for tests and compatibility.++This order keeps old CLI scripts working while making every new task/watch use+the durable agent session handle.++## Implementation Slices++### Slice 1: Session ID Targeting Bridge++Completed bridge before moving task/watch persistence itself to SQLite:++- preserve `agent_sessions.id` across `save_state()` rebuilds;+- attach `agent_session_id` to Claude, Codex, and OpenCode prompt contexts when+ the row already exists or is created;+- inject `Current session id` as the only agent-facing background target;+- add `--session-id` to task, hook, and watch CLI commands;+- resolve `session_id` through SQLite `agent_sessions` at runtime, while still+ accepting old `session_key`-only records.++### Slice 2: SQLite Background Store++This slice adds `background_tasks` and `background_runs`, imports existing JSON+tasks/watches/request state once, and makes SQLite the default source of truth.+It does not change the public targeting contract again: new rows store+`session_id` directly and keep `legacy_session_key` only for compatibility+display/import.diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 096d6e9ea..89543c62b 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -336,7 +336,7 @@ class ClaudeAgent(BaseAgent):touch_session_activity = getattr(self.session_handler, "touch_session_activity", None)if callable(touch_session_activity):touch_session_activity(composite_key)- claude_session_id = self._maybe_capture_session_id(message, base_session_id, session_key)+ claude_session_id = self._maybe_capture_session_id(message, base_session_id, session_key, context)if claude_session_id:logger.info(f"Captured Claude session id {claude_session_id} for {base_session_id}")@@ -696,6 +696,7 @@ class ClaudeAgent(BaseAgent):message,base_session_id: str,session_key: str,+ context: MessageContext,) -> Optional[str]:"""Capture session id from system init messages."""if (@@ -706,7 +707,11 @@ class ClaudeAgent(BaseAgent):):session_id = message.data.get("session_id")if session_id:- self.session_handler.capture_session_id(base_session_id, session_id, session_key)+ agent_session_id = self.session_handler.capture_session_id(base_session_id, session_id, session_key)+ if agent_session_id:+ payload = dict(context.platform_specific or {})+ payload["agent_session_id"] = agent_session_id+ context.platform_specific = payloadreturn session_idreturn Nonediff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 2d46ad9f3..0e5ad7da2 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -499,8 +499,21 @@ class CodexAgent(BaseAgent):request.base_session_id,thread_id,)+ self._attach_agent_session_id(request)return thread_id+ def _attach_agent_session_id(self, request: AgentRequest) -> Optional[str]:+ getter = getattr(self.sessions, "get_agent_session_row_id", None)+ if not callable(getter):+ return None+ agent_session_id = getter(request.session_key, request.base_session_id, self.name)+ if not agent_session_id:+ return None+ payload = dict(request.context.platform_specific or {})+ payload["agent_session_id"] = agent_session_id+ request.context.platform_specific = payload+ return agent_session_id+def _resolve_codex_agent_settings(self,request: AgentRequest,@@ -559,6 +572,7 @@ class CodexAgent(BaseAgent):)if persisted:try:+ self._attach_agent_session_id(request)resume_params: Dict[str, Any] = {"threadId": persisted,"developerInstructions": self._build_thread_developer_instructions(request),diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.pyindex f487ea87d..b8e3a5ff8 100644--- a/modules/agents/codex/event_handler.py+++ b/modules/agents/codex/event_handler.py@@ -94,6 +94,15 @@ class CodexEventHandler:request.base_session_id,thread_id,)+ agent_session_id = self._agent.sessions.get_agent_session_row_id(+ request.session_key,+ request.base_session_id,+ self._agent.name,+ )+ if agent_session_id:+ payload = dict(request.context.platform_specific or {})+ payload["agent_session_id"] = agent_session_id+ request.context.platform_specific = payloadsystem_text = self._agent._get_formatter(request.context).format_system_message(request.working_path,diff --git a/modules/agents/opencode/session.py b/modules/agents/opencode/session.pyindex 3a6f0691b..449a2c917 100644--- a/modules/agents/opencode/session.py+++ b/modules/agents/opencode/session.py@@ -176,6 +176,15 @@ class OpenCodeSessionManager:composite_session_key,session_id,)+ agent_session_id = sessions.get_agent_session_row_id(+ request.session_key,+ composite_session_key,+ self._agent_name,+ )+ if agent_session_id:+ payload = dict(request.context.platform_specific or {})+ payload["agent_session_id"] = agent_session_id+ request.context.platform_specific = payloadlogger.info(f"Created OpenCode session {session_id} for {request.base_session_id}")except Exception as e:logger.error(f"Failed to create OpenCode session: {e}", exc_info=True)@@ -199,6 +208,15 @@ class OpenCodeSessionManager:composite_session_key,new_session_id,)+ agent_session_id = sessions.get_agent_session_row_id(+ request.session_key,+ composite_session_key,+ self._agent_name,+ )+ if agent_session_id:+ payload = dict(request.context.platform_specific or {})+ payload["agent_session_id"] = agent_session_id+ request.context.platform_specific = payloadlogger.info(f"Recreated OpenCode session {new_session_id} for {request.base_session_id}")return new_session_idexcept Exception as e:diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex d0707c1f6..937268bd5 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -50,6 +50,18 @@ class SessionsFacade:agent_map = self.sessions_store.get_agent_map(user_key, agent_name)return agent_map.get(thread_id)+ def get_agent_session_row_id(+ self,+ user_id: Union[int, str],+ thread_id: str,+ agent_name: str,+ ) -> Optional[str]:+ user_key = self._normalize_user_id(user_id)+ getter = getattr(self.sessions_store, "get_agent_session_row_id", None)+ if not callable(getter):+ return None+ return getter(user_key, agent_name, thread_id)+def clear_agent_session_mapping(self,user_id: Union[int, str],diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.mdindex 4b3cb7471..9f3b57d8c 100644--- a/skills/background-watch-hook/SKILL.md+++ b/skills/background-watch-hook/SKILL.md@@ -36,7 +36,7 @@ Prefer `vibe watch` when the wait should be inspectable, pausable, resumable, orUse `vibe watch add` first. Most tasks only need:-1. the target `session_key`+1. the target Agent Session ID2. a short action-oriented prefix3. a blocking waiter command@@ -44,7 +44,7 @@ Generic shape:```bashvibe watch add \- --session-key "<session-key>" \+ --session-id "<session-id>" \--prefix "<what the next turn should do>" \--name "<optional label>" \-- \@@ -62,7 +62,7 @@ Use `--forever` when the same waiter should re-arm after each detected event ins## `vibe watch` Parameters To Remember-- `--session-key`: where the follow-up should go+- `--session-id`: which Agent Session the follow-up should continue- `--prefix`: the instruction text prepended before waiter stdout in the follow-up; when both exist they are joined with a blank line- `--name`: optional label for later management- `--forever`: re-arm after each detected event@@ -96,7 +96,7 @@ Delay:```bashvibe watch add \- --session-key "slack::channel::C123::thread::171717.123" \+ --session-id "sesk8m4q2p7x" \--name "Delay callback" \--prefix "The delayed check completed. Continue from the result below." \-- \@@ -107,7 +107,7 @@ File appears:```bashvibe watch add \- --session-key "slack::channel::C123::thread::171717.123" \+ --session-id "sesk8m4q2p7x" \--name "Wait for export file" \--prefix "The export file is ready. Inspect it and continue." \-- \@@ -118,7 +118,7 @@ Log match:```bashvibe watch add \- --session-key "slack::channel::C123::thread::171717.123" \+ --session-id "sesk8m4q2p7x" \--name "Watch app log" \--prefix "The expected log pattern appeared. Inspect the event and continue." \--forever \@@ -130,13 +130,10 @@ vibe watch add \Use the current Vibe Remote context:-- `session_key` controls which session Vibe Remote will continue using-- keep the current session key when the follow-up should continue the same session-- when you do not want to keep the current thread session and instead want to start or reuse the higher-level session, use the higher-level key-- example: `slack::channel::C123::thread::171717.123` keeps the current thread session, while `slack::channel::C123` creates or reuses the channel-scoped session-- `--post-to channel` only when the follow-up should keep the session chosen by `session_key` but publish in the parent channel--If the current turn does not expose a usable target, ask instead of guessing.+- `session_id` controls which Agent Session Vibe Remote will continue using+- use the current Agent Session ID when the follow-up should continue the same session+- if the current turn does not expose a usable Agent Session ID, ask the user to retry from an active Vibe Remote session instead of guessing+- `--post-to channel` only when the follow-up should keep the same Agent Session but publish in the parent channel## Timeout And Lifecycle@@ -174,7 +171,7 @@ One-shot watch:```bashvibe watch add \- --session-key "slack::channel::C123::thread::171717.123" \+ --session-id "sesk8m4q2p7x" \--name "Watch PR 151 reviews" \--prefix "PR #151 has new review activity. Fetch the latest review state, summarize actionable items, and continue handling them if needed." \-- \@@ -188,7 +185,7 @@ Catch up on existing activity first:```bashvibe watch add \- --session-key "slack::channel::C123::thread::171717.123" \+ --session-id "sesk8m4q2p7x" \--name "Catch up PR 151 reviews" \--prefix "PR #151 already has review activity. Fetch the latest review state and continue handling it if needed." \-- \@@ -202,7 +199,7 @@ Stay armed for future activity:```bashvibe watch add \- --session-key "slack::channel::C123::thread::171717.123" \+ --session-id "sesk8m4q2p7x" \--name "Monitor PR 151 reviews" \--forever \--timeout 21600 \@@ -228,7 +225,7 @@ New PRs in a repository:```bashvibe watch add \- --session-key "slack::channel::C123::thread::171717.123" \+ --session-id "sesk8m4q2p7x" \--name "Watch new PRs" \--prefix "The repository has new pull requests. Review the new PRs and continue as needed." \-- \@@ -249,7 +246,7 @@ GitHub Actions for a pushed commit:```bashvibe watch add \- --session-key "slack::channel::C123::thread::171717.123" \+ --session-id "sesk8m4q2p7x" \--name "Watch CI" \--prefix "GitHub Actions finished. Inspect the result below and continue with the deployment or fix failures." \-- \diff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.mdindex ba983d36b..0d690f6de 100644--- a/skills/use-vibe-remote/SKILL.md+++ b/skills/use-vibe-remote/SKILL.md@@ -753,30 +753,27 @@ Use scheduled tasks and watches when the user wants Vibe Remote to inject a promPreferred CLI shape:-- recurring task: `vibe task add --session-key '<key>' --cron '<expr>' --prompt '...'`-- one-off task: `vibe task add --session-key '<key>' --at '<ISO-8601>' --prompt '...'`+- recurring task: `vibe task add --session-id '<session-id>' --cron '<expr>' --prompt '...'`+- one-off task: `vibe task add --session-id '<session-id>' --at '<ISO-8601>' --prompt '...'`- immediate rerun: `vibe task run <id>`-- one-shot async hook: `vibe hook send --session-key '<key>' --prompt '...'`-- managed background watch: `vibe watch add --session-key '<key>' --prefix '...' -- <cmd>` (or `--shell '<cmd>'` to pass a single shell string)+- one-shot async hook: `vibe hook send --session-id '<session-id>' --prompt '...'`+- managed background watch: `vibe watch add --session-id '<session-id>' --prefix '...' -- <cmd>` (or `--shell '<cmd>'` to pass a single shell string)Delivery controls (apply to `vibe task add`, `vibe hook send`, and `vibe watch add`):-- `session_key` controls which session Vibe Remote continues using-- when you want to keep the current session, keep using the current `session_key`-- when you do not want to keep the current thread session and instead want to start or reuse the higher-level session, switch to the higher-level key-- example: `slack::channel::C123::thread::171717.123` keeps the current thread session, while `slack::channel::C123` creates or reuses the channel-scoped session-- use `--post-to channel` when the task, hook, or watch should keep the session chosen by `session_key` but publish to the parent channel-- use `--deliver-key '<key>'` only when delivery must go to a different explicit target than `session_key`+- `session_id` controls which Agent Session Vibe Remote continues using+- when you want to keep the current session, use the current Agent Session ID shown in the prompt+- if the current turn does not expose a usable Agent Session ID, ask the user to retry from an active Vibe Remote session instead of guessing+- use `--post-to channel` when the task, hook, or watch should keep the same Agent Session but publish to the parent channel+- use `--deliver-key '<key>'` only when delivery must go to a different explicit target than the continued session- do not combine `--post-to` and `--deliver-key` in the same command- `vibe task add` stores the text from `--prompt` or `--prompt-file` and injects it each time the task runs- `vibe hook send` queues the text from `--prompt` or `--prompt-file` once without storing a task- `vibe watch add` uses `--prefix` as follow-up instruction text; on a successful cycle Vibe Remote prepends it before waiter stdout, joined with a blank line when both exist-Session key format:+Legacy compatibility:-- channel scope: `<platform>::channel::<channel_id>`-- DM scope: `<platform>::user::<user_id>`-- exact thread target: append `::thread::<thread_id>` when the user explicitly wants the task bound to that thread+- `--session-key` is still accepted for old scripts; do not use it in new examples or instructions unless the user explicitly asks for legacy targetingOperational guidance:@@ -943,7 +940,7 @@ Watches:- `vibe watch add`, `vibe watch list [--brief]`, `vibe watch show <id>`, `vibe watch pause <id>`, `vibe watch resume <id>`, `vibe watch remove <id>`-For any subcommand, prefer `<command> --help` before composing a new invocation. The delivery flags shared by all three commands are `--session-key`, `--post-to`, and `--deliver-key`. The remaining surface differs: `vibe task add` and `vibe hook send` take `--prompt` / `--prompt-file`; `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; and `vibe watch add` takes its own set (`--prefix`, `--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). Do not copy task or hook flags into a watch invocation, and do not pass `--name` to `vibe hook send`.+For any subcommand, prefer `<command> --help` before composing a new invocation. The delivery flags shared by all three commands are `--session-id`, `--post-to`, and `--deliver-key`. The remaining surface differs: `vibe task add` and `vibe hook send` take `--prompt` / `--prompt-file`; `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; and `vibe watch add` takes its own set (`--prefix`, `--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). Do not copy task or hook flags into a watch invocation, and do not pass `--name` to `vibe hook send`.## Troubleshootingdiff --git a/storage/alembic/versions/20260515_0002_background_tasks.py b/storage/alembic/versions/20260515_0002_background_tasks.pynew file mode 100644index 000000000..d21823149--- /dev/null+++ b/storage/alembic/versions/20260515_0002_background_tasks.py@@ -0,0 +1,87 @@+"""background task and run tables++Revision ID: 20260515_0002+Revises: 20260501_0001+Create Date: 2026-05-15+"""++from __future__ import annotations++import sqlalchemy as sa+from alembic import op++revision = "20260515_0002"+down_revision = "20260501_0001"+branch_labels = None+depends_on = None+++def upgrade() -> None:+ op.create_table(+ "background_tasks",+ sa.Column("id", sa.String(), primary_key=True),+ sa.Column("task_type", sa.String(), nullable=False),+ sa.Column("name", sa.Text(), nullable=True),+ sa.Column("session_id", sa.String(), nullable=True),+ sa.Column("legacy_session_key", sa.Text(), nullable=True),+ sa.Column("prompt", sa.Text(), nullable=True),+ sa.Column("schedule_type", sa.String(), nullable=True),+ sa.Column("cron", sa.Text(), nullable=True),+ sa.Column("run_at", sa.String(), nullable=True),+ sa.Column("timezone", sa.String(), nullable=True),+ sa.Column("command_json", sa.Text(), nullable=True),+ sa.Column("shell_command", sa.Text(), nullable=True),+ sa.Column("prefix", sa.Text(), nullable=True),+ sa.Column("cwd", sa.Text(), nullable=True),+ sa.Column("mode", sa.String(), nullable=True),+ sa.Column("timeout_seconds", sa.Float(), nullable=True),+ sa.Column("lifetime_timeout_seconds", sa.Float(), nullable=True),+ sa.Column("retry_exit_codes_json", sa.Text(), nullable=True),+ sa.Column("retry_delay_seconds", sa.Float(), nullable=True),+ sa.Column("post_to", sa.String(), nullable=True),+ sa.Column("deliver_key", sa.Text(), nullable=True),+ sa.Column("enabled", sa.Integer(), nullable=False),+ sa.Column("created_at", sa.String(), nullable=False),+ sa.Column("updated_at", sa.String(), nullable=False),+ sa.Column("last_started_at", sa.String(), nullable=True),+ sa.Column("last_finished_at", sa.String(), nullable=True),+ sa.Column("last_event_at", sa.String(), nullable=True),+ sa.Column("last_run_at", sa.String(), nullable=True),+ sa.Column("last_error", sa.Text(), nullable=True),+ sa.Column("last_exit_code", sa.Integer(), nullable=True),+ sa.Column("metadata_json", sa.Text(), nullable=False),+ )+ op.create_index("ix_background_tasks_type_enabled", "background_tasks", ["task_type", "enabled"])+ op.create_index("ix_background_tasks_session", "background_tasks", ["session_id"])+ op.create_index("ix_background_tasks_updated", "background_tasks", ["updated_at"])++ op.create_table(+ "background_runs",+ sa.Column("id", sa.String(), primary_key=True),+ sa.Column("task_id", sa.String(), nullable=True),+ sa.Column("run_type", sa.String(), nullable=False),+ sa.Column("status", sa.String(), nullable=False),+ sa.Column("session_id", sa.String(), nullable=True),+ sa.Column("legacy_session_key", sa.Text(), nullable=True),+ sa.Column("post_to", sa.String(), nullable=True),+ sa.Column("deliver_key", sa.Text(), nullable=True),+ sa.Column("prompt", sa.Text(), nullable=True),+ sa.Column("pid", sa.Integer(), nullable=True),+ sa.Column("exit_code", sa.Integer(), nullable=True),+ sa.Column("error", sa.Text(), nullable=True),+ sa.Column("stdout", sa.Text(), nullable=True),+ sa.Column("stderr", sa.Text(), nullable=True),+ sa.Column("created_at", sa.String(), nullable=False),+ sa.Column("started_at", sa.String(), nullable=True),+ sa.Column("completed_at", sa.String(), nullable=True),+ sa.Column("updated_at", sa.String(), nullable=False),+ sa.Column("metadata_json", sa.Text(), nullable=False),+ )+ op.create_index("ix_background_runs_task_created", "background_runs", ["task_id", "created_at"])+ op.create_index("ix_background_runs_status", "background_runs", ["status"])+ op.create_index("ix_background_runs_session_created", "background_runs", ["session_id", "created_at"])+++def downgrade() -> None:+ op.drop_table("background_runs")+ op.drop_table("background_tasks")diff --git a/storage/background.py b/storage/background.pynew file mode 100644index 000000000..653e6f862--- /dev/null+++ b/storage/background.py@@ -0,0 +1,407 @@+from __future__ import annotations++import json+import logging+from pathlib import Path+from typing import Any, Optional++from sqlalchemy import delete, insert, select, update++from config import paths+from storage.db import SqliteInvalidationProbe, create_sqlite_engine+from storage.migrations import background_tables_ready, initialize_background_tables+from storage.models import background_runs, background_tasks++logger = logging.getLogger(__name__)+++def _json_dumps(value: Any) -> str:+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))+++def _json_loads(value: Optional[str], default: Any) -> Any:+ if not value:+ return default+ try:+ return json.loads(value)+ except Exception:+ return default+++class SQLiteBackgroundTaskStore:+ def __init__(self, db_path: Optional[Path] = None):+ self.db_path = db_path or paths.get_sqlite_state_path()+ self.db_path.parent.mkdir(parents=True, exist_ok=True)+ if not background_tables_ready(self.db_path):+ initialize_background_tables(self.db_path)+ if db_path is None:+ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config++ ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))+ self.engine = create_sqlite_engine(self.db_path)+ self._probe = SqliteInvalidationProbe(self.engine)++ def close(self) -> None:+ self._probe.close()+ self.engine.dispose()++ def maybe_reload(self) -> bool:+ return self._probe.has_external_write()++ def list_scheduled_tasks(self) -> list[dict[str, Any]]:+ with self.engine.connect() as conn:+ rows = conn.execute(+ select(background_tasks)+ .where(background_tasks.c.task_type == "scheduled")+ .order_by(background_tasks.c.created_at, background_tasks.c.id)+ ).mappings()+ return [self._scheduled_task_from_row(row) for row in rows]++ def get_scheduled_task(self, task_id: str) -> Optional[dict[str, Any]]:+ with self.engine.connect() as conn:+ row = conn.execute(+ select(background_tasks)+ .where(background_tasks.c.task_type == "scheduled")+ .where(background_tasks.c.id == task_id)+ .limit(1)+ ).mappings().first()+ return self._scheduled_task_from_row(row) if row else None++ def upsert_scheduled_task(self, payload: dict[str, Any]) -> None:+ values = self._scheduled_task_values(payload)+ with self.engine.begin() as conn:+ existing = conn.execute(+ select(background_tasks.c.id).where(background_tasks.c.id == values["id"]).limit(1)+ ).scalar_one_or_none()+ if existing:+ conn.execute(update(background_tasks).where(background_tasks.c.id == values["id"]).values(**values))+ else:+ conn.execute(insert(background_tasks).values(**values))++ def remove_task(self, task_id: str) -> bool:+ with self.engine.begin() as conn:+ result = conn.execute(delete(background_tasks).where(background_tasks.c.id == task_id))+ return bool(result.rowcount)++ def list_watches(self) -> list[dict[str, Any]]:+ with self.engine.connect() as conn:+ rows = conn.execute(+ select(background_tasks)+ .where(background_tasks.c.task_type == "watch")+ .order_by(background_tasks.c.created_at, background_tasks.c.id)+ ).mappings()+ return [self._watch_from_row(row) for row in rows]++ def get_watch(self, watch_id: str) -> Optional[dict[str, Any]]:+ with self.engine.connect() as conn:+ row = conn.execute(+ select(background_tasks)+ .where(background_tasks.c.task_type == "watch")+ .where(background_tasks.c.id == watch_id)+ .limit(1)+ ).mappings().first()+ return self._watch_from_row(row) if row else None++ def upsert_watch(self, payload: dict[str, Any]) -> None:+ values = self._watch_values(payload)+ with self.engine.begin() as conn:+ existing = conn.execute(+ select(background_tasks.c.id).where(background_tasks.c.id == values["id"]).limit(1)+ ).scalar_one_or_none()+ if existing:+ conn.execute(update(background_tasks).where(background_tasks.c.id == values["id"]).values(**values))+ else:+ conn.execute(insert(background_tasks).values(**values))++ def enqueue_run(self, payload: dict[str, Any]) -> None:+ values = self._run_values(payload)+ with self.engine.begin() as conn:+ existing = conn.execute(+ select(background_runs.c.id).where(background_runs.c.id == values["id"]).limit(1)+ ).scalar_one_or_none()+ if existing:+ conn.execute(update(background_runs).where(background_runs.c.id == values["id"]).values(**values))+ else:+ conn.execute(insert(background_runs).values(**values))++ def list_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:+ stmt = select(background_runs)+ if status:+ stmt = stmt.where(background_runs.c.status == status)+ stmt = stmt.order_by(background_runs.c.created_at, background_runs.c.id)+ with self.engine.connect() as conn:+ return [self._run_from_row(row) for row in conn.execute(stmt).mappings()]++ def get_run(self, run_id: str) -> Optional[dict[str, Any]]:+ with self.engine.connect() as conn:+ row = conn.execute(select(background_runs).where(background_runs.c.id == run_id).limit(1)).mappings().first()+ return self._run_from_row(row) if row else None++ def update_run_status(+ self,+ run_id: str,+ *,+ status: str,+ updated_at: str,+ started_at: Optional[str] = None,+ completed_at: Optional[str] = None,+ exit_code: Optional[int] = None,+ error: Optional[str] = None,+ stdout: Optional[str] = None,+ stderr: Optional[str] = None,+ pid: Optional[int] = None,+ metadata: Optional[dict[str, Any]] = None,+ ) -> None:+ values: dict[str, Any] = {+ "status": status,+ "updated_at": updated_at,+ }+ if started_at is not None:+ values["started_at"] = started_at+ if completed_at is not None:+ values["completed_at"] = completed_at+ if exit_code is not None:+ values["exit_code"] = exit_code+ if error is not None:+ values["error"] = error+ if stdout is not None:+ values["stdout"] = stdout+ if stderr is not None:+ values["stderr"] = stderr+ if pid is not None:+ values["pid"] = pid+ if metadata is not None:+ values["metadata_json"] = _json_dumps(metadata)+ with self.engine.begin() as conn:+ conn.execute(update(background_runs).where(background_runs.c.id == run_id).values(**values))++ def recover_processing_runs(self) -> None:+ with self.engine.begin() as conn:+ conn.execute(+ update(background_runs)+ .where(background_runs.c.status == "processing")+ .values(status="pending", started_at=None, pid=None)+ )++ def write_watch_runtime(self, payload: dict[str, Any], *, updated_at: str) -> None:+ watches = payload.get("watches", {}) if isinstance(payload, dict) else {}+ with self.engine.begin() as conn:+ conn.execute(+ update(background_runs)+ .where(background_runs.c.run_type == "watch_runtime")+ .where(background_runs.c.status.in_(["running", "pending"]))+ .values(status="completed", completed_at=updated_at, updated_at=updated_at)+ )+ for watch_id, runtime_payload in watches.items():+ if not isinstance(runtime_payload, dict):+ continue+ run_id = f"runtime:{watch_id}"+ values = self._run_values(+ {+ "id": run_id,+ "request_type": "watch_runtime",+ "status": "running" if runtime_payload.get("running") else "completed",+ "task_id": watch_id,+ "pid": runtime_payload.get("pid"),+ "created_at": runtime_payload.get("started_at") or updated_at,+ "started_at": runtime_payload.get("started_at"),+ "updated_at": runtime_payload.get("updated_at") or updated_at,+ "metadata": runtime_payload,+ }+ )+ existing = conn.execute(+ select(background_runs.c.id).where(background_runs.c.id == run_id).limit(1)+ ).scalar_one_or_none()+ if existing:+ conn.execute(update(background_runs).where(background_runs.c.id == run_id).values(**values))+ else:+ conn.execute(insert(background_runs).values(**values))++ def load_watch_runtime(self) -> dict[str, Any]:+ with self.engine.connect() as conn:+ rows = conn.execute(+ select(background_runs)+ .where(background_runs.c.run_type == "watch_runtime")+ .where(background_runs.c.status == "running")+ ).mappings()+ watches: dict[str, Any] = {}+ for row in rows:+ payload = _json_loads(row["metadata_json"], {})+ watch_id = row["task_id"]+ if watch_id:+ watches[str(watch_id)] = {+ "running": True,+ "pid": row["pid"],+ "started_at": row["started_at"],+ "updated_at": row["updated_at"],+ } | (payload if isinstance(payload, dict) else {})+ return {"watches": watches}++ def _scheduled_task_values(self, payload: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": payload["id"],+ "task_type": "scheduled",+ "name": payload.get("name"),+ "session_id": payload.get("session_id"),+ "legacy_session_key": payload.get("session_key") or None,+ "prompt": payload.get("prompt") or "",+ "schedule_type": payload.get("schedule_type") or "",+ "cron": payload.get("cron"),+ "run_at": payload.get("run_at"),+ "timezone": payload.get("timezone") or "UTC",+ "command_json": None,+ "shell_command": None,+ "prefix": None,+ "cwd": None,+ "mode": None,+ "timeout_seconds": None,+ "lifetime_timeout_seconds": None,+ "retry_exit_codes_json": None,+ "retry_delay_seconds": None,+ "post_to": payload.get("post_to"),+ "deliver_key": payload.get("deliver_key"),+ "enabled": 1 if payload.get("enabled", True) else 0,+ "created_at": payload.get("created_at") or payload.get("updated_at"),+ "updated_at": payload.get("updated_at") or payload.get("created_at"),+ "last_started_at": None,+ "last_finished_at": None,+ "last_event_at": None,+ "last_run_at": payload.get("last_run_at"),+ "last_error": payload.get("last_error"),+ "last_exit_code": None,+ "metadata_json": _json_dumps({}),+ }++ def _watch_values(self, payload: dict[str, Any]) -> dict[str, Any]:+ return {+ "id": payload["id"],+ "task_type": "watch",+ "name": payload.get("name"),+ "session_id": payload.get("session_id"),+ "legacy_session_key": payload.get("session_key") or None,+ "prompt": None,+ "schedule_type": None,+ "cron": None,+ "run_at": None,+ "timezone": None,+ "command_json": _json_dumps(payload.get("command") or []),+ "shell_command": payload.get("shell_command"),+ "prefix": payload.get("prefix"),+ "cwd": payload.get("cwd"),+ "mode": payload.get("mode") or "once",+ "timeout_seconds": float(payload.get("timeout_seconds", 21600.0)),+ "lifetime_timeout_seconds": float(payload.get("lifetime_timeout_seconds", 0.0)),+ "retry_exit_codes_json": _json_dumps(payload.get("retry_exit_codes") or []),+ "retry_delay_seconds": float(payload.get("retry_delay_seconds", 30.0)),+ "post_to": payload.get("post_to"),+ "deliver_key": payload.get("deliver_key"),+ "enabled": 1 if payload.get("enabled", True) else 0,+ "created_at": payload.get("created_at") or payload.get("updated_at"),+ "updated_at": payload.get("updated_at") or payload.get("created_at"),+ "last_started_at": payload.get("last_started_at"),+ "last_finished_at": payload.get("last_finished_at"),+ "last_event_at": payload.get("last_event_at"),+ "last_run_at": None,+ "last_error": payload.get("last_error"),+ "last_exit_code": payload.get("last_exit_code"),+ "metadata_json": _json_dumps({}),+ }++ def _run_values(self, payload: dict[str, Any]) -> dict[str, Any]:+ created_at = payload.get("created_at") or payload.get("updated_at")+ return {+ "id": payload["id"],+ "task_id": payload.get("task_id"),+ "run_type": payload.get("request_type") or payload.get("run_type") or "hook_send",+ "status": payload.get("status") or "pending",+ "session_id": payload.get("session_id"),+ "legacy_session_key": payload.get("session_key") or payload.get("legacy_session_key"),+ "post_to": payload.get("post_to"),+ "deliver_key": payload.get("deliver_key"),+ "prompt": payload.get("prompt"),+ "pid": payload.get("pid"),+ "exit_code": payload.get("exit_code"),+ "error": payload.get("error"),+ "stdout": payload.get("stdout"),+ "stderr": payload.get("stderr"),+ "created_at": created_at,+ "started_at": payload.get("started_at"),+ "completed_at": payload.get("completed_at"),+ "updated_at": payload.get("updated_at") or created_at,+ "metadata_json": _json_dumps(payload.get("metadata") or {}),+ }++ @staticmethod+ def _scheduled_task_from_row(row: Any) -> dict[str, Any]:+ return {+ "id": row["id"],+ "name": row["name"],+ "session_key": row["legacy_session_key"] or "",+ "session_id": row["session_id"],+ "prompt": row["prompt"] or "",+ "schedule_type": row["schedule_type"] or "",+ "post_to": row["post_to"],+ "deliver_key": row["deliver_key"],+ "cron": row["cron"],+ "run_at": row["run_at"],+ "timezone": row["timezone"] or "UTC",+ "enabled": bool(row["enabled"]),+ "created_at": row["created_at"],+ "updated_at": row["updated_at"],+ "last_run_at": row["last_run_at"],+ "last_error": row["last_error"],+ }++ @staticmethod+ def _watch_from_row(row: Any) -> dict[str, Any]:+ return {+ "id": row["id"],+ "name": row["name"],+ "session_key": row["legacy_session_key"] or "",+ "session_id": row["session_id"],+ "command": _json_loads(row["command_json"], []),+ "shell_command": row["shell_command"],+ "prefix": row["prefix"],+ "cwd": row["cwd"],+ "mode": row["mode"] or "once",+ "timeout_seconds": float(row["timeout_seconds"] or 21600.0),+ "lifetime_timeout_seconds": float(row["lifetime_timeout_seconds"] or 0.0),+ "retry_exit_codes": [int(code) for code in _json_loads(row["retry_exit_codes_json"], [])],+ "retry_delay_seconds": float(row["retry_delay_seconds"] or 30.0),+ "post_to": row["post_to"],+ "deliver_key": row["deliver_key"],+ "enabled": bool(row["enabled"]),+ "created_at": row["created_at"],+ "updated_at": row["updated_at"],+ "last_started_at": row["last_started_at"],+ "last_finished_at": row["last_finished_at"],+ "last_event_at": row["last_event_at"],+ "last_error": row["last_error"],+ "last_exit_code": row["last_exit_code"],+ }++ @staticmethod+ def _run_from_row(row: Any) -> dict[str, Any]:+ return {+ "id": row["id"],+ "request_type": row["run_type"],+ "run_type": row["run_type"],+ "status": row["status"],+ "task_id": row["task_id"],+ "session_key": row["legacy_session_key"],+ "session_id": row["session_id"],+ "post_to": row["post_to"],+ "deliver_key": row["deliver_key"],+ "prompt": row["prompt"],+ "pid": row["pid"],+ "exit_code": row["exit_code"],+ "error": row["error"],+ "stdout": row["stdout"],+ "stderr": row["stderr"],+ "created_at": row["created_at"],+ "started_at": row["started_at"],+ "completed_at": row["completed_at"],+ "updated_at": row["updated_at"],+ "metadata": _json_loads(row["metadata_json"], {}),+ "ok": None if row["completed_at"] is None else row["status"] == "completed",+ }diff --git a/storage/importer.py b/storage/importer.pyindex de9e23437..225e5e747 100644--- a/storage/importer.py+++ b/storage/importer.py@@ -24,11 +24,22 @@ from config.v2_settings import SettingsState, load_settings_state_from_jsonfrom storage.db import create_sqlite_enginefrom storage.lock import MigrationFileLockfrom storage.migrations import run_migrations-from storage.models import agent_sessions, auth_codes, imported_state_tables, runtime_records, scope_settings, scopes, state_meta+from storage.models import (+ agent_sessions,+ auth_codes,+ background_runs,+ background_tasks,+ imported_state_tables,+ runtime_records,+ scope_settings,+ scopes,+ state_meta,+)from storage.sessions_service import SESSIONS_LAST_ACTIVITY_KEY, SQLiteSessionsServicefrom storage.settings_service import SQLiteSettingsService, upsert_scopeJSON_IMPORT_MARKER = "json_import_completed_at"+BACKGROUND_IMPORT_MARKER = "background_json_import_completed_at"logger = logging.getLogger(__name__)@@ -61,12 +72,26 @@ def ensure_sqlite_state(run_migrations(target_db)engine = create_sqlite_engine(target_db)try:+ backup_path: Path | None = Nonewith engine.begin() as conn:if _has_import_marker(conn):+ imported_background = False+ background_counts: dict[str, int] = {}+ if not _has_background_import_marker(conn):+ backup_path = _backup_json_state(target_state_dir)+ background_counts = _import_background_state(conn, target_state_dir)+ _set_background_import_marker(conn)+ _validate_import(conn, _current_counts(conn))+ imported_background = bool(+ background_counts.get("background_scheduled_tasks")+ or background_counts.get("background_watches")+ or background_counts.get("background_runs_imported")+ )return MigrationImportReport(db_path=target_db,- imported=False,- counts=_current_counts(conn),+ imported=imported_background,+ backup_path=backup_path,+ counts=_current_counts(conn) | background_counts,)_clear_imported_state(conn)@@ -77,18 +102,22 @@ def ensure_sqlite_state(with engine.begin() as conn:discovered_count = _import_discovered_chats(conn, parsed.discovered)+ background_counts = _import_background_state(conn, target_state_dir)counts = _current_counts(conn)counts["discovered_scopes"] = discovered_count+ counts.update(background_counts)if parsed.discovered_skipped:counts["discovered_chats_skipped"] = 1_validate_import(conn, counts)_set_import_marker(conn)+ _set_background_import_marker(conn)return MigrationImportReport(db_path=target_db,imported=True,backup_path=backup_path,counts=_current_counts(conn)| {"discovered_scopes": discovered_count}+ | background_counts| ({"discovered_chats_skipped": 1} if parsed.discovered_skipped else {}),)finally:@@ -155,6 +184,15 @@ def _has_import_marker(conn: Connection) -> bool:)+def _has_background_import_marker(conn: Connection) -> bool:+ return (+ conn.execute(+ select(state_meta.c.value_json).where(state_meta.c.key == BACKGROUND_IMPORT_MARKER)+ ).scalar_one_or_none()+ is not None+ )++def _set_import_marker(conn: Connection) -> None:now = _utc_now_iso()conn.execute(@@ -166,6 +204,20 @@ def _set_import_marker(conn: Connection) -> None:)+def _set_background_import_marker(conn: Connection) -> None:+ now = _utc_now_iso()+ conn.execute(+ state_meta.delete().where(state_meta.c.key == BACKGROUND_IMPORT_MARKER),+ )+ conn.execute(+ state_meta.insert().values(+ key=BACKGROUND_IMPORT_MARKER,+ value_json=_json_dumps(now),+ updated_at=now,+ )+ )++def _backup_json_state(state_dir: Path) -> Path:backups_dir = state_dir / "backups"backups_dir.mkdir(parents=True, exist_ok=True)@@ -178,7 +230,13 @@ def _backup_json_state(state_dir: Path) -> Path:backup_path.mkdir(parents=True)manifest: dict[str, Any] = {"created_at": _utc_now_iso(), "files": {}}- for name in ("settings.json", "sessions.json", "discovered_chats.json"):+ for name in (+ "settings.json",+ "sessions.json",+ "discovered_chats.json",+ "scheduled_tasks.json",+ "watches.json",+ ):source = state_dir / nameif not source.exists():manifest["files"][name] = {"present": False}@@ -191,6 +249,12 @@ def _backup_json_state(state_dir: Path) -> Path:"size": stat.st_size,"mtime_ns": stat.st_mtime_ns,}+ task_requests = state_dir / "task_requests"+ if task_requests.exists():+ shutil.copytree(task_requests, backup_path / "task_requests")+ manifest["files"]["task_requests"] = {"present": True}+ else:+ manifest["files"]["task_requests"] = {"present": False}(backup_path / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")return backup_path@@ -305,6 +369,7 @@ def _clear_imported_state(conn: Connection) -> None:for table in imported_state_tables:conn.execute(table.delete())conn.execute(state_meta.delete().where(state_meta.c.key == JSON_IMPORT_MARKER))+ conn.execute(state_meta.delete().where(state_meta.c.key == BACKGROUND_IMPORT_MARKER))conn.execute(state_meta.delete().where(state_meta.c.key == SESSIONS_LAST_ACTIVITY_KEY))@@ -344,6 +409,185 @@ def _import_discovered_chats(conn: Connection, discovered: DiscoveredChatsStore)return count+def _import_background_state(conn: Connection, state_dir: Path) -> dict[str, int]:+ task_count = _import_scheduled_tasks(conn, state_dir / "scheduled_tasks.json")+ watch_count = _import_watches(conn, state_dir / "watches.json")+ request_count = _import_task_requests(conn, state_dir / "task_requests")+ runtime_count = _import_watch_runtime(conn, state_dir / "watch_runtime.json")+ return {+ "background_scheduled_tasks": task_count,+ "background_watches": watch_count,+ "background_runs_imported": request_count + runtime_count,+ }+++def _import_scheduled_tasks(conn: Connection, source: Path) -> int:+ payload = _read_json_object(source)+ count = 0+ for item in payload.get("tasks", []) if isinstance(payload, dict) else []:+ if not isinstance(item, dict):+ continue+ conn.execute(+ background_tasks.insert().values(+ id=str(item.get("id") or ""),+ task_type="scheduled",+ name=item.get("name"),+ session_id=item.get("session_id"),+ legacy_session_key=item.get("session_key") or None,+ prompt=item.get("prompt") or "",+ schedule_type=item.get("schedule_type") or "",+ cron=item.get("cron"),+ run_at=item.get("run_at"),+ timezone=item.get("timezone") or "UTC",+ command_json=None,+ shell_command=None,+ prefix=None,+ cwd=None,+ mode=None,+ timeout_seconds=None,+ lifetime_timeout_seconds=None,+ retry_exit_codes_json=None,+ retry_delay_seconds=None,+ post_to=item.get("post_to"),+ deliver_key=item.get("deliver_key"),+ enabled=1 if item.get("enabled", True) else 0,+ created_at=item.get("created_at") or _utc_now_iso(),+ updated_at=item.get("updated_at") or item.get("created_at") or _utc_now_iso(),+ last_started_at=None,+ last_finished_at=None,+ last_event_at=None,+ last_run_at=item.get("last_run_at"),+ last_error=item.get("last_error"),+ last_exit_code=None,+ metadata_json=_json_dumps({}),+ )+ )+ count += 1+ return count+++def _import_watches(conn: Connection, source: Path) -> int:+ payload = _read_json_object(source)+ count = 0+ for item in payload.get("watches", []) if isinstance(payload, dict) else []:+ if not isinstance(item, dict):+ continue+ conn.execute(+ background_tasks.insert().values(+ id=str(item.get("id") or ""),+ task_type="watch",+ name=item.get("name"),+ session_id=item.get("session_id"),+ legacy_session_key=item.get("session_key") or None,+ prompt=None,+ schedule_type=None,+ cron=None,+ run_at=None,+ timezone=None,+ command_json=_json_dumps(item.get("command") or []),+ shell_command=item.get("shell_command"),+ prefix=item.get("prefix"),+ cwd=item.get("cwd"),+ mode=item.get("mode") or "once",+ timeout_seconds=float(item.get("timeout_seconds", 21600.0)),+ lifetime_timeout_seconds=float(item.get("lifetime_timeout_seconds", 0.0)),+ retry_exit_codes_json=_json_dumps(item.get("retry_exit_codes") or []),+ retry_delay_seconds=float(item.get("retry_delay_seconds", 30.0)),+ post_to=item.get("post_to"),+ deliver_key=item.get("deliver_key"),+ enabled=1 if item.get("enabled", True) else 0,+ created_at=item.get("created_at") or _utc_now_iso(),+ updated_at=item.get("updated_at") or item.get("created_at") or _utc_now_iso(),+ last_started_at=item.get("last_started_at"),+ last_finished_at=item.get("last_finished_at"),+ last_event_at=item.get("last_event_at"),+ last_run_at=None,+ last_error=item.get("last_error"),+ last_exit_code=item.get("last_exit_code"),+ metadata_json=_json_dumps({}),+ )+ )+ count += 1+ return count+++def _import_task_requests(conn: Connection, root: Path) -> int:+ count = 0+ for status_dir, status in (("pending", "pending"), ("processing", "pending"), ("completed", "completed")):+ directory = root / status_dir+ if not directory.exists():+ continue+ for path in sorted(directory.glob("*.json")):+ item = _read_json_object(path)+ if not item:+ continue+ ok = item.get("ok")+ run_status = "failed" if status == "completed" and ok is False else status+ created_at = item.get("created_at") or item.get("completed_at") or _utc_now_iso()+ conn.execute(+ background_runs.insert().values(+ id=str(item.get("id") or path.stem),+ task_id=item.get("task_id"),+ run_type=item.get("request_type") or "hook_send",+ status=run_status,+ session_id=item.get("session_id"),+ legacy_session_key=item.get("session_key"),+ post_to=item.get("post_to"),+ deliver_key=item.get("deliver_key"),+ prompt=item.get("prompt"),+ pid=None,+ exit_code=None,+ error=item.get("error"),+ stdout=None,+ stderr=None,+ created_at=created_at,+ started_at=None,+ completed_at=item.get("completed_at"),+ updated_at=item.get("completed_at") or created_at,+ metadata_json=_json_dumps({"ok": ok} if ok is not None else {}),+ )+ )+ count += 1+ return count+++def _import_watch_runtime(conn: Connection, source: Path) -> int:+ payload = _read_json_object(source)+ watches = payload.get("watches", {}) if isinstance(payload, dict) else {}+ if not isinstance(watches, dict):+ return 0+ count = 0+ for watch_id, item in watches.items():+ if not isinstance(item, dict):+ continue+ now = item.get("updated_at") or _utc_now_iso()+ conn.execute(+ background_runs.insert().values(+ id=f"runtime:{watch_id}",+ task_id=str(watch_id),+ run_type="watch_runtime",+ status="running" if item.get("running") else "completed",+ session_id=None,+ legacy_session_key=None,+ post_to=None,+ deliver_key=None,+ prompt=None,+ pid=item.get("pid"),+ exit_code=None,+ error=None,+ stdout=None,+ stderr=None,+ created_at=item.get("started_at") or now,+ started_at=item.get("started_at"),+ completed_at=None,+ updated_at=now,+ metadata_json=_json_dumps(item),+ )+ )+ count += 1+ return count++def _validate_import(conn: Connection, _counts: dict[str, int]) -> None:integrity = conn.exec_driver_sql("PRAGMA integrity_check").scalar_one()if integrity != "ok":@@ -357,10 +601,25 @@ def _current_counts(conn: Connection) -> dict[str, int]:"auth_codes": auth_codes,"agent_sessions": agent_sessions,"runtime_records": runtime_records,+ "background_tasks": background_tasks,+ "background_runs": background_runs,}return {key: int(conn.execute(select(func.count()).select_from(table)).scalar_one()) for key, table in tables.items()}+def _read_json_object(path: Path) -> dict[str, Any]:+ if not path.exists():+ return {}+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except Exception as exc:+ logger.warning("Skipping invalid background JSON state %s: %s", path, exc)+ return {}+ return payload if isinstance(payload, dict) else {}++++def _json_dumps(value: Any) -> str:return json.dumps(value, ensure_ascii=False, separators=(",", ":"))diff --git a/storage/migrations.py b/storage/migrations.pyindex 23e686bef..1004e268d 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -18,6 +18,7 @@ INITIAL_TABLES = {"agent_sessions","runtime_records",}+HEAD_TABLES = INITIAL_TABLES | {"background_tasks", "background_runs"}UNRELEASED_OLD_INITIAL_TABLES = ["session_messages","chat_sessions",@@ -56,6 +57,23 @@ def run_migrations(db_path: Path | None = None, *, revision: str = "head") -> Nocommand.upgrade(cfg, revision)+def background_tables_ready(db_path: Path | None = None) -> bool:+ target_db = (db_path or paths.get_sqlite_state_path()).expanduser().resolve()+ if not target_db.exists():+ return False+ with sqlite3.connect(target_db) as conn:+ tables = _table_names(conn)+ return {"background_tasks", "background_runs"}.issubset(tables)+++def initialize_background_tables(db_path: Path | None = None) -> None:+ target_db = db_path or paths.get_sqlite_state_path()+ cfg = alembic_config(target_db)+ command.ensure_version(cfg)+ _stamp_existing_initial_schema(target_db, cfg)+ command.upgrade(cfg, "head")++def _reset_unreleased_initial_schema_drift(db_path: Path) -> None:path = db_path.expanduser().resolve()if not path.exists():@@ -91,9 +109,12 @@ def _stamp_existing_initial_schema(db_path: Path, cfg: Config) -> None:returnif "alembic_version" in tables:version = conn.execute("select version_num from alembic_version").fetchone()- if version is not None:+ if version is not None and version[0]:return- if not INITIAL_TABLES.issubset(tables):+ if not (INITIAL_TABLES - {"scopes"}).issubset(tables):+ return+ if HEAD_TABLES.issubset(tables):+ command.stamp(cfg, "head")returncommand.stamp(cfg, INITIAL_REVISION)diff --git a/storage/models.py b/storage/models.pyindex 6a4ad87d3..370681f33 100644--- a/storage/models.py+++ b/storage/models.py@@ -120,7 +120,75 @@ runtime_records = Table(Index("ix_runtime_records_workdir", "workdir"),)+background_tasks = Table(+ "background_tasks",+ metadata,+ Column("id", String, primary_key=True),+ Column("task_type", String, nullable=False),+ Column("name", Text, nullable=True),+ Column("session_id", String, nullable=True),+ Column("legacy_session_key", Text, nullable=True),+ Column("prompt", Text, nullable=True),+ Column("schedule_type", String, nullable=True),+ Column("cron", Text, nullable=True),+ Column("run_at", String, nullable=True),+ Column("timezone", String, nullable=True),+ Column("command_json", Text, nullable=True),+ Column("shell_command", Text, nullable=True),+ Column("prefix", Text, nullable=True),+ Column("cwd", Text, nullable=True),+ Column("mode", String, nullable=True),+ Column("timeout_seconds", Float, nullable=True),+ Column("lifetime_timeout_seconds", Float, nullable=True),+ Column("retry_exit_codes_json", Text, nullable=True),+ Column("retry_delay_seconds", Float, nullable=True),+ Column("post_to", String, nullable=True),+ Column("deliver_key", Text, nullable=True),+ Column("enabled", Integer, nullable=False),+ Column("created_at", String, nullable=False),+ Column("updated_at", String, nullable=False),+ Column("last_started_at", String, nullable=True),+ Column("last_finished_at", String, nullable=True),+ Column("last_event_at", String, nullable=True),+ Column("last_run_at", String, nullable=True),+ Column("last_error", Text, nullable=True),+ Column("last_exit_code", Integer, nullable=True),+ Column("metadata_json", Text, nullable=False),+ Index("ix_background_tasks_type_enabled", "task_type", "enabled"),+ Index("ix_background_tasks_session", "session_id"),+ Index("ix_background_tasks_updated", "updated_at"),+)++background_runs = Table(+ "background_runs",+ metadata,+ Column("id", String, primary_key=True),+ Column("task_id", String, nullable=True),+ Column("run_type", String, nullable=False),+ Column("status", String, nullable=False),+ Column("session_id", String, nullable=True),+ Column("legacy_session_key", Text, nullable=True),+ Column("post_to", String, nullable=True),+ Column("deliver_key", Text, nullable=True),+ Column("prompt", Text, nullable=True),+ Column("pid", Integer, nullable=True),+ Column("exit_code", Integer, nullable=True),+ Column("error", Text, nullable=True),+ Column("stdout", Text, nullable=True),+ Column("stderr", Text, nullable=True),+ Column("created_at", String, nullable=False),+ Column("started_at", String, nullable=True),+ Column("completed_at", String, nullable=True),+ Column("updated_at", String, nullable=False),+ Column("metadata_json", Text, nullable=False),+ Index("ix_background_runs_task_created", "task_id", "created_at"),+ Index("ix_background_runs_status", "status"),+ Index("ix_background_runs_session_created", "session_id", "created_at"),+)+imported_state_tables = [+ background_runs,+ background_tasks,scope_settings,auth_codes,agent_sessions,diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex 53d074021..34feaf8f8 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -11,7 +11,7 @@ from sqlalchemy import Connection, selectfrom config.v2_sessions import ActivePollInfo, SessionStatefrom config.v2_settings import _split_scoped_keyfrom storage.db import SqliteInvalidationProbe, create_sqlite_engine-from storage.models import agent_sessions, runtime_records, scopes, state_meta+from storage.models import agent_sessions, metadata, runtime_records, scopes, state_metafrom storage.settings_service import make_scope_id, upsert_scopeSESSIONS_LAST_ACTIVITY_KEY = "sessions_last_activity"@@ -23,6 +23,7 @@ class SQLiteSessionsService:def __init__(self, db_path: Path):self.db_path = db_pathself.engine = create_sqlite_engine(db_path)+ metadata.create_all(self.engine)self._probe = SqliteInvalidationProbe(self.engine)def close(self) -> None:@@ -32,6 +33,25 @@ class SQLiteSessionsService:def has_external_write(self) -> bool:return self._probe.has_external_write()+ def get_agent_session_row_id(+ self,+ *,+ scope_key: str,+ agent_name: str,+ session_anchor: str,+ ) -> str | None:+ with self.engine.begin() as conn:+ scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=_utc_now_iso())+ if scope_id is None:+ return None+ return conn.execute(+ select(agent_sessions.c.id)+ .where(agent_sessions.c.scope_id == scope_id)+ .where(agent_sessions.c.agent_variant == (str(agent_name) or "default"))+ .where(agent_sessions.c.session_anchor == str(session_anchor))+ .limit(1)+ ).scalar_one_or_none()+def load_state(self) -> SessionState:with self.engine.connect() as conn:return SessionState(@@ -44,9 +64,10 @@ class SQLiteSessionsService:def save_state(self, state: SessionState) -> None:with self.engine.begin() as conn:+ existing_session_ids = self._load_existing_session_ids(conn)self._clear(conn)now = _utc_now_iso()- used_session_ids: set[str] = set()+ used_session_ids: set[str] = set(existing_session_ids.values())for scope_key, agent_maps in state.session_mappings.items():if not isinstance(agent_maps, dict):@@ -57,9 +78,16 @@ class SQLiteSessionsService:continuefor thread_id, native_session_id in thread_map.items():thread_key = str(thread_id)+ encoded_session_id = encode_session_value(native_session_id)+ row_key = _session_row_key(+ scope_id=scope_id,+ agent_variant=str(agent_name) or "default",+ session_anchor=thread_key,+ native_session_id=encoded_session_id,+ )conn.execute(agent_sessions.insert().values(- id=_new_session_id(used_session_ids),+ id=existing_session_ids.get(row_key) or _new_session_id(used_session_ids),scope_id=scope_id,agent_backend=_agent_backend(str(agent_name)),agent_variant=str(agent_name) or "default",@@ -67,7 +95,7 @@ class SQLiteSessionsService:reasoning_effort=None,session_anchor=thread_key,workdir=_workdir_from_anchor(thread_key),- native_session_id=encode_session_value(native_session_id),+ native_session_id=encoded_session_id,title=None,status="active",metadata_json=_json_dumps({"legacy_scope_key": str(scope_key)}),@@ -183,6 +211,28 @@ class SQLiteSessionsService:conn.execute(runtime_records.delete())conn.execute(state_meta.delete().where(state_meta.c.key == SESSIONS_LAST_ACTIVITY_KEY))+ def _load_existing_session_ids(self, conn: Connection) -> dict[tuple[str | None, str, str, str], str]:+ rows = conn.execute(+ select(+ agent_sessions.c.id,+ agent_sessions.c.scope_id,+ agent_sessions.c.agent_variant,+ agent_sessions.c.session_anchor,+ agent_sessions.c.native_session_id,+ )+ ).mappings()+ result: dict[tuple[str | None, str, str, str], str] = {}+ for row in rows:+ result[+ _session_row_key(+ scope_id=row["scope_id"],+ agent_variant=str(row["agent_variant"] or "default"),+ session_anchor=str(row["session_anchor"] or ""),+ native_session_id=str(row["native_session_id"] or ""),+ )+ ] = str(row["id"])+ return result+def _load_session_mappings(self, conn: Connection) -> dict[str, dict[str, dict[str, Any]]]:rows = conn.execute(select(@@ -328,6 +378,16 @@ def _new_session_id(used: set[str]) -> str:return value+def _session_row_key(+ *,+ scope_id: str | None,+ agent_variant: str,+ session_anchor: str,+ native_session_id: str,+) -> tuple[str | None, str, str, str]:+ return (scope_id, agent_variant, session_anchor, native_session_id)++def _workdir_from_anchor(anchor: str) -> str | None:if ":" not in anchor:return Nonediff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.pyindex 90a7be926..1cd330ab5 100644--- a/tests/test_cli_task_command.py+++ b/tests/test_cli_task_command.py@@ -92,7 +92,7 @@ def test_task_add_rejects_disabled_platform_even_with_credentials_present() -> Nassert payload["details"]["configured_platforms"] == ["slack"]-def test_task_help_describes_session_key_guidance(capsys) -> None:+def test_task_help_describes_session_id_guidance(capsys) -> None:parser = cli.build_parser()with pytest.raises(SystemExit) as exc:@@ -101,7 +101,7 @@ def test_task_help_describes_session_key_guidance(capsys) -> None:assert exc.value.code == 0captured = capsys.readouterr()assert "Create, inspect, and control scheduled prompts for Vibe Remote." in captured.out- assert "vibe task add --session-key 'slack::channel::C123'" in captured.out+ assert "vibe task add --session-id sesk8m4q2p7x" in captured.outassert "{add,update,list,show,pause,resume,run,remove}" in captured.outassert "rm (remove)" not in captured.outassert "\n ls" not in captured.out@@ -116,7 +116,7 @@ def test_task_add_help_includes_examples_and_threadless_guidance(capsys) -> Noneassert exc.value.code == 0captured = capsys.readouterr()assert "If this is your first time using this command, read this whole help entry before creating a task." in captured.out- assert "`--session-key` chooses which session Vibe Remote will continue using when the task runs." in captured.out+ assert "`--session-id` chooses which Agent Session Vibe Remote will continue using when the task runs." in captured.outassert "--post-to" in captured.outassert "--deliver-key" in captured.out@@ -133,8 +133,8 @@ def test_hook_send_help_describes_runtime_effects(capsys) -> None:assert "`vibe hook send` queues one asynchronous turn without persisting a scheduled task." in captured.outassert "`--post-to channel` changes where the message is posted, not which session is continued." in captured.outassert "`--prompt` and `--prompt-file` provide the one-shot async content that will be queued immediately." in captured.out- assert "<platform>::channel::<channel_id>" in captured.out- assert "vibe hook send --session-key 'slack::channel::C123'" in captured.out+ assert "--session-id" in captured.out+ assert "vibe hook send --session-id sesk8m4q2p7x" in captured.outdef test_task_list_help_mentions_completed_one_shots_hidden_by_default(capsys) -> None:@@ -174,8 +174,8 @@ def test_hook_send_help_includes_examples_and_threadless_guidance(capsys) -> Nonassert "`vibe hook send` queues one asynchronous turn" in captured.outassert "--post-to" in captured.outassert "--deliver-key" in captured.out- assert "<platform>::channel::<channel_id>" in captured.out- assert "vibe hook send --session-key 'slack::channel::C123'" in captured.out+ assert "--session-id" in captured.out+ assert "vibe hook send --session-id sesk8m4q2p7x" in captured.outdef test_task_add_parse_error_is_structured_json(capsys) -> None:diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.pyindex bca7b0b84..f928a1dc0 100644--- a/tests/test_cli_watch_command.py+++ b/tests/test_cli_watch_command.py@@ -49,7 +49,7 @@ def _startup_ok(store: ManagedWatchStore, runtime_store: WatchRuntimeStateStore,return store.get_watch(watch_id), runtime_store.load().get("watches", {}).get(watch_id)-def test_watch_help_describes_session_key_guidance(capsys) -> None:+def test_watch_help_describes_session_id_guidance(capsys) -> None:parser = cli.build_parser()with pytest.raises(SystemExit) as exc:@@ -58,7 +58,7 @@ def test_watch_help_describes_session_key_guidance(capsys) -> None:assert exc.value.code == 0captured = capsys.readouterr()assert "managed background watchers" in captured.out- assert "vibe watch add --session-key 'slack::channel::C123'" in captured.out+ assert "vibe watch add --session-id sesk8m4q2p7x" in captured.outassert "{add,list,show,pause,resume,remove}" in captured.out@@ -72,7 +72,7 @@ def test_watch_add_help_mentions_shell_and_lifetime_timeout(capsys) -> None:captured = capsys.readouterr()assert "Pass either --shell '<command>' or a command after '--'." in captured.outassert "--lifetime-timeout" in captured.out- assert "vibe watch add --session-key 'slack::channel::C123'" in captured.out+ assert "vibe watch add --session-id sesk8m4q2p7x" in captured.outassert "`--prefix` becomes the instruction text of the follow-up hook." in captured.outassert "Terminal failures also send a follow-up and disable the watch." in captured.outassert "If this is your first time using this command, read this whole help entry before creating a watch." in captured.outdiff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex a86fa1584..2c002e3d4 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -869,6 +869,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):agent._session_mgr = SimpleNamespace(set_thread_id=Mock())agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-existing"),+ get_agent_session_row_id=Mock(return_value="sesk8m4q2p7x"),)request = SimpleNamespace(working_path="/tmp/work",@@ -905,12 +906,11 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(params["threadId"], "thread-existing")developer_instructions = params["developerInstructions"]self.assertEqual(developer_instructions.count("Focus on regressions."), 1)- self.assertEqual(developer_instructions.count("Current session key:"), 1)+ self.assertEqual(developer_instructions.count("Current session id:"), 1)+ self.assertNotIn("Legacy session key:", developer_instructions)+ self.assertNotIn("--session-key", developer_instructions)self.assertEqual(developer_instructions.count("If you generate an image with Codex"), 1)- self.assertIn(- "Current session key: `slack::channel::C1::thread::171717.123`",- developer_instructions,- )+ self.assertIn("Current session id: `sesk8m4q2p7x`", developer_instructions)self.assertNotIn("Channel-level session key:", developer_instructions)async def test_resume_thread_keeps_system_prompt_injection_when_quick_replies_are_disabled(self):diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.pyindex c50aee9b2..5a4fa31a4 100644--- a/tests/test_reply_enhancer_platform.py+++ b/tests/test_reply_enhancer_platform.py@@ -166,13 +166,13 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(reply.text, text)self.assertEqual(reply.buttons, [])- def test_prompt_includes_task_watch_and_hook_usage_with_thread_default_session_key(self):+ def test_prompt_includes_task_watch_and_hook_usage_with_current_session_id(self):context = MessageContext(user_id="U1",channel_id="C1",platform="slack",thread_id="171717.123",- platform_specific={"is_dm": False},+ platform_specific={"is_dm": False, "agent_session_id": "sesk8m4q2p7x"},)with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):@@ -180,14 +180,16 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):self.assertIn("## 3. Scheduled tasks, watches, and hooks", prompt)self.assertIn("`vibe task add`", prompt)- self.assertIn("`vibe hook send --session-key ... --prompt ...`", prompt)+ self.assertIn("`vibe hook send --session-id ... --prompt ...`", prompt)self.assertIn("`vibe watch add`", prompt)self.assertIn("Use `vibe task add` for saved work that should run later on a schedule or at one exact time.", prompt)self.assertIn("Use `vibe watch add` for managed background waiters that should keep running until a condition is met and then send a follow-up.",prompt,)- self.assertIn("Current session key: `slack::channel::C1::thread::171717.123`", prompt)+ self.assertIn("Current session id: `sesk8m4q2p7x`", prompt)+ self.assertNotIn("Legacy session key:", prompt)+ self.assertNotIn("--session-key", prompt)self.assertNotIn("Channel-level session key:", prompt)self.assertIn("`--post-to` changes the delivery target, not the session scope. Use `--post-to channel` when the session should stay thread-scoped but the follow-up message should be posted to the parent channel.",@@ -234,7 +236,9 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):fallback_platform="slack",)- self.assertIn("Current session key: `slack::channel::C1::thread::171717.123`", prompt)+ self.assertIn("Current session id: `<not available yet>`", prompt)+ self.assertIn("do not guess a target", prompt)+ self.assertNotIn("Legacy session key:", prompt)self.assertNotIn("Channel-level session key:", prompt)self.assertIn("usually in the current user's section: `slack/U1`.", prompt)diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex ea0f78296..a4a77d7be 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -17,6 +17,7 @@ from core.scheduled_tasks import (parse_session_key,)from modules.im import MessageContext+from storage.background import SQLiteBackgroundTaskStoreclass _StubScheduler:@@ -90,6 +91,49 @@ def test_build_session_key_for_context_uses_fallback_platform() -> None:assert parsed.to_key(include_thread=False) == "slack::channel::C123"+def test_scheduled_task_store_uses_sqlite_when_path_is_default(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ store = ScheduledTaskStore()+ task = store.add_task(+ name="Hourly summary",+ session_key="slack::channel::C123",+ session_id="sesk8m4q2p7x",+ prompt="hello",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ )++ reloaded = ScheduledTaskStore()+ saved = reloaded.get_task(task.id)+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")++ assert not (tmp_path / "state" / "scheduled_tasks.json").exists()+ assert saved is not None+ assert saved.session_id == "sesk8m4q2p7x"+ assert sqlite.get_scheduled_task(task.id)["prompt"] == "hello"+++def test_task_execution_store_uses_sqlite_runs_when_root_is_default(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ store = TaskExecutionStore()+ request = store.enqueue_hook_send(+ session_key="slack::channel::C123",+ session_id="sesk8m4q2p7x",+ prompt="hello",+ )++ claimed = store.claim(request.id)+ assert claimed is not None+ store.complete(claimed, ok=True, session_key="slack::channel::C123", session_id="sesk8m4q2p7x")++ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")+ saved = sqlite.get_run(request.id)+ assert not (tmp_path / "state" / "task_requests").exists()+ assert saved["status"] == "completed"+ assert saved["session_id"] == "sesk8m4q2p7x"++def test_store_round_trip_persists_task(tmp_path: Path) -> None:store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")task = store.add_task(diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.pyindex feccbe1d5..6fc8a5dea 100644--- a/tests/test_sqlite_sessions_store.py+++ b/tests/test_sqlite_sessions_store.py@@ -3,8 +3,12 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+from sqlalchemy import select+from config import pathsfrom config.v2_sessions import ActivePollInfo, SessionState, SessionsStore+from storage.db import create_sqlite_engine+from storage.models import agent_sessionsfrom storage.sessions_service import SQLiteSessionsService@@ -97,6 +101,63 @@ def test_sessions_store_reloads_external_sqlite_writes(tmp_path: Path) -> None:store.close()+def test_sqlite_sessions_service_preserves_agent_session_ids_on_save(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ state = SessionState(+ session_mappings={+ "slack::C123": {+ "codex": {+ "slack_171717.123": "thread-native-1",+ }+ }+ }+ )+ service.save_state(state)++ engine = create_sqlite_engine(db_path)+ try:+ with engine.connect() as conn:+ original_id = conn.execute(select(agent_sessions.c.id)).scalar_one()+ finally:+ engine.dispose()++ service.save_state(+ SessionState(+ session_mappings={+ "slack::C123": {+ "codex": {+ "slack_171717.123": "thread-native-1",+ }+ }+ },+ active_polls={+ "oc-1": ActivePollInfo(+ opencode_session_id="oc-1",+ base_session_id="base",+ channel_id="C123",+ thread_id="171717.123",+ settings_key="C123",+ working_path="/repo",+ platform="slack",+ ).to_dict()+ },+ )+ )++ engine = create_sqlite_engine(db_path)+ try:+ with engine.connect() as conn:+ saved_id = conn.execute(select(agent_sessions.c.id)).scalar_one()+ finally:+ engine.dispose()++ assert saved_id == original_id+ finally:+ service.close()++def test_sessions_store_bootstrap_uses_config_primary_platform(tmp_path: Path, monkeypatch) -> None:monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))paths.ensure_data_dirs()diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex a0b4504ed..cc3ef90b2 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -31,8 +31,10 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:assert "scope_settings" in tablesassert "agent_sessions" in tablesassert "runtime_records" in tables+ assert "background_tasks" in tables+ assert "background_runs" in tablesversion = conn.execute("select version_num from alembic_version").fetchone()- assert version == ("20260501_0001",)+ assert version == ("20260515_0002",)def test_initial_migration_is_schema_snapshot() -> None:@@ -70,7 +72,7 @@ def test_run_migrations_stamps_existing_initial_schema(tmp_path: Path) -> None:with sqlite3.connect(db_path) as conn:version = conn.execute("select version_num from alembic_version").fetchone()- assert version == ("20260501_0001",)+ assert version == ("20260515_0002",)def test_run_migrations_stamps_existing_initial_schema_with_empty_version_table(tmp_path: Path) -> None:@@ -90,7 +92,7 @@ def test_run_migrations_stamps_existing_initial_schema_with_empty_version_table(with sqlite3.connect(db_path) as conn:version = conn.execute("select version_num from alembic_version").fetchone()- assert version == ("20260501_0001",)+ assert version == ("20260515_0002",)def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:@@ -168,7 +170,100 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:assert second.imported is Falseassert second.backup_path is None- assert second.counts == {key: value for key, value in first.counts.items() if key != "discovered_scopes"}+ assert second.counts == {+ key: value+ for key, value in first.counts.items()+ if key+ not in {+ "discovered_scopes",+ "background_scheduled_tasks",+ "background_watches",+ "background_runs_imported",+ }+ }+++def test_ensure_sqlite_state_imports_background_json(tmp_path: Path) -> None:+ state_dir = tmp_path / "state"+ state_dir.mkdir()+ db_path = state_dir / "vibe.sqlite"+ (state_dir / "scheduled_tasks.json").write_text(+ json.dumps(+ {+ "tasks": [+ {+ "id": "task-1",+ "name": "Digest",+ "session_id": "sesk8m4q2p7x",+ "session_key": "slack::channel::C123",+ "prompt": "hello",+ "schedule_type": "cron",+ "cron": "0 * * * *",+ "timezone": "UTC",+ "enabled": True,+ "created_at": "2026-05-15T00:00:00+00:00",+ "updated_at": "2026-05-15T00:00:00+00:00",+ }+ ]+ }+ ),+ encoding="utf-8",+ )+ (state_dir / "watches.json").write_text(+ json.dumps(+ {+ "watches": [+ {+ "id": "watch-1",+ "name": "Watch CI",+ "session_id": "sesk8m4q2p7x",+ "session_key": "slack::channel::C123",+ "command": ["python3", "wait.py"],+ "mode": "forever",+ "timeout_seconds": 600,+ "lifetime_timeout_seconds": 3600,+ "retry_exit_codes": [75],+ "retry_delay_seconds": 30,+ "enabled": True,+ "created_at": "2026-05-15T00:00:00+00:00",+ "updated_at": "2026-05-15T00:00:00+00:00",+ }+ ]+ }+ ),+ encoding="utf-8",+ )+ pending = state_dir / "task_requests" / "pending"+ pending.mkdir(parents=True)+ (pending / "hook-1.json").write_text(+ json.dumps(+ {+ "id": "hook-1",+ "request_type": "hook_send",+ "created_at": "2026-05-15T00:00:00+00:00",+ "session_id": "sesk8m4q2p7x",+ "session_key": "slack::channel::C123",+ "prompt": "queued",+ }+ ),+ encoding="utf-8",+ )++ report = ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")++ assert report.counts["background_scheduled_tasks"] == 1+ assert report.counts["background_watches"] == 1+ assert report.counts["background_runs_imported"] == 1+ with sqlite3.connect(db_path) as conn:+ tasks = conn.execute(+ "select task_type, session_id, legacy_session_key from background_tasks order by id"+ ).fetchall()+ runs = conn.execute("select run_type, status, session_id from background_runs").fetchall()+ assert tasks == [+ ("scheduled", "sesk8m4q2p7x", "slack::channel::C123"),+ ("watch", "sesk8m4q2p7x", "slack::channel::C123"),+ ]+ assert runs == [("hook_send", "pending", "sesk8m4q2p7x")]def test_custom_state_paths_do_not_bootstrap_default_home(tmp_path: Path, monkeypatch) -> None:diff --git a/tests/test_watches.py b/tests/test_watches.pyindex 283b2bcde..ef2605d62 100644--- a/tests/test_watches.py+++ b/tests/test_watches.py@@ -14,6 +14,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from core.scheduled_tasks import TaskExecutionStorefrom core.watches import ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore+from storage.background import SQLiteBackgroundTaskStoredef test_managed_watch_store_round_trip(tmp_path: Path) -> None:@@ -73,6 +74,57 @@ def test_managed_watch_store_preserves_zero_values_on_reload(tmp_path: Path) ->assert saved.retry_delay_seconds == 0+def test_managed_watch_store_uses_sqlite_when_path_is_default(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ store = ManagedWatchStore()+ watch = store.add_watch(+ name="Watch CI",+ session_key="slack::channel::C123",+ session_id="sesk8m4q2p7x",+ command=["python3", "wait.py"],+ shell_command=None,+ prefix="CI finished.",+ cwd=None,+ mode="forever",+ timeout_seconds=600,+ lifetime_timeout_seconds=3600,+ retry_exit_codes=[75],+ retry_delay_seconds=45,+ post_to="channel",+ deliver_key=None,+ )++ reloaded = ManagedWatchStore()+ saved = reloaded.get_watch(watch.id)+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")++ assert not (tmp_path / "state" / "watches.json").exists()+ assert saved is not None+ assert saved.session_id == "sesk8m4q2p7x"+ assert sqlite.get_watch(watch.id)["command"] == ["python3", "wait.py"]+++def test_watch_runtime_store_uses_sqlite_when_path_is_default(tmp_path: Path, monkeypatch) -> None:+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ store = WatchRuntimeStateStore()++ store.write(+ {+ "watches": {+ "watch-1": {+ "running": True,+ "pid": 1234,+ "started_at": "2026-05-15T00:00:00+00:00",+ "updated_at": "2026-05-15T00:00:01+00:00",+ }+ }+ }+ )++ assert not (tmp_path / "runtime" / "watch_runtime.json").exists()+ assert store.load()["watches"]["watch-1"]["pid"] == 1234++def test_managed_watch_service_once_success_enqueues_hook_and_disables(tmp_path: Path) -> None:store = ManagedWatchStore(tmp_path / "watches.json")request_store = TaskExecutionStore(tmp_path / "task_requests")diff --git a/vibe/cli.py b/vibe/cli.pyindex 8d246b412..273191c84 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -30,7 +30,7 @@ from config.v2_config import (SlackConfig,V2Config,)-from core.scheduled_tasks import ScheduledTaskStore, TaskExecutionStore, parse_session_key+from core.scheduled_tasks import ScheduledTaskStore, TaskExecutionStore, parse_session_key, resolve_session_id_targetfrom core.watches import (DEFAULT_RETRY_EXIT_CODE,WATCH_RECONCILE_INTERVAL_SECONDS,@@ -132,12 +132,11 @@ def _task_examples_text() -> str:return dedent("""\Examples:- vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *' --prompt 'Share the hourly summary.'+ vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --prompt 'Share the hourly summary.'vibe task update 12ab34cd56ef --cron '*/30 * * * *' --name 'Half-hour summary'vibe task run 12ab34cd56ef- vibe task add --session-key 'discord::user::123456789' --at '2026-03-31T09:00:00+08:00' --prompt-file briefing.md- vibe task add --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --cron '*/5 * * * *' --prompt 'Tell a new joke each time.'- vibe task add --session-key 'lark::channel::oc_abc::thread::om_123' --cron '30 9 * * 1-5' --prompt 'Post the daily standup reminder in this thread.'+ vibe task add --session-id sesk8m4q2p7x --post-to channel --cron '*/5 * * * *' --prompt 'Tell a new joke each time.'+ vibe task add --session-id sesk8m4q2p7x --at '2026-03-31T09:00:00+08:00' --prompt-file briefing.md""")@@ -145,19 +144,14 @@ def _task_examples_text() -> str:def _task_add_examples_text() -> str:return dedent("""\- Session key format:- <platform>::channel::<channel_id>- <platform>::user::<user_id>- <platform>::channel::<channel_id>::thread::<thread_id>- <platform>::user::<user_id>::thread::<thread_id>+ Session target:+ Use --session-id with the current Agent Session ID, for example sesk8m4q2p7x.Guidance:If this is your first time using this command, read this whole help entry before creating a task.- `--session-key` chooses which session Vibe Remote will continue using when the task runs.- Keep the current session key when future runs should stay in the same session.- When you want to leave the current thread session and start or reuse the higher-level session instead, use the higher-level key. Example:- slack::channel::C123::thread::171717.123 -> keep the current thread session- slack::channel::C123 -> create or reuse the channel-scoped session+ `--session-id` chooses which Agent Session Vibe Remote will continue using when the task runs.+ Keep the current session id when future runs should stay in the same session.+ If no session id is available, trigger this from an active Vibe Remote conversation instead of guessing.`--post-to channel` changes where the message is posted, not which session is continued.Use --deliver-key only when delivery must go to a different explicit target.`--prompt` and `--prompt-file` provide the stored task content that will be injected each time the task runs.@@ -165,11 +159,9 @@ def _task_add_examples_text() -> str:--timezone controls how --cron and naive --at timestamps are interpreted.Examples:- vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *' --prompt 'Share the hourly summary.'- vibe task add --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --cron '*/5 * * * *' --prompt 'Tell a new joke each time.'- vibe task add --session-key 'slack::channel::C123::thread::171717.123' --deliver-key 'slack::channel::C999' --cron '0 9 * * *' --prompt 'Post the daily summary in the announcements channel.'- vibe task add --session-key 'discord::user::123456789' --at '2026-03-31T09:00:00+08:00' --prompt 'Send the release reminder.'- vibe task add --session-key 'lark::channel::oc_abc::thread::om_123' --cron '30 9 * * 1-5' --timezone 'Asia/Shanghai' --prompt-file standup.txt+ vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --prompt 'Share the hourly summary.'+ vibe task add --session-id sesk8m4q2p7x --post-to channel --cron '*/5 * * * *' --prompt 'Tell a new joke each time.'+ vibe task add --session-id sesk8m4q2p7x --deliver-key 'slack::channel::C999' --cron '0 9 * * *' --prompt 'Post the daily summary in the announcements channel.'""")@@ -183,13 +175,13 @@ def _task_update_examples_text() -> str:vibe task update 12ab34cd56ef --name 'Morning summary'vibe task update 12ab34cd56ef --cron '*/30 * * * *'vibe task update 12ab34cd56ef --prompt 'Send a shorter summary.'- vibe task update 12ab34cd56ef --session-key 'slack::channel::C123::thread::171717.123' --post-to channel+ vibe task update 12ab34cd56ef --session-id sesk8m4q2p7x --post-to channelvibe task update 12ab34cd56ef --deliver-key 'slack::channel::C999'vibe task update 12ab34cd56ef --reset-deliveryGuidance:Unspecified fields keep their existing values.- Use --reset-delivery to return to following --session-key directly.+ Use --reset-delivery to return to following the session target directly.When changing schedule fields, pass either --cron or --at.Use --clear-name if you want the task to stop storing a custom name."""@@ -199,30 +191,23 @@ def _task_update_examples_text() -> str:def _hook_send_examples_text() -> str:return dedent("""\- Session key format:- <platform>::channel::<channel_id>- <platform>::user::<user_id>- <platform>::channel::<channel_id>::thread::<thread_id>- <platform>::user::<user_id>::thread::<thread_id>+ Session target:+ Use --session-id with the current Agent Session ID, for example sesk8m4q2p7x.Guidance:If this is your first time using this command, read this whole help entry before queuing a hook.`vibe hook send` queues one asynchronous turn without persisting a scheduled task.- `--session-key` chooses which session Vibe Remote will continue using for that one async turn.- Keep the current session key when the hook should continue in the same session.- When you want to leave the current thread session and start or reuse the higher-level session instead, use the higher-level key. Example:- slack::channel::C123::thread::171717.123 -> keep the current thread session- slack::channel::C123 -> create or reuse the channel-scoped session+ `--session-id` chooses which Agent Session Vibe Remote will continue using for that one async turn.+ Keep the current session id when the hook should continue in the same session.+ If no session id is available, trigger this from an active Vibe Remote conversation instead of guessing.`--post-to channel` changes where the message is posted, not which session is continued.Use --deliver-key only when delivery must go to a different explicit target.`--prompt` and `--prompt-file` provide the one-shot async content that will be queued immediately.Examples:- vibe hook send --session-key 'slack::channel::C123' --prompt 'The export finished. Share the summary.'- vibe hook send --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --prompt 'Share the benchmark result in the channel.'- vibe hook send --session-key 'slack::channel::C123' --deliver-key 'slack::channel::C999' --prompt 'Post the deployment summary in announcements.'- vibe hook send --session-key 'discord::user::123456789' --prompt-file release-note.txt- vibe hook send --session-key 'lark::channel::oc_abc::thread::om_123' --prompt 'Post the benchmark result in this thread.'+ vibe hook send --session-id sesk8m4q2p7x --prompt 'The export finished. Share the summary.'+ vibe hook send --session-id sesk8m4q2p7x --post-to channel --prompt 'Share the benchmark result in the channel.'+ vibe hook send --session-id sesk8m4q2p7x --deliver-key 'slack::channel::C999' --prompt 'Post the deployment summary in announcements.'""")@@ -231,9 +216,9 @@ def _watch_examples_text() -> str:return dedent("""\Examples:- vibe watch add --session-key 'slack::channel::C123' --name 'Wait for export' --shell 'python3 scripts/wait_for_export.py'- vibe watch add --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --prefix 'The CI job finished.' -- python3 scripts/wait_for_ci.py --build 42- vibe watch add --session-key 'slack::channel::C123' --forever --retry-exit-code 75 --retry-delay 60 --shell 'bash scripts/wait_for_log_pattern.sh'+ vibe watch add --session-id sesk8m4q2p7x --name 'Wait for export' --shell 'python3 scripts/wait_for_export.py'+ vibe watch add --session-id sesk8m4q2p7x --post-to channel --prefix 'The CI job finished.' -- python3 scripts/wait_for_ci.py --build 42+ vibe watch add --session-id sesk8m4q2p7x --forever --retry-exit-code 75 --retry-delay 60 --shell 'bash scripts/wait_for_log_pattern.sh'vibe watch list --briefvibe watch show 12ab34cd56efvibe watch pause 12ab34cd56ef@@ -280,20 +265,15 @@ def _print_json(payload: dict) -> None:def _watch_add_examples_text() -> str:return dedent("""\- Session key format:- <platform>::channel::<channel_id>- <platform>::user::<user_id>- <platform>::channel::<channel_id>::thread::<thread_id>- <platform>::user::<user_id>::thread::<thread_id>+ Session target:+ Use --session-id with the current Agent Session ID, for example sesk8m4q2p7x.Guidance:If this is your first time using this command, read this whole help entry before creating a watch.Use a watch when a script should wait in the background and send a follow-up when it detects an event or reaches a terminal failure.- `--session-key` chooses which session Vibe Remote will continue using for follow-up messages from the watch.- Keep the current session key when follow-up should continue in the same session.- When you want to leave the current thread session and start or reuse the higher-level session instead, use the higher-level key. Example:- slack::channel::C123::thread::171717.123 -> keep the current thread session- slack::channel::C123 -> create or reuse the channel-scoped session+ `--session-id` chooses which Agent Session Vibe Remote will continue using for follow-up messages from the watch.+ Keep the current session id when follow-up should continue in the same session.+ If no session id is available, trigger this from an active Vibe Remote conversation instead of guessing.`--post-to channel` changes where the follow-up is posted, not which session is continued.Use --deliver-key only when delivery must go to a different explicit target.`--prefix` becomes the instruction text of the follow-up hook. On a successful cycle, Vibe Remote prepends `--prefix` before waiter stdout and joins them with a blank line when both exist.@@ -303,9 +283,9 @@ def _watch_add_examples_text() -> str:--timeout applies to each cycle. --lifetime-timeout applies only to the whole forever watch lifetime.Examples:- vibe watch add --session-key 'slack::channel::C123' --shell 'python3 scripts/wait_for_export.py'- vibe watch add --session-key 'slack::channel::C123::thread::171717.123' --post-to channel --prefix 'The export finished.' -- bash -lc 'sleep 120; echo done'- vibe watch add --session-key 'slack::channel::C123' --forever --timeout 600 --lifetime-timeout 86400 --retry-exit-code 75 --retry-delay 30 -- uv run --no-project scripts/wait_pr.py --repo cyhhao/vibe-remote --pr 153+ vibe watch add --session-id sesk8m4q2p7x --shell 'python3 scripts/wait_for_export.py'+ vibe watch add --session-id sesk8m4q2p7x --post-to channel --prefix 'The export finished.' -- bash -lc 'sleep 120; echo done'+ vibe watch add --session-id sesk8m4q2p7x --forever --timeout 600 --lifetime-timeout 86400 --retry-exit-code 75 --retry-delay 30 -- uv run --no-project scripts/wait_pr.py --repo cyhhao/vibe-remote --pr 153""")@@ -636,6 +616,7 @@ def _task_payload(task, *, brief: bool = False):"next_run_at": derived["next_run_at"],"schedule_type": task.schedule_type,"schedule_summary": derived["schedule_summary"],+ "session_id": task.session_id,"session_key": task.session_key,"post_to": task.post_to,"deliver_key": task.deliver_key,@@ -724,9 +705,71 @@ def _parse_validated_session_key(return parsed+def _validate_session_id_target(+ session_id: str,+ *,+ help_command: str,+) -> object:+ try:+ resolved = resolve_session_id_target(session_id)+ except ValueError as exc:+ raise TaskCliError(+ str(exc),+ code="invalid_session_id",+ hint="Use the current Agent Session ID from the prompt, such as sesk8m4q2p7x.",+ example="sesk8m4q2p7x",+ help_command=help_command,+ details={"session_id": session_id},+ ) from exc++ supported_platforms = _supported_task_platforms()+ if resolved.session_key.platform not in supported_platforms:+ supported_text = ", ".join(sorted(supported_platforms)) or "none"+ raise TaskCliError(+ f"unsupported task platform: {resolved.session_key.platform}",+ code="unsupported_platform",+ hint="Choose a session whose platform is enabled in Vibe Remote before sending the request.",+ example="sesk8m4q2p7x",+ help_command=help_command,+ details={+ "requested_platform": resolved.session_key.platform,+ "configured_platforms": sorted(supported_platforms),+ "configured_platforms_text": supported_text,+ },+ )+ return resolved.session_key+++def _resolve_session_target_args(+ args,+ *,+ required: bool,+ help_command: str,+) -> tuple[Optional[str], str]:+ session_id = (getattr(args, "session_id", None) or "").strip()+ session_key = (getattr(args, "session_key", None) or "").strip()+ if session_id and session_key:+ raise TaskCliError(+ "use either --session-id or --session-key, not both",+ code="conflicting_session_target",+ hint="Use --session-id for new commands.",+ help_command=help_command,+ )+ if required and not session_id and not session_key:+ raise TaskCliError(+ "one of --session-id or --session-key is required",+ code="missing_session_target",+ hint="Use --session-id with the current Agent Session ID.",+ example="vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --prompt 'Share the hourly summary.'",+ help_command=help_command,+ )+ return session_id or None, session_key++def _validate_delivery_args(*,session_key: str,+ session_id: Optional[str] = None,post_to: Optional[str],deliver_key: Optional[str],help_command: str,@@ -739,13 +782,16 @@ def _validate_delivery_args(help_command=help_command,)- session_target = _parse_validated_session_key(session_key, help_command=help_command)+ if session_id:+ session_target = _validate_session_id_target(session_id, help_command=help_command)+ else:+ session_target = _parse_validated_session_key(session_key, help_command=help_command)delivery_target = Noneif deliver_key:delivery_target = _parse_validated_session_key(deliver_key, help_command=help_command)if delivery_target.platform != session_target.platform:raise TaskCliError(- "--deliver-key must use the same platform as --session-key",+ "--deliver-key must use the same platform as the session target",code="invalid_delivery_target",hint="Keep session memory and delivery on the same IM platform. Change only the channel, user, or thread target.",help_command=help_command,@@ -756,46 +802,46 @@ def _validate_delivery_args()elif post_to == "thread" and not session_target.thread_id:raise TaskCliError(- "--post-to thread requires a thread-bound --session-key or an explicit --deliver-key",+ "--post-to thread requires a thread-bound session target or an explicit --deliver-key",code="invalid_delivery_target",- hint="Append ::thread::<thread_id> to --session-key, or use --deliver-key with a thread target.",+ hint="Use a thread-bound Agent Session ID or --deliver-key with a thread target.",help_command=help_command,- details={"session_key": session_key, "post_to": post_to},+ details={"session_id": session_id, "session_key": session_key, "post_to": post_to},)return session_target, delivery_targetdef _collect_target_warnings(*targets) -> list[dict]:+ lark_targets = [target for target in targets if target is not None and target.platform == "lark" and target.is_dm]+ if not lark_targets:+ return []store = SettingsStore.get_instance(paths.get_settings_path())warnings: list[dict] = []seen: set[tuple[str, str, str]] = set()- for target in targets:- if target is None:- continue+ for target in lark_targets:dedupe_key = (target.platform, target.scope_type, target.scope_id)if dedupe_key in seen:continueseen.add(dedupe_key)- if target.platform == "lark" and target.is_dm:- bound_user = store.get_user(target.scope_id, platform="lark")- if bound_user is None:- warnings.append(- {- "code": "lark_user_not_bound",- "message": "The target Lark user is not bound in Vibe Remote yet; delivery may fail at runtime.",- "details": {"session_key": target.to_key(include_thread=False)},- }- )- elif not getattr(bound_user, "dm_chat_id", ""):- warnings.append(- {- "code": "lark_dm_chat_unbound",- "message": "The target Lark user has no dm_chat_id binding yet; delivery may fail at runtime.",- "details": {"session_key": target.to_key(include_thread=False)},- }- )+ bound_user = store.get_user(target.scope_id, platform="lark")+ if bound_user is None:+ warnings.append(+ {+ "code": "lark_user_not_bound",+ "message": "The target Lark user is not bound in Vibe Remote yet; delivery may fail at runtime.",+ "details": {"session_key": target.to_key(include_thread=False)},+ }+ )+ elif not getattr(bound_user, "dm_chat_id", ""):+ warnings.append(+ {+ "code": "lark_dm_chat_unbound",+ "message": "The target Lark user has no dm_chat_id binding yet; delivery may fail at runtime.",+ "details": {"session_key": target.to_key(include_thread=False)},+ }+ )return warnings@@ -865,6 +911,7 @@ def _watch_payload(watch, runtime_entry: Optional[dict[str, object]], *, brief:"display_name": derived["display_name"],"state": derived["state"],"mode": watch.mode,+ "session_id": watch.session_id,"session_key": watch.session_key,"timeout_seconds": watch.timeout_seconds,"lifetime_timeout_seconds": watch.lifetime_timeout_seconds,@@ -960,8 +1007,14 @@ def _wait_for_watch_startup(def cmd_task_add(args):try:+ session_id, session_key = _resolve_session_target_args(+ args,+ required=True,+ help_command="vibe task add --help",+ )session_target, delivery_target = _validate_delivery_args(- session_key=args.session_key,+ session_id=session_id,+ session_key=session_key,post_to=getattr(args, "post_to", None),deliver_key=getattr(args, "deliver_key", None),help_command="vibe task add --help",@@ -969,7 +1022,7 @@ def cmd_task_add(args):prompt = _resolve_prompt_input(args,help_command="vibe task add --help",- example_command="vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *'",+ example_command="vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *'",)timezone_name = args.timezone or _default_timezone_name()try:@@ -999,7 +1052,8 @@ def cmd_task_add(args):) from exctask = store.add_task(name=_normalize_task_name(getattr(args, "name", None)),- session_key=args.session_key,+ session_key=session_key,+ session_id=session_id,post_to=args.post_to,deliver_key=args.deliver_key,prompt=prompt,@@ -1021,7 +1075,8 @@ def cmd_task_add(args):) from exctask = store.add_task(name=_normalize_task_name(getattr(args, "name", None)),- session_key=args.session_key,+ session_key=session_key,+ session_id=session_id,post_to=args.post_to,deliver_key=args.deliver_key,prompt=prompt,@@ -1125,7 +1180,13 @@ def cmd_task_update(args):hint="Pass --reset-delivery to clear delivery overrides, or pass --post-to/--deliver-key to replace them.",help_command="vibe task update --help",)- session_key = args.session_key or task.session_key+ session_id_update, session_key_update = _resolve_session_target_args(+ args,+ required=False,+ help_command="vibe task update --help",+ )+ session_id = session_id_update if session_id_update is not None else task.session_id+ session_key = session_key_update if session_key_update else ("" if session_id_update else task.session_key)if getattr(args, "reset_delivery", False):post_to = Nonedeliver_key = None@@ -1143,6 +1204,7 @@ def cmd_task_update(args):deliver_key = task.deliver_keysession_target, delivery_target = _validate_delivery_args(+ session_id=session_id,session_key=session_key,post_to=post_to,deliver_key=deliver_key,@@ -1231,6 +1293,7 @@ def cmd_task_update(args):changes = {"name": name,+ "session_id": session_id,"session_key": session_key,"prompt": prompt,"schedule_type": schedule_type,@@ -1242,6 +1305,7 @@ def cmd_task_update(args):}current = {"name": task.name,+ "session_id": task.session_id,"session_key": task.session_key,"prompt": task.prompt,"schedule_type": task.schedule_type,@@ -1255,7 +1319,7 @@ def cmd_task_update(args):raise TaskCliError("no task fields were changed",code="no_task_changes",- hint="Pass at least one field to update, such as --name, --cron, --prompt, --session-key, or --deliver-key.",+ hint="Pass at least one field to update, such as --name, --cron, --prompt, --session-id, or --deliver-key.",help_command="vibe task update --help",details={"task_id": args.task_id},)@@ -1264,6 +1328,7 @@ def cmd_task_update(args):args.task_id,name=name,session_key=session_key,+ session_id=session_id,prompt=prompt,schedule_type=schedule_type,post_to=post_to,@@ -1312,8 +1377,14 @@ def cmd_task_run(task_id: str):def cmd_hook_send(args):try:+ session_id, session_key = _resolve_session_target_args(+ args,+ required=True,+ help_command="vibe hook send --help",+ )session_target, delivery_target = _validate_delivery_args(- session_key=args.session_key,+ session_id=session_id,+ session_key=session_key,post_to=getattr(args, "post_to", None),deliver_key=getattr(args, "deliver_key", None),help_command="vibe hook send --help",@@ -1321,10 +1392,11 @@ def cmd_hook_send(args):prompt = _resolve_prompt_input(args,help_command="vibe hook send --help",- example_command="vibe hook send --session-key 'slack::channel::C123'",+ example_command="vibe hook send --session-id sesk8m4q2p7x",)request = _task_request_store().enqueue_hook_send(- session_key=args.session_key,+ session_key=session_key,+ session_id=session_id,post_to=args.post_to,deliver_key=args.deliver_key,prompt=prompt,@@ -1337,7 +1409,8 @@ def cmd_hook_send(args):"accepted": True,"execution_id": request.id,"request_type": request.request_type,- "session_key": args.session_key,+ "session_id": session_id,+ "session_key": session_key,"post_to": args.post_to,"deliver_key": args.deliver_key,"warnings": warnings,@@ -1353,8 +1426,14 @@ def cmd_hook_send(args):def cmd_watch_add(args):try:+ session_id, session_key = _resolve_session_target_args(+ args,+ required=True,+ help_command="vibe watch add --help",+ )session_target, delivery_target = _validate_delivery_args(- session_key=args.session_key,+ session_id=session_id,+ session_key=session_key,post_to=getattr(args, "post_to", None),deliver_key=getattr(args, "deliver_key", None),help_command="vibe watch add --help",@@ -1409,7 +1488,8 @@ def cmd_watch_add(args):store = _watch_store()watch = store.add_watch(name=_normalize_watch_name(getattr(args, "name", None)),- session_key=args.session_key,+ session_key=session_key,+ session_id=session_id,command=command,shell_command=shell_command,prefix=_normalize_task_name(getattr(args, "prefix", None)),@@ -2479,16 +2559,19 @@ def build_parser():epilog=_task_add_examples_text(),formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe task add --help",- error_hint="Use --session-key together with exactly one schedule flag and one prompt input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",+ error_hint="Use --session-id together with exactly one schedule flag and one prompt input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",)task_add_parser.add_argument("--name",help="Optional human-friendly task name",)+ task_add_parser.add_argument(+ "--session-id",+ help="Agent Session ID to continue when the task runs.",+ )task_add_parser.add_argument("--session-key",- required=True,- help="Conversation session key to continue when the task runs.",+ help="Legacy compatibility target; prefer --session-id.",)delivery_group = task_add_parser.add_mutually_exclusive_group()delivery_group.add_argument(@@ -2524,7 +2607,8 @@ def build_parser():action="store_true",help="Remove the stored custom task name",)- task_update_parser.add_argument("--session-key", help="Replace the stored session key")+ task_update_parser.add_argument("--session-id", help="Replace the stored Agent Session ID")+ task_update_parser.add_argument("--session-key", help="Legacy compatibility target; prefer --session-id")update_delivery_group = task_update_parser.add_mutually_exclusive_group()update_delivery_group.add_argument("--post-to",@@ -2538,7 +2622,7 @@ def build_parser():task_update_parser.add_argument("--reset-delivery",action="store_true",- help="Clear any stored delivery override so delivery follows --session-key directly",+ help="Clear any stored delivery override so delivery follows the session target directly",)task_update_parser.add_argument("--cron", help="Replace the schedule with a recurring 5-field crontab")task_update_parser.add_argument("--at", help="Replace the schedule with a one-shot ISO 8601 timestamp")@@ -2631,16 +2715,19 @@ def build_parser():hook_send_parser = hook_subparsers.add_parser("send",help="Queue one async hook message",- description="Queue one asynchronous turn for a session key without storing a scheduled task.",+ description="Queue one asynchronous turn for an Agent Session ID without storing a scheduled task.",epilog=_hook_send_examples_text(),formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe hook send --help",- error_hint="Use --session-key together with exactly one prompt input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",+ error_hint="Use --session-id together with exactly one prompt input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",+ )+ hook_send_parser.add_argument(+ "--session-id",+ help="Agent Session ID to continue for this one-shot async turn.",)hook_send_parser.add_argument("--session-key",- required=True,- help="Conversation session key to continue for this one-shot async turn.",+ help="Legacy compatibility target; prefer --session-id.",)hook_delivery_group = hook_send_parser.add_mutually_exclusive_group()hook_delivery_group.add_argument(@@ -2678,13 +2765,16 @@ def build_parser():epilog=_watch_add_examples_text(),formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe watch add --help",- error_hint="Use --session-key and either --shell or a command after '--'. Add --forever only when the waiter should re-arm after successful cycles and only retry failures for explicit retry exit codes.",+ error_hint="Use --session-id and either --shell or a command after '--'. Add --forever only when the waiter should re-arm after successful cycles and only retry failures for explicit retry exit codes.",)watch_add_parser.add_argument("--name", help="Optional human-friendly watch name")+ watch_add_parser.add_argument(+ "--session-id",+ help="Agent Session ID to continue for follow-up messages from this watch.",+ )watch_add_parser.add_argument("--session-key",- required=True,- help="Conversation session key to continue for follow-up messages from this watch.",+ help="Legacy compatibility target; prefer --session-id.",)watch_delivery_group = watch_add_parser.add_mutually_exclusive_group()watch_delivery_group.add_argument(