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(tasks): add task run and hook send

cyhfa39b0be4590
diff --git a/core/reply_enhancer.py b/core/reply_enhancer.py
index 4757819ea..e5a8c5569 100644
--- a/core/reply_enhancer.py
+++ b/core/reply_enhancer.py
@@ -186,8 +186,10 @@ Rules:
_SCHEDULED_TASKS_PROMPT = """\
-## 3. Scheduled tasks
-You can create scheduled tasks with the `vibe task add` command.
+## 3. Scheduled tasks and hooks
+Use `vibe task add` to store recurring or one-off tasks.
+Use `vibe task run <id>` to trigger an existing task immediately.
+Use `vibe hook send --session-key ... --prompt ...` for one-shot asynchronous sends without storing a task.
Current conversation targeting:
- Default session key: `{session_key}`
@@ -195,14 +197,11 @@ Current conversation targeting:
Rules:
- The default session key intentionally does not include a thread ID.
-- Only append `::thread::<thread_id>` to `--session-key` when the user explicitly wants the scheduled task to keep replying in the current thread.
-- Use `--cron "<expr>"` for recurring tasks or `--at "<ISO-8601>"` for one-off tasks.
+- Only append `::thread::<thread_id>` to `--session-key` when the user explicitly wants replies to stay in the current thread.
+- Use `--cron "<expr>"` for recurring tasks or `--at "<ISO-8601>"` for one-off stored tasks.
- If `--timezone` is omitted, the task uses the local system timezone at creation time.
-- Use `--prompt "..."` or `--prompt-file <path>` to provide the task content.
-
-Examples:
-- Default scope: `vibe task add --session-key '{session_key}' --cron '0 * * * *' --prompt 'Send the hourly update.'`
-- Current thread only when needed: `vibe task add --session-key '{session_key_with_thread}' --cron '0 9 * * *' --prompt 'Post the daily summary in this thread.'`
+- 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.
"""
_VIBE_SKILL_PROMPT = """\
@@ -222,14 +221,9 @@ def _build_scheduled_tasks_prompt(context: MessageContext, *, fallback_platform:
fallback_platform=fallback_platform,
).to_key(include_thread=False)
thread_id = context.thread_id or "(none)"
- if context.thread_id:
- session_key_with_thread = f"{default_key}::thread::{context.thread_id}"
- else:
- session_key_with_thread = f"{default_key}::thread::<thread_id>"
return _SCHEDULED_TASKS_PROMPT.format(
session_key=default_key,
thread_id=thread_id,
- session_key_with_thread=session_key_with_thread,
)
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 8b03487b3..818a40e8f 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -130,6 +130,30 @@ class ScheduledTask:
)
+@dataclass
+class TaskExecutionRequest:
+ id: str
+ request_type: str
+ created_at: str = field(default_factory=_utc_now_iso)
+ task_id: Optional[str] = None
+ session_key: Optional[str] = None
+ prompt: Optional[str] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ return asdict(self)
+
+ @classmethod
+ def from_dict(cls, payload: Dict[str, Any]) -> "TaskExecutionRequest":
+ return cls(
+ id=str(payload.get("id") or uuid4().hex[:12]),
+ request_type=str(payload.get("request_type") or ""),
+ created_at=str(payload.get("created_at") or _utc_now_iso()),
+ task_id=payload.get("task_id"),
+ session_key=payload.get("session_key"),
+ prompt=payload.get("prompt"),
+ )
+
+
class ScheduledTaskStore:
def __init__(self, path: Optional[Path] = None):
self.path = path or (paths.get_state_dir() / "scheduled_tasks.json")
@@ -238,26 +262,148 @@ class ScheduledTaskStore:
self._save()
return task
- def mark_task_result(self, task_id: str, *, error: Optional[str]) -> bool:
+ def mark_task_result(self, task_id: str, *, error: Optional[str], disable_one_shot: bool = True) -> bool:
self.maybe_reload()
task = self._tasks.get(task_id)
if task is None:
return False
task.last_run_at = _utc_now_iso()
task.last_error = error
- if task.schedule_type == "at":
+ if disable_one_shot and task.schedule_type == "at":
task.enabled = False
task.updated_at = _utc_now_iso()
self._save()
return True
+class TaskExecutionStore:
+ def __init__(self, root: Optional[Path] = None):
+ self.root = root or (paths.get_state_dir() / "task_requests")
+ self.pending_dir = self.root / "pending"
+ self.processing_dir = self.root / "processing"
+ self.completed_dir = self.root / "completed"
+ self._ensure_dirs()
+ self.recover_processing()
+
+ def _ensure_dirs(self) -> None:
+ self.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)
+
+ def _request_path(self, request_id: str, *, state: str) -> Path:
+ directory = {
+ "pending": self.pending_dir,
+ "processing": self.processing_dir,
+ "completed": self.completed_dir,
+ }[state]
+ return directory / f"{request_id}.json"
+
+ def recover_processing(self) -> None:
+ self._ensure_dirs()
+ for path in self.processing_dir.glob("*.json"):
+ pending_path = self.pending_dir / path.name
+ if pending_path.exists():
+ path.unlink(missing_ok=True)
+ continue
+ path.replace(pending_path)
+
+ def enqueue(self, request: TaskExecutionRequest) -> TaskExecutionRequest:
+ self._ensure_dirs()
+ path = self._request_path(request.id, state="pending")
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ dir=self.pending_dir,
+ suffix=".tmp",
+ delete=False,
+ encoding="utf-8",
+ ) as handle:
+ json.dump(request.to_dict(), handle, indent=2)
+ tmp_path = Path(handle.name)
+ tmp_path.replace(path)
+ return request
+
+ def enqueue_task_run(self, task_id: str) -> TaskExecutionRequest:
+ return self.enqueue(TaskExecutionRequest(id=uuid4().hex[:12], request_type="task_run", task_id=task_id))
+
+ def enqueue_hook_send(self, *, session_key: str, prompt: str) -> TaskExecutionRequest:
+ return self.enqueue(
+ TaskExecutionRequest(
+ id=uuid4().hex[:12],
+ request_type="hook_send",
+ session_key=session_key,
+ prompt=prompt,
+ )
+ )
+
+ def list_pending(self) -> list[TaskExecutionRequest]:
+ self._ensure_dirs()
+ requests: list[TaskExecutionRequest] = []
+ for path in sorted(self.pending_dir.glob("*.json"), key=lambda item: item.name):
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except Exception as exc:
+ logger.error("Failed to read task request %s: %s", path, exc)
+ continue
+ if not isinstance(payload, dict):
+ continue
+ requests.append(TaskExecutionRequest.from_dict(payload))
+ return requests
+
+ def claim(self, request_id: str) -> Optional[TaskExecutionRequest]:
+ pending_path = self._request_path(request_id, state="pending")
+ processing_path = self._request_path(request_id, state="processing")
+ if not pending_path.exists():
+ return None
+ pending_path.replace(processing_path)
+ payload = json.loads(processing_path.read_text(encoding="utf-8"))
+ return TaskExecutionRequest.from_dict(payload)
+
+ def complete(
+ self,
+ request: TaskExecutionRequest,
+ *,
+ ok: bool,
+ error: Optional[str] = None,
+ task_id: Optional[str] = None,
+ session_key: Optional[str] = None,
+ ) -> None:
+ processing_path = self._request_path(request.id, state="processing")
+ completed_path = self._request_path(request.id, state="completed")
+ payload = request.to_dict()
+ payload.update(
+ {
+ "ok": ok,
+ "error": error,
+ "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,
+ }
+ )
+ with tempfile.NamedTemporaryFile(
+ mode="w",
+ dir=self.completed_dir,
+ suffix=".tmp",
+ delete=False,
+ encoding="utf-8",
+ ) as handle:
+ json.dump(payload, handle, indent=2)
+ tmp_path = Path(handle.name)
+ tmp_path.replace(completed_path)
+ processing_path.unlink(missing_ok=True)
+
+
class ScheduledTaskService:
"""Controller-owned runtime that executes persisted scheduled tasks."""
- def __init__(self, controller, store: Optional[ScheduledTaskStore] = None):
+ def __init__(
+ self,
+ controller,
+ store: Optional[ScheduledTaskStore] = None,
+ request_store: Optional[TaskExecutionStore] = None,
+ ):
self.controller = controller
self.store = store or ScheduledTaskStore()
+ self.request_store = request_store or TaskExecutionStore()
self.scheduler = AsyncIOScheduler(timezone="UTC")
self._reconcile_task: Optional[asyncio.Task] = None
self._job_signatures: Dict[str, tuple[Any, ...]] = {}
@@ -294,6 +440,7 @@ class ScheduledTaskService:
try:
if self.store.maybe_reload():
self.reconcile_jobs()
+ await self._drain_requests()
except asyncio.CancelledError:
raise
except Exception as exc:
@@ -358,24 +505,105 @@ class ScheduledTaskService:
task = self.store.get_task(task_id)
if not task or not task.enabled:
return
+ execution_id = uuid4().hex[:12]
+ error = await self._execute_task(task, execution_id=execution_id, disable_one_shot=True)
+ if error:
+ logger.error("Scheduled task %s failed: %s", task_id, error)
+
+ async def _drain_requests(self) -> None:
+ for pending in self.request_store.list_pending():
+ request = self.request_store.claim(pending.id)
+ if request is None:
+ continue
+ error: Optional[str] = None
+ task_id = request.task_id
+ session_key = request.session_key
+ try:
+ if request.request_type == "task_run":
+ self.store.maybe_reload()
+ task = self.store.get_task(request.task_id or "")
+ if task is None:
+ raise ValueError(f"task '{request.task_id}' not found")
+ task_id = task.id
+ session_key = task.session_key
+ error = 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")
+ error = await self._execute_request(
+ session_key=request.session_key,
+ prompt=request.prompt,
+ execution_id=request.id,
+ trigger_kind="hook",
+ )
+ else:
+ raise ValueError(f"unknown task request type: {request.request_type}")
+ except Exception as exc:
+ error = str(exc)
+ logger.error("Task execution request %s failed: %s", request.id, exc, exc_info=True)
+ finally:
+ self.request_store.complete(
+ request,
+ ok=not error,
+ error=error,
+ task_id=task_id,
+ session_key=session_key,
+ )
+ async def _execute_task(
+ self,
+ task: ScheduledTask,
+ *,
+ execution_id: str,
+ disable_one_shot: bool,
+ ) -> Optional[str]:
error: Optional[str] = None
try:
- target = parse_session_key(task.session_key)
- context = await self._build_context(target, task_id=task.id)
- error = await self.controller.message_handler.handle_scheduled_message(
- context=context,
- message=task.prompt,
- parsed_session_key=target,
+ error = await self._execute_request(
+ session_key=task.session_key,
+ prompt=task.prompt,
+ execution_id=execution_id,
+ task_id=task.id,
+ trigger_kind="scheduled",
)
except Exception as exc:
error = str(exc)
- logger.error("Scheduled task %s failed: %s", task_id, exc, exc_info=True)
+ logger.error("Scheduled task %s failed: %s", task.id, exc, exc_info=True)
finally:
- self.store.mark_task_result(task_id, error=error)
+ self.store.mark_task_result(task.id, error=error, disable_one_shot=disable_one_shot)
self.reconcile_jobs()
+ return error
- async def _build_context(self, target: ParsedSessionKey, *, task_id: str) -> MessageContext:
+ async def _execute_request(
+ self,
+ *,
+ session_key: str,
+ prompt: str,
+ execution_id: str,
+ task_id: Optional[str] = None,
+ trigger_kind: str,
+ ) -> Optional[str]:
+ target = parse_session_key(session_key)
+ context = await self._build_context(
+ target,
+ execution_id=execution_id,
+ task_id=task_id,
+ trigger_kind=trigger_kind,
+ )
+ return await self.controller.message_handler.handle_scheduled_message(
+ context=context,
+ message=prompt,
+ parsed_session_key=target,
+ )
+
+ async def _build_context(
+ self,
+ target: ParsedSessionKey,
+ *,
+ execution_id: str,
+ task_id: Optional[str] = None,
+ trigger_kind: str = "scheduled",
+ ) -> MessageContext:
platform = target.platform
self.validate_platform(platform)
settings_manager = self.controller.platform_settings_managers[platform]
@@ -398,11 +626,25 @@ class ScheduledTaskService:
channel_id=channel_id,
platform=platform,
thread_id=target.thread_id,
- message_id=f"scheduled:{task_id}:{uuid4().hex}",
+ message_id=self._build_message_id(
+ execution_id=execution_id,
+ task_id=task_id,
+ trigger_kind=trigger_kind,
+ ),
platform_specific={
"platform": platform,
"is_dm": target.is_dm,
"turn_source": "scheduled",
"session_key_external": target.to_key(),
+ "task_execution_id": execution_id,
+ "task_trigger_kind": trigger_kind,
},
)
+
+ @staticmethod
+ def _build_message_id(*, execution_id: str, task_id: Optional[str], trigger_kind: str) -> str:
+ if trigger_kind == "hook":
+ return f"hook:{execution_id}"
+ if task_id:
+ return f"scheduled:{task_id}:{execution_id}"
+ return f"scheduled:{execution_id}"
diff --git a/docs/plans/task-run-hook.md b/docs/plans/task-run-hook.md
new file mode 100644
index 000000000..f59ef7315
--- /dev/null
+++ b/docs/plans/task-run-hook.md
@@ -0,0 +1,36 @@
+# Task Run And Hook Send
+
+## Background
+
+Vibe Remote already supports persisted scheduled tasks through `vibe task add`, but it lacks:
+
+- an immediate rerun command for an existing task definition
+- a one-shot asynchronous hook command for scripts and long-running workflows
+
+The service runtime and CLI are separate processes, so these new commands need a lightweight IPC path instead of direct controller access from the CLI.
+
+## Goal
+
+Add two user-facing commands:
+
+- `vibe task run <id>`: queue an immediate execution of an existing stored task
+- `vibe hook send --session-key ... --prompt ...`: queue a one-shot asynchronous turn without storing a task
+
+Keep prompt guidance concise and keep session behavior identical to the current scheduled-turn pipeline.
+
+## Solution
+
+Introduce a small request queue under `~/.vibe_remote/state/task_requests/`:
+
+- CLI commands write JSON requests into `pending/`
+- `ScheduledTaskService` polls and claims requests
+- claimed requests move to `processing/`
+- finished requests write receipts to `completed/`
+
+Both new commands reuse the existing scheduled-turn execution path, so they inherit the same session and IM behavior.
+
+## Notes
+
+- `task run` updates `last_run_at` and `last_error` but does not disable one-shot tasks
+- `hook send` does not persist anything into `scheduled_tasks.json`
+- prompt guidance should mention `task add`, `task run`, and `hook send`, but defer full syntax details to `--help`
diff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.md
index 7850d15c3..5421274fa 100644
--- a/skills/use-vibe-remote/SKILL.md
+++ b/skills/use-vibe-remote/SKILL.md
@@ -2,7 +2,7 @@
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.3
+version: 0.1.4
---
# Use Vibe Remote
@@ -15,7 +15,8 @@ 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 scheduled task with `vibe task`
+- 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
- inspect logs, run doctor, restart services, or explain where Vibe Remote stores its state
- decide whether a requested change belongs in Vibe Remote config or in the host backend's own config
@@ -43,6 +44,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/task_requests/`: queued task-run and hook-send requests plus completion receipts
- `~/.vibe_remote/state/sessions.json`: runtime session state
- `~/.vibe_remote/logs/vibe_remote.log`: main application log
- `~/.vibe_remote/runtime/status.json`: runtime status file
@@ -257,6 +259,7 @@ Do not hand-edit this file during normal operations unless the user explicitly a
- `vibe task add`
- `vibe task list`
- `vibe task show <id>`
+- `vibe task run <id>`
- `vibe task pause <id>`
- `vibe task resume <id>`
- `vibe task remove <id>`
@@ -302,6 +305,8 @@ Preferred CLI shape:
- recurring: `vibe task add --session-key '<key>' --cron '<expr>' --prompt '...'`
- one-off: `vibe task add --session-key '<key>' --at '<ISO-8601>' --prompt '...'`
+- immediate rerun: `vibe task run <id>`
+- one-shot async hook: `vibe hook send --session-key '<key>' --prompt '...'`
Session key format:
@@ -317,6 +322,8 @@ Operational guidance:
- use `vibe task list` before editing or deleting an existing task
- use `vibe task show <id>` to inspect the exact stored schedule and target
+- use `vibe task run <id>` when the user wants to trigger one stored task immediately without changing its schedule
+- use `vibe hook send` when the user wants one asynchronous turn without storing a task definition
- if a scheduled task fails unexpectedly, inspect `last_error` first and then check `~/.vibe_remote/logs/vibe_remote.log`
## Backend Capability Matrix
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index bff947888..4497a1275 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -36,6 +36,11 @@ def _parse_task_add(argv: list[str]):
return parser.parse_args(["task", "add", *argv])
+def _parse_hook_send(argv: list[str]):
+ parser = cli.build_parser()
+ return parser.parse_args(["hook", "send", *argv])
+
+
def _capture_stderr_json(func, *args):
stderr = io.StringIO()
with redirect_stderr(stderr):
@@ -97,7 +102,7 @@ def test_task_help_describes_session_key_guidance(capsys) -> None:
captured = 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 "{add,list,show,pause,resume,remove}" in captured.out
+ assert "{add,list,show,pause,resume,run,remove}" in captured.out
assert "rm (remove)" not in captured.out
assert "\n ls" not in captured.out
@@ -115,6 +120,19 @@ def test_task_add_help_includes_examples_and_threadless_guidance(capsys) -> None
assert "vibe task add --session-key 'slack::channel::C123'" in captured.out
+def test_hook_send_help_includes_examples_and_threadless_guidance(capsys) -> None:
+ parser = cli.build_parser()
+
+ with pytest.raises(SystemExit) as exc:
+ parser.parse_args(["hook", "send", "--help"])
+
+ assert exc.value.code == 0
+ captured = capsys.readouterr()
+ assert "`vibe hook send` queues one asynchronous turn" in captured.out
+ assert "<platform>::channel::<channel_id>" in captured.out
+ assert "vibe hook send --session-key 'slack::channel::C123'" in captured.out
+
+
def test_task_add_parse_error_is_structured_json(capsys) -> None:
parser = cli.build_parser()
@@ -214,6 +232,70 @@ def test_task_show_missing_id_returns_guidance(tmp_path: Path) -> None:
assert payload["help_command"] == "vibe task list"
+def test_task_run_missing_id_returns_guidance(tmp_path: Path) -> None:
+ store_path = tmp_path / "scheduled_tasks.json"
+
+ with patch("vibe.cli._task_store", return_value=cli.ScheduledTaskStore(store_path)):
+ result, payload = _capture_stderr_json(cli.cmd_task_run, "missing")
+
+ assert result == 1
+ assert payload["code"] == "task_not_found"
+ assert payload["help_command"] == "vibe task list"
+
+
+def test_task_run_enqueues_request(tmp_path: Path, capsys) -> None:
+ store_path = tmp_path / "scheduled_tasks.json"
+ request_root = tmp_path / "task_requests"
+ store = cli.ScheduledTaskStore(store_path)
+ task = store.add_task(
+ session_key="slack::channel::C123",
+ prompt="hello",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="Asia/Shanghai",
+ )
+
+ with (
+ patch("vibe.cli._task_store", return_value=store),
+ patch("vibe.cli._task_request_store", return_value=cli.TaskExecutionStore(request_root)),
+ ):
+ result = cli.cmd_task_run(task.id)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["ok"] is True
+ assert payload["task_id"] == task.id
+ assert (request_root / "pending" / f"{payload['execution_id']}.json").exists()
+
+
+def test_hook_send_rejects_invalid_session_key_with_hint() -> None:
+ args = _parse_hook_send(["--session-key", "slack::thread::123", "--prompt", "hello"])
+
+ with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):
+ result, payload = _capture_stderr_json(cli.cmd_hook_send, args)
+
+ assert result == 1
+ assert payload["code"] == "invalid_session_key"
+ assert payload["help_command"] == "vibe hook send --help"
+
+
+def test_hook_send_enqueues_request(tmp_path: Path, capsys) -> None:
+ args = _parse_hook_send(["--session-key", "slack::channel::C123", "--prompt", "hello"])
+ request_root = tmp_path / "task_requests"
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._task_request_store", return_value=cli.TaskExecutionStore(request_root)),
+ ):
+ result = cli.cmd_hook_send(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["ok"] is True
+ assert payload["session_key"] == "slack::channel::C123"
+ assert (request_root / "pending" / f"{payload['execution_id']}.json").exists()
+
+
def test_task_remove_alias_parses_to_remove_command() -> None:
parser = cli.build_parser()
args = parser.parse_args(["task", "remove", "task-123"])
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index eac589fac..4b14989a5 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -78,12 +78,14 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
prompt = build_reply_enhancements_prompt(include_quick_replies=True, context=context)
- self.assertIn("## 3. Scheduled tasks", prompt)
+ self.assertIn("## 3. Scheduled tasks and hooks", prompt)
self.assertIn("`vibe task add`", prompt)
+ self.assertIn("`vibe task run <id>`", prompt)
+ self.assertIn("`vibe hook send --session-key ... --prompt ...`", prompt)
self.assertIn("Default session key: `slack::channel::C1`", prompt)
self.assertIn("Current thread ID: `171717.123`", prompt)
- self.assertIn("slack::channel::C1::thread::171717.123", 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("https://github.com/cyhhao/vibe-remote/raw/master/skills/use-vibe-remote/SKILL.md", prompt)
def test_prompt_uses_fallback_platform_for_unannotated_context(self):
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 752931f68..75cd2fc49 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -11,6 +11,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.scheduled_tasks import (
ScheduledTaskService,
ScheduledTaskStore,
+ TaskExecutionStore,
build_session_key_for_context,
parse_session_key,
)
@@ -161,14 +162,26 @@ def test_build_context_assigns_unique_scheduled_message_ids() -> None:
service = ScheduledTaskService(controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json")))
target = parse_session_key("slack::channel::C123")
- first = asyncio.run(service._build_context(target, task_id="task-1"))
- second = asyncio.run(service._build_context(target, task_id="task-1"))
+ first = asyncio.run(service._build_context(target, execution_id="exec-1", task_id="task-1"))
+ second = asyncio.run(service._build_context(target, execution_id="exec-2", task_id="task-1"))
assert first.message_id.startswith("scheduled:task-1:")
assert second.message_id.startswith("scheduled:task-1:")
assert first.message_id != second.message_id
+def test_build_context_assigns_hook_message_id() -> None:
+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))
+ controller = SimpleNamespace(platform_settings_managers={"slack": settings_manager})
+ service = ScheduledTaskService(controller=controller, store=ScheduledTaskStore(Path("/tmp/nonexistent-scheduled.json")))
+ target = parse_session_key("slack::channel::C123")
+
+ context = asyncio.run(service._build_context(target, execution_id="exec-hook", trigger_kind="hook"))
+
+ assert context.message_id == "hook:exec-hook"
+ assert context.platform_specific["task_trigger_kind"] == "hook"
+
+
def test_run_task_records_scheduled_handler_error(tmp_path: Path) -> None:
path = tmp_path / "scheduled_tasks.json"
store = ScheduledTaskStore(path)
@@ -225,6 +238,89 @@ def test_reconcile_jobs_skips_invalid_tasks_and_keeps_valid_jobs(tmp_path: Path)
assert invalid.id not in service.scheduler.jobs
+def test_request_store_enqueue_claim_and_complete(tmp_path: Path) -> None:
+ store = TaskExecutionStore(tmp_path / "task_requests")
+
+ request = store.enqueue_hook_send(session_key="slack::channel::C123", prompt="hello")
+ pending = store.list_pending()
+ claimed = store.claim(request.id)
+
+ assert [item.id for item in pending] == [request.id]
+ assert claimed is not None
+ assert claimed.request_type == "hook_send"
+
+ store.complete(claimed, ok=True, session_key="slack::channel::C123")
+ completed_path = store.completed_dir / f"{request.id}.json"
+ payload = json.loads(completed_path.read_text(encoding="utf-8"))
+
+ assert payload["ok"] is True
+ assert payload["session_key"] == "slack::channel::C123"
+ assert not (store.processing_dir / f"{request.id}.json").exists()
+
+
+def test_drain_requests_executes_hook_send(tmp_path: Path) -> None:
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ request = request_store.enqueue_hook_send(session_key="slack::channel::C123", prompt="ship it")
+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))
+ calls = []
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ calls.append((context, message, parsed_session_key))
+ return None
+
+ controller = SimpleNamespace(
+ platform_settings_managers={"slack": settings_manager},
+ message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),
+ )
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ asyncio.run(service._drain_requests())
+
+ assert len(calls) == 1
+ context, message, parsed = calls[0]
+ assert message == "ship it"
+ assert parsed.to_key() == "slack::channel::C123"
+ assert context.message_id == f"hook:{request.id}"
+ payload = json.loads((request_store.completed_dir / f"{request.id}.json").read_text(encoding="utf-8"))
+ assert payload["ok"] is True
+
+
+def test_run_task_request_does_not_disable_one_shot(tmp_path: Path) -> None:
+ path = tmp_path / "scheduled_tasks.json"
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ store = ScheduledTaskStore(path)
+ task = store.add_task(
+ session_key="slack::channel::C123",
+ prompt="send digest",
+ schedule_type="at",
+ run_at="2026-03-31T09:00:00+08:00",
+ timezone_name="Asia/Shanghai",
+ )
+ request_store.enqueue_task_run(task.id)
+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ return None
+
+ controller = SimpleNamespace(
+ platform_settings_managers={"slack": settings_manager},
+ message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),
+ )
+ service = ScheduledTaskService(controller=controller, store=store, request_store=request_store)
+
+ asyncio.run(service._drain_requests())
+
+ reloaded = ScheduledTaskStore(path)
+ updated = reloaded.get_task(task.id)
+ assert updated is not None
+ assert updated.enabled is True
+ assert updated.last_run_at is not None
+
+
def test_start_keeps_watcher_alive_after_initial_reconcile_failure(tmp_path: Path) -> None:
store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
controller = SimpleNamespace(platform_settings_managers={})
diff --git a/vibe/cli.py b/vibe/cli.py
index 5149d1e9d..12474df5d 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -25,7 +25,7 @@ from config.v2_config import (
SlackConfig,
V2Config,
)
-from core.scheduled_tasks import ScheduledTaskStore, parse_session_key
+from core.scheduled_tasks import ScheduledTaskStore, TaskExecutionStore, parse_session_key
from vibe import __version__, api, runtime
from vibe.upgrade import build_upgrade_plan, cache_running_vibe_path, get_latest_version_info, get_safe_cwd
@@ -102,6 +102,7 @@ def _task_examples_text() -> str:
"""\
Examples:
vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *' --prompt 'Share the hourly 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 'lark::channel::oc_abc::thread::om_123' --cron '30 9 * * 1-5' --prompt 'Post the daily standup reminder in this thread.'
"""
@@ -131,6 +132,28 @@ def _task_add_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>
+
+ Guidance:
+ `vibe hook send` queues one asynchronous turn without persisting a scheduled task.
+ Prefer a threadless session key by default.
+ Only append ::thread::<thread_id> when the hook must continue in one specific thread.
+
+ Examples:
+ vibe hook send --session-key 'slack::channel::C123' --prompt 'The export finished. Share the summary.'
+ 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.'
+ """
+ )
+
+
def _add_hidden_task_alias(task_subparsers, alias: str, parser) -> None:
alias_parser = task_subparsers.add_parser(
alias,
@@ -275,7 +298,7 @@ def _default_timezone_name() -> str:
return "UTC"
-def _resolve_task_prompt(args) -> str:
+def _resolve_prompt_input(args, *, help_command: str, example_command: str) -> str:
prompt = (getattr(args, "prompt", None) or "").strip()
prompt_file = getattr(args, "prompt_file", None)
if prompt and prompt_file:
@@ -283,7 +306,7 @@ def _resolve_task_prompt(args) -> str:
"use either --prompt or --prompt-file",
code="conflicting_prompt_inputs",
hint="Pass inline text with --prompt or load it from disk with --prompt-file, but not both.",
- help_command="vibe task add --help",
+ help_command=help_command,
)
if prompt:
return prompt
@@ -292,7 +315,7 @@ def _resolve_task_prompt(args) -> str:
"prompt text cannot be empty",
code="empty_prompt",
hint="Provide non-empty text after --prompt, or use --prompt-file with a readable text file.",
- help_command="vibe task add --help",
+ help_command=help_command,
)
if prompt_file:
try:
@@ -302,8 +325,8 @@ def _resolve_task_prompt(args) -> str:
f"failed to read prompt file: {exc}",
code="prompt_file_read_failed",
hint="Use --prompt-file with a readable UTF-8 text file.",
- example="vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *' --prompt-file briefing.md",
- help_command="vibe task add --help",
+ example=f"{example_command} --prompt-file briefing.md",
+ help_command=help_command,
details={"prompt_file": prompt_file},
) from exc
if not content:
@@ -311,8 +334,8 @@ def _resolve_task_prompt(args) -> str:
"prompt file is empty",
code="empty_prompt",
hint="Put the prompt text in the file, or pass it directly with --prompt.",
- example="vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *' --prompt 'Share the hourly summary.'",
- help_command="vibe task add --help",
+ example=f"{example_command} --prompt 'Share the hourly summary.'",
+ help_command=help_command,
details={"prompt_file": prompt_file},
)
return content
@@ -320,7 +343,7 @@ def _resolve_task_prompt(args) -> str:
"one of --prompt or --prompt-file is required",
code="missing_prompt",
hint="Pass inline text with --prompt or load it from disk with --prompt-file.",
- help_command="vibe task add --help",
+ help_command=help_command,
)
@@ -342,6 +365,10 @@ def _task_store() -> ScheduledTaskStore:
return ScheduledTaskStore()
+def _task_request_store() -> TaskExecutionStore:
+ return TaskExecutionStore()
+
+
def _supported_task_platforms() -> set[str]:
try:
config = _ensure_config()
@@ -353,36 +380,49 @@ def _supported_task_platforms() -> set[str]:
return {getattr(config, "platform", "slack")}
-def cmd_task_add(args):
+def _parse_validated_session_key(
+ session_key: str,
+ *,
+ help_command: str,
+) -> object:
try:
- try:
- parsed = parse_session_key(args.session_key)
- except ValueError as exc:
- raise TaskCliError(
- str(exc),
- code="invalid_session_key",
- hint="Use <platform>::<channel|user>::<id>[::thread::<thread_id>]. Prefer a threadless key unless the task must reply in one specific thread.",
- example="slack::channel::C123",
- help_command="vibe task add --help",
- details={"session_key": args.session_key},
- ) from exc
+ parsed = parse_session_key(session_key)
+ except ValueError as exc:
+ raise TaskCliError(
+ str(exc),
+ code="invalid_session_key",
+ hint="Use <platform>::<channel|user>::<id>[::thread::<thread_id>]. Prefer a threadless key unless the command must reply in one specific thread.",
+ example="slack::channel::C123",
+ help_command=help_command,
+ details={"session_key": session_key},
+ ) from exc
+
+ supported_platforms = _supported_task_platforms()
+ if parsed.platform not in supported_platforms:
+ supported_text = ", ".join(sorted(supported_platforms)) or "none"
+ raise TaskCliError(
+ f"unsupported task platform: {parsed.platform}",
+ code="unsupported_platform",
+ hint="Choose a platform that is enabled in Vibe Remote before sending the request.",
+ example="slack::channel::C123",
+ help_command=help_command,
+ details={
+ "requested_platform": parsed.platform,
+ "configured_platforms": sorted(supported_platforms),
+ "configured_platforms_text": supported_text,
+ },
+ )
+ return parsed
- supported_platforms = _supported_task_platforms()
- if parsed.platform not in supported_platforms:
- supported_text = ", ".join(sorted(supported_platforms)) or "none"
- raise TaskCliError(
- f"unsupported task platform: {parsed.platform}",
- code="unsupported_platform",
- hint="Choose a platform that is enabled in Vibe Remote before creating the task.",
- example="slack::channel::C123",
- help_command="vibe task add --help",
- details={
- "requested_platform": parsed.platform,
- "configured_platforms": sorted(supported_platforms),
- "configured_platforms_text": supported_text,
- },
- )
- prompt = _resolve_task_prompt(args)
+
+def cmd_task_add(args):
+ try:
+ _parse_validated_session_key(args.session_key, help_command="vibe task add --help")
+ prompt = _resolve_prompt_input(
+ args,
+ help_command="vibe task add --help",
+ example_command="vibe task add --session-key 'slack::channel::C123' --cron '0 * * * *'",
+ )
timezone_name = args.timezone or _default_timezone_name()
try:
timezone = ZoneInfo(timezone_name)
@@ -504,6 +544,63 @@ def cmd_task_remove(task_id: str):
return 0
+def cmd_task_run(task_id: str):
+ store = _task_store()
+ task = store.get_task(task_id)
+ if task is None:
+ _print_task_error(
+ TaskCliError(
+ f"task '{task_id}' not found",
+ code="task_not_found",
+ hint="Use 'vibe task list' to find a valid task ID before calling run.",
+ help_command="vibe task list",
+ details={"task_id": task_id},
+ )
+ )
+ return 1
+ request = _task_request_store().enqueue_task_run(task.id)
+ print(
+ json.dumps(
+ {
+ "ok": True,
+ "accepted": True,
+ "execution_id": request.id,
+ "request_type": request.request_type,
+ "task_id": task.id,
+ },
+ indent=2,
+ )
+ )
+ return 0
+
+
+def cmd_hook_send(args):
+ try:
+ _parse_validated_session_key(args.session_key, help_command="vibe hook send --help")
+ prompt = _resolve_prompt_input(
+ args,
+ help_command="vibe hook send --help",
+ example_command="vibe hook send --session-key 'slack::channel::C123'",
+ )
+ request = _task_request_store().enqueue_hook_send(session_key=args.session_key, prompt=prompt)
+ print(
+ json.dumps(
+ {
+ "ok": True,
+ "accepted": True,
+ "execution_id": request.id,
+ "request_type": request.request_type,
+ "session_key": args.session_key,
+ },
+ indent=2,
+ )
+ )
+ return 0
+ except Exception as exc:
+ _print_task_error(exc, help_command="vibe hook send --help")
+ return 1
+
+
def _doctor():
"""Run diagnostic checks and return results in UI-compatible format.
@@ -1042,7 +1139,7 @@ def build_parser():
)
task_subparsers = task_parser.add_subparsers(
dest="task_command",
- metavar="{add,list,show,pause,resume,remove}",
+ metavar="{add,list,show,pause,resume,run,remove}",
)
task_subparsers.required = True
@@ -1109,6 +1206,16 @@ def build_parser():
)
task_resume_parser.add_argument("task_id", help="Task ID from 'vibe task list'")
+ task_run_parser = task_subparsers.add_parser(
+ "run",
+ help="Run a scheduled task immediately",
+ description="Queue one immediate execution of an existing scheduled task.",
+ epilog="Find task IDs with: vibe task list",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe task run --help",
+ )
+ task_run_parser.add_argument("task_id", help="Task ID from 'vibe task list'")
+
task_rm_parser = task_subparsers.add_parser(
"remove",
help="Remove a scheduled task",
@@ -1119,6 +1226,34 @@ def build_parser():
)
task_rm_parser.add_argument("task_id", help="Task ID from 'vibe task list'")
_add_hidden_task_alias(task_subparsers, "rm", task_rm_parser)
+
+ hook_parser = subparsers.add_parser(
+ "hook",
+ help="Send one-shot async hooks",
+ description="Queue one-shot asynchronous turns without persisting scheduled tasks.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe hook --help",
+ error_hint="Run 'vibe hook send --help' for the async hook command shape.",
+ )
+ hook_subparsers = hook_parser.add_subparsers(dest="hook_command", metavar="{send}")
+ hook_subparsers.required = True
+ 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.",
+ 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.",
+ )
+ hook_send_parser.add_argument(
+ "--session-key",
+ required=True,
+ help="Target session key. Prefer a threadless key unless the hook must stay in one thread.",
+ )
+ 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")
return parser
@@ -1152,7 +1287,13 @@ def main():
sys.exit(cmd_task_set_enabled(args.task_id, False))
if args.task_command == "resume":
sys.exit(cmd_task_set_enabled(args.task_id, True))
+ if args.task_command == "run":
+ sys.exit(cmd_task_run(args.task_id))
if args.task_command in {"remove", "rm"}:
sys.exit(cmd_task_remove(args.task_id))
parser.error("task command is required")
+ if args.command == "hook":
+ if args.hook_command == "send":
+ sys.exit(cmd_hook_send(args))
+ parser.error("hook command is required")
sys.exit(cmd_vibe())