Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(watch): add managed vibe watch commands

cyh55aaff64be75
diff --git a/config/paths.py b/config/paths.py
index 27504ee25..1e3a4272a 100644
--- a/config/paths.py
+++ b/config/paths.py
@@ -57,6 +57,14 @@ def get_sessions_path() -> Path:
return get_state_dir() / "sessions.json"
+def get_watches_path() -> Path:
+ return get_state_dir() / "watches.json"
+
+
+def get_watch_runtime_path() -> Path:
+ return get_runtime_dir() / "watch_runtime.json"
+
+
def get_discovered_chats_path() -> Path:
return get_state_dir() / "discovered_chats.json"
diff --git a/core/controller.py b/core/controller.py
index 372c13b3b..447b15b3d 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -24,6 +24,7 @@ from core.handlers import (
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.scheduled_tasks import ScheduledTaskService
from core.update_checker import UpdateChecker
+from core.watches import ManagedWatchService
from vibe.i18n import get_supported_languages, t as i18n_t
logger = logging.getLogger(__name__)
@@ -65,6 +66,7 @@ class Controller:
# Consolidated message dispatcher
self.message_dispatcher = ConsolidatedMessageDispatcher(self)
self.scheduled_task_service = ScheduledTaskService(self)
+ self.watch_service = ManagedWatchService(self)
# Background task for cleanup
self.cleanup_task: Optional[asyncio.Task] = None
@@ -389,6 +391,10 @@ class Controller:
self.scheduled_task_service.start()
except Exception as e:
logger.error("Failed to start scheduled task service: %s", e, exc_info=True)
+ try:
+ self.watch_service.start()
+ except Exception as e:
+ logger.error("Failed to start watch service: %s", e, exc_info=True)
# Utility methods used by handlers
@@ -590,6 +596,13 @@ class Controller:
future.result(timeout=5)
except Exception as e:
logger.debug(f"Scheduled task service cleanup skipped: {e}")
+ try:
+ loop = self._loop
+ if loop and not loop.is_closed():
+ future = asyncio.run_coroutine_threadsafe(self.watch_service.stop(), loop)
+ future.result(timeout=5)
+ except Exception as e:
+ logger.debug(f"Watch service cleanup skipped: {e}")
# Cancel receiver tasks without awaiting (they may belong to other loops)
try:
diff --git a/core/reply_enhancer.py b/core/reply_enhancer.py
index 0dc86f6de..8a3ae0140 100644
--- a/core/reply_enhancer.py
+++ b/core/reply_enhancer.py
@@ -192,6 +192,7 @@ _SCHEDULED_TASKS_PROMPT = """\
## 3. Scheduled tasks and hooks
Use `vibe task add` for actions that should recur or remain saved.
Use `vibe hook send --session-key ... --prompt ...` for one-shot asynchronous sends without storing a task.
+Use `vibe watch add` when a background waiter should stay managed by Vibe Remote until it emits a follow-up hook.
Current conversation targeting:
- Default session key: `{session_key}`
@@ -202,9 +203,10 @@ Rules:
- Only append `::thread::<thread_id>` to `--session-key` when the user explicitly wants replies to stay in the current thread.
- Use `--post-to channel` when the task or hook should keep thread context but publish to the parent channel.
- Use `--cron "<expr>"` for recurring tasks or `--at "<ISO-8601>"` for one-off stored tasks.
+- Use `--timeout <seconds>` on watches for per-cycle timeouts, and `--lifetime-timeout <seconds>` only when a forever watch also needs an overall lifetime cap.
- If `--timezone` is omitted, the task uses the local system timezone at creation time.
- Use `--prompt "..."` or `--prompt-file <path>` for task and hook content.
-- Run `vibe task add --help` or `vibe hook send --help` for the full command reference.
+- Run `vibe task add --help`, `vibe hook send --help`, or `vibe watch add --help` for the full command reference.
"""
diff --git a/core/watches.py b/core/watches.py
new file mode 100644
index 000000000..0b0411060
--- /dev/null
+++ b/core/watches.py
@@ -0,0 +1,517 @@
+"""Managed background watch persistence and runtime orchestration."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import tempfile
+from dataclasses import asdict, dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Optional
+from uuid import uuid4
+
+from config import paths
+from core.scheduled_tasks import TaskExecutionStore
+
+logger = logging.getLogger(__name__)
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _path_signature(path: Path) -> Optional[tuple[int, int, int]]:
+ try:
+ stat = path.stat()
+ except FileNotFoundError:
+ return None
+ return (stat.st_mtime_ns, stat.st_size, stat.st_ino)
+
+
+@dataclass
+class ManagedWatch:
+ id: str
+ name: Optional[str]
+ session_key: str
+ command: list[str] = field(default_factory=list)
+ shell_command: Optional[str] = None
+ prefix: Optional[str] = None
+ cwd: Optional[str] = None
+ mode: str = "once"
+ timeout_seconds: float = 21600.0
+ lifetime_timeout_seconds: float = 0.0
+ retry_exit_codes: list[int] = field(default_factory=lambda: [1])
+ retry_delay_seconds: float = 30.0
+ post_to: Optional[str] = None
+ deliver_key: Optional[str] = None
+ enabled: bool = True
+ created_at: str = field(default_factory=_utc_now_iso)
+ updated_at: str = field(default_factory=_utc_now_iso)
+ last_started_at: Optional[str] = None
+ last_finished_at: Optional[str] = None
+ last_event_at: Optional[str] = None
+ last_error: Optional[str] = None
+ last_exit_code: Optional[int] = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, payload: dict[str, Any]) -> "ManagedWatch":
+ return cls(
+ 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 ""),
+ 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,
+ cwd=(str(payload["cwd"]).strip() if payload.get("cwd") else None) or None,
+ mode=str(payload.get("mode") or "once"),
+ timeout_seconds=float(payload.get("timeout_seconds") or 21600.0),
+ lifetime_timeout_seconds=float(payload.get("lifetime_timeout_seconds") or 0.0),
+ retry_exit_codes=[int(code) for code in (payload.get("retry_exit_codes") or [1])],
+ retry_delay_seconds=float(payload.get("retry_delay_seconds") or 30.0),
+ post_to=payload.get("post_to"),
+ deliver_key=payload.get("deliver_key"),
+ enabled=bool(payload.get("enabled", True)),
+ created_at=str(payload.get("created_at") or _utc_now_iso()),
+ updated_at=str(payload.get("updated_at") or _utc_now_iso()),
+ last_started_at=payload.get("last_started_at"),
+ last_finished_at=payload.get("last_finished_at"),
+ last_event_at=payload.get("last_event_at"),
+ last_error=payload.get("last_error"),
+ last_exit_code=(int(payload["last_exit_code"]) if payload.get("last_exit_code") is not None else None),
+ )
+
+
+class ManagedWatchStore:
+ def __init__(self, path: Optional[Path] = None):
+ self.path = path or paths.get_watches_path()
+ self._signature: Optional[tuple[int, int, int]] = None
+ self._watches: dict[str, ManagedWatch] = {}
+ self.load()
+
+ def load(self) -> None:
+ if not self.path.exists():
+ self._watches = {}
+ self._signature = None
+ return
+ try:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
+ except Exception as exc:
+ logger.error("Failed to load managed watches: %s", exc)
+ self._watches = {}
+ self._signature = None
+ return
+
+ raw_watches = payload.get("watches", []) if isinstance(payload, dict) else []
+ watches: dict[str, ManagedWatch] = {}
+ for item in raw_watches:
+ if not isinstance(item, dict):
+ continue
+ watch = ManagedWatch.from_dict(item)
+ watches[watch.id] = watch
+ self._watches = watches
+ self._signature = _path_signature(self.path)
+
+ def maybe_reload(self) -> bool:
+ signature = _path_signature(self.path)
+ if signature == self._signature:
+ return False
+ self.load()
+ return True
+
+ def _save(self) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ payload = {"watches": [watch.to_dict() for watch in self.list_watches()]}
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ dir=self.path.parent,
+ suffix=".tmp",
+ delete=False,
+ encoding="utf-8",
+ ) as handle:
+ json.dump(payload, handle, indent=2)
+ tmp_path = Path(handle.name)
+ tmp_path.replace(self.path)
+ self._signature = _path_signature(self.path)
+
+ def list_watches(self) -> list[ManagedWatch]:
+ return sorted(self._watches.values(), key=lambda item: (item.created_at, item.id))
+
+ def get_watch(self, watch_id: str) -> Optional[ManagedWatch]:
+ return self._watches.get(watch_id)
+
+ def upsert_watch(self, watch: ManagedWatch) -> ManagedWatch:
+ watch.updated_at = _utc_now_iso()
+ self._watches[watch.id] = watch
+ self._save()
+ return watch
+
+ def add_watch(
+ self,
+ *,
+ name: Optional[str],
+ session_key: str,
+ command: list[str],
+ shell_command: Optional[str],
+ prefix: Optional[str],
+ cwd: Optional[str],
+ mode: str,
+ timeout_seconds: float,
+ lifetime_timeout_seconds: float,
+ retry_exit_codes: list[int],
+ retry_delay_seconds: float,
+ post_to: Optional[str],
+ deliver_key: Optional[str],
+ ) -> ManagedWatch:
+ watch = ManagedWatch(
+ id=uuid4().hex[:12],
+ name=name,
+ session_key=session_key,
+ command=command,
+ shell_command=shell_command,
+ prefix=prefix,
+ cwd=cwd,
+ mode=mode,
+ timeout_seconds=timeout_seconds,
+ lifetime_timeout_seconds=lifetime_timeout_seconds,
+ retry_exit_codes=retry_exit_codes,
+ retry_delay_seconds=retry_delay_seconds,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ )
+ return self.upsert_watch(watch)
+
+ def remove_watch(self, watch_id: str) -> bool:
+ if watch_id not in self._watches:
+ return False
+ del self._watches[watch_id]
+ self._save()
+ return True
+
+ def set_enabled(self, watch_id: str, enabled: bool) -> ManagedWatch:
+ watch = self._watches[watch_id]
+ watch.enabled = enabled
+ watch.updated_at = _utc_now_iso()
+ self._save()
+ return watch
+
+ def mark_cycle_start(self, watch_id: str) -> bool:
+ self.maybe_reload()
+ watch = self._watches.get(watch_id)
+ if watch is None:
+ return False
+ watch.last_started_at = _utc_now_iso()
+ watch.last_error = None
+ watch.updated_at = _utc_now_iso()
+ self._save()
+ return True
+
+ def mark_cycle_result(
+ self,
+ watch_id: str,
+ *,
+ exit_code: Optional[int],
+ error: Optional[str],
+ event_detected: bool = False,
+ disable: bool = False,
+ ) -> bool:
+ self.maybe_reload()
+ watch = self._watches.get(watch_id)
+ if watch is None:
+ return False
+ watch.last_finished_at = _utc_now_iso()
+ watch.last_exit_code = exit_code
+ watch.last_error = error
+ if event_detected:
+ watch.last_event_at = watch.last_finished_at
+ if disable:
+ watch.enabled = False
+ watch.updated_at = _utc_now_iso()
+ self._save()
+ return True
+
+
+class WatchRuntimeStateStore:
+ def __init__(self, path: Optional[Path] = None):
+ self.path = path or paths.get_watch_runtime_path()
+
+ def write(self, payload: dict[str, Any]) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ dir=self.path.parent,
+ suffix=".tmp",
+ delete=False,
+ encoding="utf-8",
+ ) as handle:
+ json.dump(payload, handle, indent=2)
+ tmp_path = Path(handle.name)
+ tmp_path.replace(self.path)
+
+ def load(self) -> dict[str, Any]:
+ if not self.path.exists():
+ return {"watches": {}}
+ try:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
+ except Exception:
+ return {"watches": {}}
+ if not isinstance(payload, dict):
+ return {"watches": {}}
+ return payload
+
+
+@dataclass
+class _CycleResult:
+ exit_code: int
+ stdout: str
+ stderr: str
+ timed_out: bool
+
+
+class ManagedWatchService:
+ def __init__(
+ self,
+ controller,
+ store: Optional[ManagedWatchStore] = None,
+ request_store: Optional[TaskExecutionStore] = None,
+ runtime_store: Optional[WatchRuntimeStateStore] = None,
+ ):
+ self.controller = controller
+ self.store = store or ManagedWatchStore()
+ self.request_store = request_store or TaskExecutionStore()
+ self.runtime_store = runtime_store or WatchRuntimeStateStore()
+ self._running = False
+ self._reconcile_task: Optional[asyncio.Task] = None
+ self._active_tasks: dict[str, asyncio.Task] = {}
+ self._active_pids: dict[str, int] = {}
+ self._watch_started_at: dict[str, float] = {}
+
+ def start(self) -> None:
+ if self._running:
+ return
+ self._running = True
+ self._reconcile_task = asyncio.create_task(self._watch_store())
+ self.reconcile_watches()
+
+ async def stop(self) -> None:
+ self._running = False
+ if self._reconcile_task:
+ self._reconcile_task.cancel()
+ try:
+ await self._reconcile_task
+ except asyncio.CancelledError:
+ pass
+ self._reconcile_task = None
+ for task in list(self._active_tasks.values()):
+ task.cancel()
+ if self._active_tasks:
+ await asyncio.gather(*self._active_tasks.values(), return_exceptions=True)
+ self._active_tasks.clear()
+ self._active_pids.clear()
+ self._watch_started_at.clear()
+ self._write_runtime_state()
+
+ async def _watch_store(self) -> None:
+ while self._running:
+ try:
+ if self.store.maybe_reload():
+ self.reconcile_watches()
+ self.reconcile_watches()
+ except asyncio.CancelledError:
+ raise
+ except Exception as exc:
+ logger.error("Managed watch reconcile failed: %s", exc, exc_info=True)
+ await asyncio.sleep(2)
+
+ def reconcile_watches(self) -> None:
+ desired_ids = {watch.id for watch in self.store.list_watches() if watch.enabled}
+ for watch in self.store.list_watches():
+ if not watch.enabled or watch.id in self._active_tasks:
+ continue
+ task = asyncio.create_task(self._run_watch(watch.id))
+ self._active_tasks[watch.id] = task
+ task.add_done_callback(lambda _task, watch_id=watch.id: self._on_watch_done(watch_id))
+
+ for watch_id, task in list(self._active_tasks.items()):
+ if watch_id in desired_ids:
+ continue
+ task.cancel()
+
+ self._write_runtime_state()
+
+ def _on_watch_done(self, watch_id: str) -> None:
+ self._active_tasks.pop(watch_id, None)
+ self._active_pids.pop(watch_id, None)
+ self._watch_started_at.pop(watch_id, None)
+ self._write_runtime_state()
+
+ def _write_runtime_state(self) -> None:
+ payload = {"watches": {}}
+ now = _utc_now_iso()
+ for watch_id, task in self._active_tasks.items():
+ payload["watches"][watch_id] = {
+ "running": not task.done(),
+ "pid": self._active_pids.get(watch_id),
+ "started_at": datetime.fromtimestamp(
+ self._watch_started_at.get(watch_id, 0.0), timezone.utc
+ ).isoformat()
+ if watch_id in self._watch_started_at
+ else None,
+ "updated_at": now,
+ }
+ self.runtime_store.write(payload)
+
+ async def _run_watch(self, watch_id: str) -> None:
+ lifetime_started = asyncio.get_running_loop().time()
+ self._watch_started_at[watch_id] = lifetime_started
+ self._write_runtime_state()
+
+ while self._running:
+ self.store.maybe_reload()
+ watch = self.store.get_watch(watch_id)
+ if watch is None or not watch.enabled:
+ return
+
+ if watch.mode == "forever" and watch.lifetime_timeout_seconds > 0:
+ elapsed = asyncio.get_running_loop().time() - lifetime_started
+ remaining_lifetime = watch.lifetime_timeout_seconds - elapsed
+ if remaining_lifetime <= 0:
+ self._enqueue_hook(
+ watch,
+ prefix="Watch stopped after reaching its lifetime timeout.",
+ body=(
+ f"Watch '{watch.name or watch.id}' reached its lifetime timeout after "
+ f"{int(watch.lifetime_timeout_seconds)} second(s)."
+ ),
+ )
+ self.store.mark_cycle_result(
+ watch.id,
+ exit_code=None,
+ error=None,
+ disable=True,
+ )
+ return
+ cycle_timeout = watch.timeout_seconds
+ if cycle_timeout <= 0:
+ cycle_timeout = remaining_lifetime
+ else:
+ cycle_timeout = min(cycle_timeout, remaining_lifetime)
+ else:
+ cycle_timeout = watch.timeout_seconds
+
+ self.store.mark_cycle_start(watch.id)
+ result = await self._run_cycle(watch, timeout_seconds=cycle_timeout)
+
+ if result.exit_code == 0:
+ prompt = _build_prompt(watch.prefix, result.stdout)
+ if prompt:
+ self._enqueue_hook(watch, prompt=prompt)
+ self.store.mark_cycle_result(
+ watch.id,
+ exit_code=0,
+ error=None,
+ event_detected=True,
+ disable=watch.mode == "once",
+ )
+ if watch.mode != "forever":
+ return
+ continue
+
+ if result.timed_out or result.exit_code == 124:
+ if watch.mode == "forever":
+ self.store.mark_cycle_result(watch.id, exit_code=124, error=None, disable=False)
+ continue
+ self._enqueue_hook(
+ watch,
+ prefix=watch.prefix,
+ body=f"Watch timed out after {int(cycle_timeout)} second(s).",
+ )
+ self.store.mark_cycle_result(watch.id, exit_code=124, error="timed out", disable=True)
+ return
+
+ error_text = _squash_error(result.stderr) or f"watch command exited with status {result.exit_code}"
+ if watch.mode == "forever" and result.exit_code in set(watch.retry_exit_codes):
+ self.store.mark_cycle_result(watch.id, exit_code=result.exit_code, error=error_text, disable=False)
+ await asyncio.sleep(watch.retry_delay_seconds)
+ continue
+
+ self.store.mark_cycle_result(watch.id, exit_code=result.exit_code, error=error_text, disable=True)
+ return
+
+ async def _run_cycle(self, watch: ManagedWatch, *, timeout_seconds: float) -> _CycleResult:
+ if watch.shell_command:
+ process = await asyncio.create_subprocess_shell(
+ watch.shell_command,
+ cwd=watch.cwd or None,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ else:
+ process = await asyncio.create_subprocess_exec(
+ *watch.command,
+ cwd=watch.cwd or None,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ self._active_pids[watch.id] = process.pid
+ self._write_runtime_state()
+ try:
+ if timeout_seconds > 0:
+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout_seconds)
+ else:
+ stdout, stderr = await process.communicate()
+ timed_out = False
+ except asyncio.TimeoutError:
+ process.kill()
+ stdout, stderr = await process.communicate()
+ return _CycleResult(exit_code=124, stdout="", stderr=stderr.decode("utf-8", errors="replace"), timed_out=True)
+ finally:
+ self._active_pids.pop(watch.id, None)
+ self._write_runtime_state()
+
+ return _CycleResult(
+ exit_code=process.returncode or 0,
+ stdout=stdout.decode("utf-8", errors="replace").strip(),
+ stderr=stderr.decode("utf-8", errors="replace").strip(),
+ timed_out=timed_out,
+ )
+
+ def _enqueue_hook(
+ self,
+ watch: ManagedWatch,
+ *,
+ prompt: Optional[str] = None,
+ prefix: Optional[str] = None,
+ body: Optional[str] = None,
+ ) -> None:
+ final_prompt = prompt or _build_prompt(prefix, body)
+ if not final_prompt:
+ return
+ self.request_store.enqueue_hook_send(
+ session_key=watch.session_key,
+ post_to=watch.post_to,
+ deliver_key=watch.deliver_key,
+ prompt=final_prompt,
+ )
+
+
+def _build_prompt(prefix: Optional[str], body: Optional[str]) -> str:
+ parts = []
+ if prefix:
+ parts.append(prefix.strip())
+ if body:
+ body_text = body.strip()
+ if body_text:
+ parts.append(body_text)
+ return "\n\n".join(parts).strip()
+
+
+def _squash_error(text: str, *, limit: int = 240) -> str:
+ compact = " ".join((text or "").split())
+ if len(compact) <= limit:
+ return compact
+ return compact[: limit - 1].rstrip() + "…"
diff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.md
index 66d44042d..935709ff9 100644
--- a/skills/use-vibe-remote/SKILL.md
+++ b/skills/use-vibe-remote/SKILL.md
@@ -1,8 +1,8 @@
---
name: use-vibe-remote
slug: use-vibe-remote
-description: Safely inspect and modify local Vibe Remote configuration, routing, runtime settings, scheduled tasks, and operational state.
-version: 0.1.6
+description: Safely inspect and modify local Vibe Remote configuration, routing, runtime settings, watches, scheduled tasks, and operational state.
+version: 0.1.7
---
# Use Vibe Remote
@@ -15,6 +15,7 @@ Typical requests include:
- route one channel or DM user to OpenCode, Claude, or Codex
- set a working directory for a channel or DM
- choose a backend model, subagent, or reasoning level
+- create, inspect, pause, resume, or remove a managed background watch with `vibe watch`
- create, inspect, run, pause, resume, or remove a scheduled task with `vibe task`
- queue a one-shot asynchronous hook with `vibe hook send`
- show or hide intermediate message types
@@ -44,6 +45,7 @@ Important paths:
- `~/.vibe_remote/config/config.json`: global config
- `~/.vibe_remote/state/settings.json`: per-channel and per-user overrides
- `~/.vibe_remote/state/scheduled_tasks.json`: persisted scheduled tasks
+- `~/.vibe_remote/state/watches.json`: persisted managed watches
- `~/.vibe_remote/state/user_preferences.md`: shared long-term preference file; prefer user-specific notes under `platform/user_id` sections and keep shared rules truly cross-user
- `~/.vibe_remote/state/task_requests/`: queued task-run and hook-send requests plus completion receipts
- `~/.vibe_remote/state/user_preferences.md`: shared long-term preference file; prefer user-specific notes under `platform/user_id` sections and keep shared rules truly cross-user
@@ -51,6 +53,7 @@ Important paths:
- `~/.vibe_remote/logs/vibe_remote.log`: main application log
- `~/.vibe_remote/runtime/status.json`: runtime status file
- `~/.vibe_remote/runtime/doctor.json`: latest doctor result
+- `~/.vibe_remote/runtime/watch_runtime.json`: live watch runtime state, including active PIDs
- `~/.vibe_remote/attachments/`: attachment staging area
## Edit Workflow
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
new file mode 100644
index 000000000..e819691f3
--- /dev/null
+++ b/tests/test_cli_watch_command.py
@@ -0,0 +1,291 @@
+from __future__ import annotations
+
+import io
+import json
+import sys
+from contextlib import redirect_stderr
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.watches import ManagedWatchStore, WatchRuntimeStateStore
+from vibe import cli
+
+
+def _configured_v2(platforms: set[str]):
+ return SimpleNamespace(
+ slack=SimpleNamespace(
+ bot_token="x" if "slack" in platforms else "",
+ app_token="y" if "slack" in platforms else "",
+ ),
+ discord=SimpleNamespace(bot_token="x" if "discord" in platforms else ""),
+ lark=SimpleNamespace(
+ app_id="x" if "lark" in platforms else "",
+ app_secret="y" if "lark" in platforms else "",
+ ),
+ wechat=SimpleNamespace(enable="wechat" in platforms),
+ enabled_platforms=lambda: list(platforms),
+ )
+
+
+def _parse_watch_add(argv: list[str]):
+ parser = cli.build_parser()
+ return parser.parse_args(["watch", "add", *argv])
+
+
+def _capture_stderr_json(func, *args):
+ stderr = io.StringIO()
+ with redirect_stderr(stderr):
+ result = func(*args)
+ return result, json.loads(stderr.getvalue())
+
+
+def test_watch_help_describes_session_key_guidance(capsys) -> None:
+ parser = cli.build_parser()
+
+ with pytest.raises(SystemExit) as exc:
+ parser.parse_args(["watch", "--help"])
+
+ assert exc.value.code == 0
+ captured = capsys.readouterr()
+ assert "managed background watchers" in captured.out
+ assert "vibe watch add --session-key 'slack::channel::C123'" in captured.out
+ assert "{add,list,show,pause,resume,remove}" in captured.out
+
+
+def test_watch_add_help_mentions_shell_and_lifetime_timeout(capsys) -> None:
+ parser = cli.build_parser()
+
+ with pytest.raises(SystemExit) as exc:
+ parser.parse_args(["watch", "add", "--help"])
+
+ assert exc.value.code == 0
+ captured = capsys.readouterr()
+ assert "Pass either --shell '<command>' or a command after '--'." in captured.out
+ assert "--lifetime-timeout" in captured.out
+ assert "vibe watch add --session-key 'slack::channel::C123'" in captured.out
+
+
+def test_watch_add_parser_keeps_top_level_command_name() -> None:
+ args = _parse_watch_add(
+ [
+ "--session-key",
+ "slack::channel::C123",
+ "--",
+ "python3",
+ "wait.py",
+ ]
+ )
+
+ assert args.command == "watch"
+ assert args.watch_command == "add"
+ assert args.waiter_command == ["--", "python3", "wait.py"]
+
+
+def test_watch_add_missing_command_is_structured_json() -> None:
+ args = _parse_watch_add(["--session-key", "slack::channel::C123"])
+
+ with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):
+ result, payload = _capture_stderr_json(cli.cmd_watch_add, args)
+
+ assert result == 1
+ assert payload["code"] == "missing_watch_command"
+ assert payload["help_command"] == "vibe watch add --help"
+
+
+def test_watch_add_rejects_lifetime_timeout_without_forever() -> None:
+ args = _parse_watch_add(
+ [
+ "--session-key",
+ "slack::channel::C123",
+ "--lifetime-timeout",
+ "10",
+ "--shell",
+ "echo done",
+ ]
+ )
+
+ with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):
+ result, payload = _capture_stderr_json(cli.cmd_watch_add, args)
+
+ assert result == 1
+ assert payload["code"] == "invalid_watch_lifetime_timeout"
+
+
+def test_watch_add_rejects_missing_cwd() -> None:
+ args = _parse_watch_add(
+ [
+ "--session-key",
+ "slack::channel::C123",
+ "--cwd",
+ "/tmp/definitely-missing-watch-dir",
+ "--shell",
+ "echo done",
+ ]
+ )
+
+ with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):
+ result, payload = _capture_stderr_json(cli.cmd_watch_add, args)
+
+ assert result == 1
+ assert payload["code"] == "invalid_watch_cwd"
+
+
+def test_watch_add_creates_shell_watch(tmp_path: Path, capsys) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ args = _parse_watch_add(
+ [
+ "--session-key",
+ "slack::channel::C123",
+ "--name",
+ "Wait for export",
+ "--prefix",
+ "Export finished.",
+ "--shell",
+ "python3 scripts/wait.py",
+ ]
+ )
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ result = cli.cmd_watch_add(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["ok"] is True
+ assert payload["watch"]["name"] == "Wait for export"
+ assert payload["watch"]["shell_command"] == "python3 scripts/wait.py"
+ assert payload["watch"]["command"] == []
+ assert payload["watch"]["mode"] == "once"
+
+
+def test_watch_add_creates_exec_watch_with_retry_codes(tmp_path: Path, capsys) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ args = _parse_watch_add(
+ [
+ "--session-key",
+ "slack::channel::C123",
+ "--forever",
+ "--timeout",
+ "600",
+ "--lifetime-timeout",
+ "7200",
+ "--retry-exit-code",
+ "1",
+ "--retry-exit-code",
+ "75",
+ "--",
+ "python3",
+ "scripts/wait.py",
+ "--build",
+ "42",
+ ]
+ )
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ result = cli.cmd_watch_add(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["watch"]["mode"] == "forever"
+ assert payload["watch"]["command"] == ["python3", "scripts/wait.py", "--build", "42"]
+ assert payload["watch"]["retry_exit_codes"] == [1, 75]
+
+
+def test_watch_list_brief_includes_runtime_state(tmp_path: Path, capsys) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = store.add_watch(
+ name="Watch CI",
+ session_key="slack::channel::C123",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="forever",
+ timeout_seconds=600,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[1],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ )
+ runtime_store.write(
+ {
+ "watches": {
+ watch.id: {
+ "running": True,
+ "pid": 1234,
+ "started_at": "2026-04-02T00:00:00+00:00",
+ "updated_at": "2026-04-02T00:00:00+00:00",
+ }
+ }
+ }
+ )
+
+ with (
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ result = cli.cmd_watch_list(brief=True)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["watches"][0]["state"] == "running"
+ assert payload["watches"][0]["mode"] == "forever"
+
+
+def test_watch_show_missing_returns_structured_error() -> None:
+ result, payload = _capture_stderr_json(cli.cmd_watch_show, "missing-watch")
+
+ assert result == 1
+ assert payload["code"] == "watch_not_found"
+
+
+def test_watch_pause_resume_and_remove_update_store(tmp_path: Path, capsys) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = store.add_watch(
+ name="Watch CI",
+ session_key="slack::channel::C123",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix=None,
+ cwd=None,
+ mode="once",
+ timeout_seconds=600,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[1],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ )
+
+ with (
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ ):
+ assert cli.cmd_watch_set_enabled(watch.id, False) == 0
+ paused = json.loads(capsys.readouterr().out)
+ assert paused["watch"]["enabled"] is False
+
+ assert cli.cmd_watch_set_enabled(watch.id, True) == 0
+ resumed = json.loads(capsys.readouterr().out)
+ assert resumed["watch"]["enabled"] is True
+
+ assert cli.cmd_watch_remove(watch.id) == 0
+ removed = json.loads(capsys.readouterr().out)
+ assert removed["removed_id"] == watch.id
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 313bc7a11..60019a103 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -102,15 +102,27 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("## 3. Scheduled tasks and hooks", prompt)
self.assertIn("`vibe task add`", prompt)
self.assertIn("`vibe hook send --session-key ... --prompt ...`", prompt)
+ self.assertIn("`vibe watch add`", prompt)
self.assertIn("Use `vibe task add` for actions that should recur or remain saved.", prompt)
+ self.assertIn(
+ "Use `vibe watch add` when a background waiter should stay managed by Vibe Remote until it emits a follow-up hook.",
+ prompt,
+ )
self.assertIn("Default session key: `slack::channel::C1`", prompt)
self.assertIn("Current thread ID: `171717.123`", prompt)
self.assertIn(
"Use `--post-to channel` when the task or hook should keep thread context but publish to the parent channel.",
prompt,
)
+ self.assertIn(
+ "Use `--timeout <seconds>` on watches for per-cycle timeouts, and `--lifetime-timeout <seconds>` only when a forever watch also needs an overall lifetime cap.",
+ prompt,
+ )
self.assertIn("If `--timezone` is omitted, the task uses the local system timezone at creation time.", prompt)
- self.assertIn("Run `vibe task add --help` or `vibe hook send --help` for the full command reference.", prompt)
+ self.assertIn(
+ "Run `vibe task add --help`, `vibe hook send --help`, or `vibe watch add --help` for the full command reference.",
+ prompt,
+ )
self.assertIn("A shared user context and preferences file is available at ", prompt)
self.assertIn("/tmp/user_preferences.md", prompt)
self.assertIn("From first principles, serving the user better means thinking proactively about how to make full use of the available context", prompt)
diff --git a/tests/test_watches.py b/tests/test_watches.py
new file mode 100644
index 000000000..c6f3bcb11
--- /dev/null
+++ b/tests/test_watches.py
@@ -0,0 +1,131 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.scheduled_tasks import TaskExecutionStore
+from core.watches import ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore
+
+
+def test_managed_watch_store_round_trip(tmp_path: Path) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ watch = store.add_watch(
+ name="Watch CI",
+ session_key="slack::channel::C123",
+ command=["python3", "wait.py"],
+ shell_command=None,
+ prefix="CI finished.",
+ cwd="/tmp",
+ mode="forever",
+ timeout_seconds=600,
+ lifetime_timeout_seconds=3600,
+ retry_exit_codes=[1, 75],
+ retry_delay_seconds=45,
+ post_to="channel",
+ deliver_key=None,
+ )
+
+ payload = json.loads(store.path.read_text(encoding="utf-8"))
+ reloaded = ManagedWatchStore(store.path)
+ saved = reloaded.get_watch(watch.id)
+
+ assert payload["watches"][0]["id"] == watch.id
+ assert saved is not None
+ assert saved.name == "Watch CI"
+ assert saved.mode == "forever"
+ assert saved.retry_exit_codes == [1, 75]
+ assert saved.post_to == "channel"
+
+
+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")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = store.add_watch(
+ name="Wait once",
+ session_key="slack::channel::C123",
+ command=["python3", "-c", "print('waiter output')"],
+ shell_command=None,
+ prefix="The waiter finished.",
+ cwd=None,
+ mode="once",
+ timeout_seconds=5,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[1],
+ retry_delay_seconds=30,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+
+ async def _run() -> None:
+ service.start()
+ for _ in range(100):
+ if watch.id not in service._active_tasks:
+ break
+ await asyncio.sleep(0.05)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ pending = request_store.list_pending()
+ saved = store.get_watch(watch.id)
+
+ assert len(pending) == 1
+ assert pending[0].request_type == "hook_send"
+ assert pending[0].prompt == "The waiter finished.\n\nwaiter output"
+ assert saved is not None
+ assert saved.enabled is False
+ assert saved.last_exit_code == 0
+ assert saved.last_event_at is not None
+
+
+def test_managed_watch_service_forever_timeout_is_silent_per_cycle(tmp_path: Path) -> None:
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ watch = store.add_watch(
+ name="Wait forever",
+ session_key="slack::channel::C123",
+ command=["python3", "-c", "import time; time.sleep(0.2)"],
+ shell_command=None,
+ prefix="Should stay silent.",
+ cwd=None,
+ mode="forever",
+ timeout_seconds=0.05,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[1],
+ retry_delay_seconds=0.01,
+ post_to=None,
+ deliver_key=None,
+ )
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=store,
+ request_store=request_store,
+ runtime_store=runtime_store,
+ )
+
+ async def _run() -> None:
+ service.start()
+ await asyncio.sleep(0.2)
+ await service.stop()
+
+ asyncio.run(_run())
+
+ saved = store.get_watch(watch.id)
+
+ assert request_store.list_pending() == []
+ assert saved is not None
+ assert saved.enabled is True
+ assert saved.last_exit_code == 124
diff --git a/vibe/cli.py b/vibe/cli.py
index 88da7c92b..c9b2fa635 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -2,6 +2,7 @@ import argparse
import json
import logging
import os
+import shlex
import shutil
import signal
import subprocess
@@ -28,6 +29,7 @@ from config.v2_config import (
V2Config,
)
from core.scheduled_tasks import ScheduledTaskStore, TaskExecutionStore, parse_session_key
+from core.watches import ManagedWatchStore, WatchRuntimeStateStore
from vibe import __version__, api, runtime
from vibe.upgrade import build_upgrade_plan, cache_running_vibe_path, get_latest_version_info, get_safe_cwd
@@ -188,6 +190,46 @@ def _hook_send_examples_text() -> str:
)
+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 1 --retry-delay 60 --shell 'bash scripts/wait_for_log_pattern.sh'
+ vibe watch list --brief
+ vibe watch show 12ab34cd56ef
+ vibe watch pause 12ab34cd56ef
+ """
+ )
+
+
+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>
+
+ Guidance:
+ Use a watch when a script should wait in the background and send one hook only after a condition is met.
+ Prefer a threadless session key by default.
+ Only append ::thread::<thread_id> when follow-up must stay inside one specific thread.
+ Use --post-to channel when the watch should keep thread context but publish to the parent channel.
+ Use --deliver-key only when delivery must go to a different explicit target.
+ Pass either --shell '<command>' or a command after '--'.
+ --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 1 --retry-delay 30 -- python3 scripts/wait_for_github_pr_activity.py --repo cyhhao/vibe-remote --pr 153
+ """
+ )
+
+
def _add_hidden_task_alias(task_subparsers, alias: str, parser) -> None:
alias_parser = task_subparsers.add_parser(
alias,
@@ -404,6 +446,20 @@ def _normalize_task_name(value: Optional[str], *, allow_none: bool = True) -> Op
return normalized
+def _normalize_watch_name(value: Optional[str]) -> Optional[str]:
+ if value is None:
+ return None
+ normalized = value.strip()
+ if not normalized:
+ raise TaskCliError(
+ "watch name cannot be empty",
+ code="empty_watch_name",
+ hint="Pass a short non-empty name, or omit --name.",
+ help_command="vibe watch add --help",
+ )
+ return normalized
+
+
def _task_prompt_preview(prompt: str, *, max_chars: int = 72) -> str:
compact = " ".join((prompt or "").split())
if len(compact) <= max_chars:
@@ -530,6 +586,14 @@ def _task_request_store() -> TaskExecutionStore:
return TaskExecutionStore()
+def _watch_store() -> ManagedWatchStore:
+ return ManagedWatchStore()
+
+
+def _watch_runtime_store() -> WatchRuntimeStateStore:
+ return WatchRuntimeStateStore()
+
+
def _supported_task_platforms() -> set[str]:
try:
config = _ensure_config()
@@ -656,6 +720,83 @@ def _collect_target_warnings(*targets) -> list[dict]:
return warnings
+def _resolve_watch_command(args, *, help_command: str) -> tuple[list[str], Optional[str]]:
+ shell_command = (getattr(args, "shell", None) or "").strip()
+ raw_command = list(getattr(args, "waiter_command", []) or [])
+ if raw_command and raw_command[0] == "--":
+ raw_command = raw_command[1:]
+
+ if shell_command and raw_command:
+ raise TaskCliError(
+ "use either --shell or a command after '--', not both",
+ code="conflicting_watch_command_inputs",
+ hint="Pass a shell string with --shell, or pass the executable and its args after '--'.",
+ help_command=help_command,
+ )
+ if shell_command:
+ return [], shell_command
+ if raw_command:
+ return raw_command, None
+ raise TaskCliError(
+ "one of --shell or a command after '--' is required",
+ code="missing_watch_command",
+ hint="Pass a shell command with --shell, or add the watcher executable and its args after '--'.",
+ help_command=help_command,
+ )
+
+
+def _watch_command_preview(watch, *, max_chars: int = 120) -> str:
+ preview = watch.shell_command or shlex.join(watch.command)
+ preview = preview.strip()
+ if len(preview) <= max_chars:
+ return preview
+ return preview[: max_chars - 1].rstrip() + "…"
+
+
+def _watch_display_name(watch) -> str:
+ return watch.name or _watch_command_preview(watch)
+
+
+def _watch_state(watch, runtime_entry: Optional[dict[str, object]]) -> str:
+ if runtime_entry and runtime_entry.get("running"):
+ return "running"
+ if watch.enabled and watch.mode == "forever":
+ return "armed"
+ if watch.enabled:
+ return "pending"
+ if watch.last_error:
+ return "failed"
+ if watch.last_event_at:
+ return "completed"
+ return "paused"
+
+
+def _watch_payload(watch, runtime_entry: Optional[dict[str, object]], *, brief: bool = False) -> dict:
+ derived = {
+ "display_name": _watch_display_name(watch),
+ "command_preview": _watch_command_preview(watch),
+ "state": _watch_state(watch, runtime_entry),
+ "runtime": runtime_entry or {},
+ }
+ if brief:
+ return {
+ "id": watch.id,
+ "name": watch.name,
+ "display_name": derived["display_name"],
+ "state": derived["state"],
+ "mode": watch.mode,
+ "session_key": watch.session_key,
+ "timeout_seconds": watch.timeout_seconds,
+ "lifetime_timeout_seconds": watch.lifetime_timeout_seconds,
+ "enabled": watch.enabled,
+ "last_event_at": watch.last_event_at,
+ "last_error": watch.last_error,
+ }
+ payload = watch.to_dict()
+ payload.update(derived)
+ return payload
+
+
def cmd_task_add(args):
try:
session_target, delivery_target = _validate_delivery_args(
@@ -1049,6 +1190,158 @@ def cmd_hook_send(args):
return 1
+def cmd_watch_add(args):
+ try:
+ session_target, delivery_target = _validate_delivery_args(
+ session_key=args.session_key,
+ post_to=getattr(args, "post_to", None),
+ deliver_key=getattr(args, "deliver_key", None),
+ help_command="vibe watch add --help",
+ )
+ command, shell_command = _resolve_watch_command(args, help_command="vibe watch add --help")
+
+ if args.timeout < 0:
+ raise TaskCliError(
+ "--timeout must be >= 0",
+ code="invalid_watch_timeout",
+ hint="Use 0 for no per-cycle timeout, or a positive number of seconds.",
+ help_command="vibe watch add --help",
+ details={"timeout": args.timeout},
+ )
+ if args.retry_delay < 0:
+ raise TaskCliError(
+ "--retry-delay must be >= 0",
+ code="invalid_watch_retry_delay",
+ hint="Use 0 to retry immediately, or a positive number of seconds.",
+ help_command="vibe watch add --help",
+ details={"retry_delay": args.retry_delay},
+ )
+ if args.lifetime_timeout < 0:
+ raise TaskCliError(
+ "--lifetime-timeout must be >= 0",
+ code="invalid_watch_lifetime_timeout",
+ hint="Use 0 for no overall lifetime limit, or a positive number of seconds.",
+ help_command="vibe watch add --help",
+ details={"lifetime_timeout": args.lifetime_timeout},
+ )
+ if args.lifetime_timeout and not args.forever:
+ raise TaskCliError(
+ "--lifetime-timeout requires --forever",
+ code="invalid_watch_lifetime_timeout",
+ hint="Use --lifetime-timeout only on forever watches.",
+ help_command="vibe watch add --help",
+ )
+ cwd = args.cwd
+ if cwd:
+ resolved = Path(cwd).expanduser()
+ if not resolved.exists() or not resolved.is_dir():
+ raise TaskCliError(
+ f"watch cwd does not exist: {cwd}",
+ code="invalid_watch_cwd",
+ hint="Point --cwd to an existing directory, or omit it to inherit the service working directory.",
+ help_command="vibe watch add --help",
+ details={"cwd": cwd},
+ )
+ cwd = str(resolved)
+
+ retry_exit_codes = sorted(set(args.retry_exit_code or [1]))
+ store = _watch_store()
+ watch = store.add_watch(
+ name=_normalize_watch_name(getattr(args, "name", None)),
+ session_key=args.session_key,
+ command=command,
+ shell_command=shell_command,
+ prefix=_normalize_task_name(getattr(args, "prefix", None)),
+ cwd=cwd,
+ mode="forever" if args.forever else "once",
+ timeout_seconds=float(args.timeout),
+ lifetime_timeout_seconds=float(args.lifetime_timeout),
+ retry_exit_codes=retry_exit_codes,
+ retry_delay_seconds=float(args.retry_delay),
+ post_to=args.post_to,
+ deliver_key=args.deliver_key,
+ )
+ warnings = _collect_target_warnings(session_target, delivery_target)
+ runtime_entry = _watch_runtime_store().load().get("watches", {}).get(watch.id)
+ print(json.dumps({"ok": True, "watch": _watch_payload(watch, runtime_entry), "warnings": warnings}, indent=2))
+ return 0
+ except Exception as exc:
+ _print_task_error(exc, help_command="vibe watch add --help")
+ return 1
+
+
+def cmd_watch_list(*, brief: bool = False):
+ store = _watch_store()
+ runtime_state = _watch_runtime_store().load().get("watches", {})
+ watches = store.list_watches()
+ watches.sort(key=lambda item: (item.enabled is False, item.created_at, item.id))
+ print(
+ json.dumps(
+ {"watches": [_watch_payload(watch, runtime_state.get(watch.id), brief=brief) for watch in watches]},
+ indent=2,
+ )
+ )
+ return 0
+
+
+def cmd_watch_show(watch_id: str):
+ store = _watch_store()
+ watch = store.get_watch(watch_id)
+ if watch is None:
+ _print_task_error(
+ TaskCliError(
+ f"watch '{watch_id}' not found",
+ code="watch_not_found",
+ hint="Use 'vibe watch list' to find a valid watch ID before calling show.",
+ help_command="vibe watch list",
+ details={"watch_id": watch_id},
+ )
+ )
+ return 1
+ runtime_entry = _watch_runtime_store().load().get("watches", {}).get(watch.id)
+ print(json.dumps({"ok": True, "watch": _watch_payload(watch, runtime_entry)}, indent=2))
+ return 0
+
+
+def cmd_watch_set_enabled(watch_id: str, enabled: bool):
+ store = _watch_store()
+ watch = store.get_watch(watch_id)
+ if watch is None:
+ action = "resume" if enabled else "pause"
+ _print_task_error(
+ TaskCliError(
+ f"watch '{watch_id}' not found",
+ code="watch_not_found",
+ hint=f"Use 'vibe watch list' to find a valid watch ID before calling {action}.",
+ help_command="vibe watch list",
+ details={"watch_id": watch_id},
+ )
+ )
+ return 1
+ updated = store.set_enabled(watch_id, enabled)
+ runtime_entry = _watch_runtime_store().load().get("watches", {}).get(updated.id)
+ print(json.dumps({"ok": True, "watch": _watch_payload(updated, runtime_entry)}, indent=2))
+ return 0
+
+
+def cmd_watch_remove(watch_id: str):
+ store = _watch_store()
+ removed = store.remove_watch(watch_id)
+ if not removed:
+ _print_task_error(
+ TaskCliError(
+ f"watch '{watch_id}' not found",
+ code="watch_not_found",
+ hint="Use 'vibe watch list' to find a valid watch ID before calling remove.",
+ help_command="vibe watch list",
+ details={"watch_id": watch_id},
+ )
+ )
+ return 1
+ print(json.dumps({"ok": True, "removed_id": watch_id}, indent=2))
+ return 0
+
+
def _doctor():
"""Run diagnostic checks and return results in UI-compatible format.
@@ -1774,6 +2067,145 @@ def build_parser():
hook_prompt_group = hook_send_parser.add_mutually_exclusive_group(required=True)
hook_prompt_group.add_argument("--prompt", help="Prompt text to send")
hook_prompt_group.add_argument("--prompt-file", help="Read prompt text from a UTF-8 text file")
+
+ watch_parser = subparsers.add_parser(
+ "watch",
+ help="Manage background watches",
+ description="Create, inspect, and control managed background watchers for Vibe Remote.",
+ epilog=_watch_examples_text(),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe watch --help",
+ error_hint="Run one of the watch subcommands below. Use 'vibe watch add --help' for watch creation details.",
+ )
+ watch_subparsers = watch_parser.add_subparsers(
+ dest="watch_command",
+ metavar="{add,list,show,pause,resume,remove}",
+ )
+ watch_subparsers.required = True
+
+ watch_add_parser = watch_subparsers.add_parser(
+ "add",
+ help="Create a managed background watch",
+ description="Create a managed background watch that runs a waiter command and sends a hook when it succeeds.",
+ 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 each successful cycle.",
+ )
+ watch_add_parser.add_argument("--name", help="Optional human-friendly watch name")
+ watch_add_parser.add_argument(
+ "--session-key",
+ required=True,
+ help="Target session key. Prefer a threadless key unless the follow-up must stay in one thread.",
+ )
+ watch_delivery_group = watch_add_parser.add_mutually_exclusive_group()
+ watch_delivery_group.add_argument(
+ "--post-to",
+ choices=("thread", "channel"),
+ help="Delivery location override. Omit to follow --session-key directly.",
+ )
+ watch_delivery_group.add_argument(
+ "--deliver-key",
+ help="Explicit delivery target key. Use this only when messages must be delivered to a different target.",
+ )
+ watch_add_parser.add_argument("--prefix", help="Optional prompt prefix prepended before waiter stdout")
+ watch_add_parser.add_argument("--cwd", help="Working directory for the waiter process")
+ watch_add_parser.add_argument(
+ "--timeout",
+ type=float,
+ default=21600,
+ help="Per-cycle timeout in seconds. Use 0 for no per-cycle timeout. Default: 21600",
+ )
+ watch_add_parser.add_argument(
+ "--forever",
+ action="store_true",
+ help="Keep re-arming the watch after each successful cycle instead of stopping after the first event.",
+ )
+ watch_add_parser.add_argument(
+ "--lifetime-timeout",
+ type=float,
+ default=0,
+ help="Overall forever-watch lifetime timeout in seconds. Use 0 for no lifetime limit. Requires --forever.",
+ )
+ watch_add_parser.add_argument(
+ "--retry-exit-code",
+ dest="retry_exit_code",
+ action="append",
+ type=int,
+ default=None,
+ help="Cycle exit code that should be retried in forever mode. Repeat to add more. Default: 1",
+ )
+ watch_add_parser.add_argument(
+ "--retry-delay",
+ type=float,
+ default=30,
+ help="Delay in seconds before retrying a retryable forever cycle failure. Default: 30",
+ )
+ watch_add_parser.add_argument(
+ "--shell",
+ help="Shell command to run as the waiter. Use this or pass a command after '--'.",
+ )
+ watch_add_parser.add_argument(
+ "waiter_command",
+ nargs=argparse.REMAINDER,
+ help="Waiter command to run after '--'. Example: vibe watch add ... -- python3 script.py --flag value",
+ )
+
+ watch_list_parser = watch_subparsers.add_parser(
+ "list",
+ help="List background watches",
+ description="List stored managed background watches.",
+ epilog="Use the returned watch IDs with 'vibe watch show', 'vibe watch pause', 'vibe watch resume', or 'vibe watch remove'.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe watch list --help",
+ )
+ watch_list_parser.add_argument(
+ "--brief",
+ action="store_true",
+ help="Show a compact watcher-focused view instead of the full stored watch payload",
+ )
+ _add_hidden_task_alias(watch_subparsers, "ls", watch_list_parser)
+
+ watch_show_parser = watch_subparsers.add_parser(
+ "show",
+ help="Show one background watch",
+ description="Show one managed background watch by ID.",
+ epilog="Find watch IDs with: vibe watch list",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe watch show --help",
+ )
+ watch_show_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")
+
+ watch_pause_parser = watch_subparsers.add_parser(
+ "pause",
+ help="Pause one background watch",
+ description="Disable one managed background watch without deleting it.",
+ epilog="Find watch IDs with: vibe watch list",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe watch pause --help",
+ )
+ watch_pause_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")
+
+ watch_resume_parser = watch_subparsers.add_parser(
+ "resume",
+ help="Resume one background watch",
+ description="Re-enable one paused managed background watch.",
+ epilog="Find watch IDs with: vibe watch list",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe watch resume --help",
+ )
+ watch_resume_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")
+
+ watch_remove_parser = watch_subparsers.add_parser(
+ "remove",
+ help="Remove one background watch",
+ description="Delete one managed background watch permanently.",
+ epilog="Find watch IDs with: vibe watch list",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe watch remove --help",
+ )
+ watch_remove_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")
+ _add_hidden_task_alias(watch_subparsers, "rm", watch_remove_parser)
return parser
@@ -1818,4 +2250,18 @@ def main():
if args.hook_command == "send":
sys.exit(cmd_hook_send(args))
parser.error("hook command is required")
+ if args.command == "watch":
+ if args.watch_command == "add":
+ sys.exit(cmd_watch_add(args))
+ if args.watch_command in {"list", "ls"}:
+ sys.exit(cmd_watch_list(brief=getattr(args, "brief", False)))
+ if args.watch_command == "show":
+ sys.exit(cmd_watch_show(args.watch_id))
+ if args.watch_command == "pause":
+ sys.exit(cmd_watch_set_enabled(args.watch_id, False))
+ if args.watch_command == "resume":
+ sys.exit(cmd_watch_set_enabled(args.watch_id, True))
+ if args.watch_command in {"remove", "rm"}:
+ sys.exit(cmd_watch_remove(args.watch_id))
+ parser.error("watch command is required")
sys.exit(cmd_vibe())