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(harness): align agent run automation

cyh532a31bc0d85
diff --git a/README.md b/README.md
index c8861e7f3..6324af4e7 100644
--- a/README.md
+++ b/README.md
@@ -91,7 +91,7 @@ Not an agent framework. Not a hosted coding VM. Vibe Remote is the remote-contro
- **Thread = session:** Start five threads, run five isolated jobs, resume later.
- **Web setup, not token archaeology:** Local wizard, dashboard, routing, and health checks.
- **Remote UI when you need it:** `vibe remote` opens your local Web UI through a secure avibe.bot tunnel.
-- **Walk away without losing the loop:** Completion notifications, scheduled tasks, and async hooks keep work moving.
+- **Walk away without losing the loop:** Completion notifications and the Agent Harness keep work moving while you live your life.
---
@@ -192,13 +192,30 @@ When your agent needs input — file selection, confirmation, options — your c
![Interactive Prompts](assets/screenshots/question-en.jpg)
-### Scheduled Tasks & Async Hooks
+---
+
+## Harness
+
+Vibe Remote is still a thin remote-control layer, but it gives agents a real harness: a small set of durable tools they can combine to work on their own timeline.
+
+Think of it like giving your AI colleague a task board, a calendar, and a notification center:
+
+- `vibe agent run` starts one concrete Agent Run. It can be synchronous when you want an answer now, or async when the agent should keep working in the background.
+- `vibe task` saves time-based work: "run this every morning", "remind me tonight", "check this once after lunch".
+- `vibe watch` waits for the world to change: a PR review, CI result, deployment, file, log line, or long-running process.
+- `vibe runs` lets the agent inspect what happened, continue from a run, or cancel work when the situation changes.
+
+The important part is that you do not have to memorize all of that. Agents can learn these primitives and use them as building blocks.
+
+Ask in normal language:
-Ask your agent to schedule work for later, repeat a prompt on a cron, or queue a one-shot async follow-up after a long-running job.
+- "Watch this PR and come back when there is actionable review feedback."
+- "Run this deployment check every weekday morning and post the summary here."
+- "Start a separate investigation session for this incident, but report the conclusion to this channel."
+- "Kick off three background checks and keep track of their run IDs."
+- "If CI fails, summarize the logs; if it passes, tell me whether the PR is mergeable."
-- Persist recurring or one-off prompts with `vibe task`
-- Queue a single async send with `vibe hook send`
-- Keep session context and delivery target separate when needed
+That is the Harness: the agent can leave the current chat turn, wait, return, branch, retry, and keep records without inventing fragile shell scripts or making you poll manually.
---
@@ -300,7 +317,9 @@ vibe status # Check if running
vibe stop # Stop everything
vibe doctor # Diagnose issues
vibe task # Create and manage scheduled tasks
-vibe hook # Queue one-shot async sends
+vibe watch # Manage background waiters
+vibe agent # Manage and run Vibe Agents
+vibe runs # Inspect Agent Run records
```
Detailed references:
diff --git a/README_ZH.md b/README_ZH.md
index d5e3d5dfa..a614f0846 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -91,7 +91,7 @@ Vibe Remote 不是 agent 框架,也不是云端 coding VM。它是你本地编
- **Thread = 会话:** 开 5 个 thread,跑 5 个隔离任务,之后还能接着做。
- **Web 向导,不是手搓 token:** 本地设置向导、仪表盘、路由、健康检查。
- **需要远程 UI 时再打开:** `vibe remote` 通过 avibe.bot 安全 tunnel 访问本地 Web UI。
-- **人走开,循环不断:** 完成通知、定时任务、异步 hook 让任务继续推进。
+- **人走开,循环不断:** 完成通知和 Agent Harness 让任务继续推进。
---
@@ -192,13 +192,30 @@ Agent 需要输入时 — 文件选择、确认、选项 — 聊天 App 弹出
![交互式提示](assets/screenshots/question-zh.jpg)
-### 定时任务与异步 Hook
+---
+
+## Harness
+
+Vibe Remote 仍然是一个很薄的远程控制层,但它给 Agent 配了一套真正能干活的 Harness:几个可以持久化、可检查、可组合的基础工具,让 Agent 不再只能“当前回合马上回答”,而是能按自己的时间线工作。
+
+可以把它想成给 AI 同事配了任务板、日历和通知中心:
+
+- `vibe agent run` 代表一次具体的 Agent Run。需要马上拿结果时同步跑;需要后台继续干时异步跑。
+- `vibe task` 负责时间触发:每天早上跑一次、今晚提醒、午饭后检查一次。
+- `vibe watch` 负责等事情发生:PR review、CI 结果、部署完成、文件出现、日志出现、长进程结束。
+- `vibe runs` 负责查看和管理执行记录:Agent 可以追踪发生了什么,也可以在情况变化时取消或接着处理。
+
+重点是,用户不需要背这些命令。Agent 已经可以学会灵活组合这些基础工具。
+
+你只需要用自然语言说:
-你可以让 Agent 把工作安排到稍后执行、按 cron 周期性触发,或者在长任务结束后异步补发一条消息。
+- “帮我盯着这个 PR,有 actionable review 再回来处理。”
+- “每天工作日上午检查一次部署状态,把摘要发到这里。”
+- “为这个 incident 新开一个调查会话,但结论发到这个频道。”
+- “后台并行跑三个检查,记住每个 run id。”
+- “CI 失败就总结日志,成功就告诉我这个 PR 能不能合并。”
-- 用 `vibe task` 保存周期性或一次性提示
-- 用 `vibe hook send` 队列化一次性的异步发送
-- 需要时可把会话上下文和消息投递目标拆开
+这就是 Harness:Agent 可以离开当前聊天回合,等待、回来、分支、重试、记录状态,而不是靠临时 shell 脚本或者让你手动刷新。
---
@@ -300,7 +317,9 @@ vibe status # 检查运行状态
vibe stop # 停止一切
vibe doctor # 诊断问题
vibe task # 创建和管理定时任务
-vibe hook # 队列化一次性异步发送
+vibe watch # 管理后台等待器
+vibe agent # 管理和运行 Vibe Agent
+vibe runs # 查看 Agent Run 记录
```
详细参考:
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 1b11b0dac..2f16c9151 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -1,8 +1,9 @@
"""Message routing and Agent communication handlers"""
import logging
+import inspect
from datetime import datetime
-from typing import List, Optional, Tuple
+from typing import Any, List, Optional, Tuple
from core.audio_asr import (
AUDIO_SIGNATURE_SAMPLE_BYTES,
@@ -148,13 +149,27 @@ class MessageHandler(BaseHandler):
# hold references to older contexts
self.controller.update_thread_message_id(context)
- requested_vibe_agent = (context.platform_specific or {}).get("vibe_agent_name")
- vibe_agent = self.controller.resolve_vibe_agent_for_context(
- context,
- override_agent_name=requested_vibe_agent,
- required=False,
+ platform_payload = context.platform_specific or {}
+ requested_vibe_agent = platform_payload.get("vibe_agent_name")
+ session_target = platform_payload.get("agent_session_target")
+ if not requested_vibe_agent and isinstance(session_target, dict):
+ requested_vibe_agent = session_target.get("agent_name")
+ resolve_vibe_agent = getattr(self.controller, "resolve_vibe_agent_for_context", None)
+ vibe_agent = (
+ resolve_vibe_agent(
+ context,
+ override_agent_name=requested_vibe_agent,
+ required=False,
+ )
+ if callable(resolve_vibe_agent)
+ else None
)
- agent_name = vibe_agent.backend if vibe_agent else self.controller.resolve_agent_for_context(context)
+ if vibe_agent:
+ agent_name = vibe_agent.backend
+ elif isinstance(session_target, dict) and session_target.get("agent_backend"):
+ agent_name = str(session_target["agent_backend"])
+ else:
+ agent_name = self.controller.resolve_agent_for_context(context)
# Check for routing-based agent to maintain session key consistency
# This ensures session IDs match between MessageHandler and SessionHandler
@@ -280,7 +295,7 @@ class MessageHandler(BaseHandler):
message = self._append_attachment_errors(message, attachment_errors)
- request = AgentRequest(
+ request = self._build_agent_request(
context=context,
message=message,
working_path=working_path,
@@ -333,6 +348,15 @@ class MessageHandler(BaseHandler):
)
return str(e)
+ @staticmethod
+ def _build_agent_request(**kwargs: Any) -> AgentRequest:
+ try:
+ signature = inspect.signature(AgentRequest)
+ except (TypeError, ValueError):
+ return AgentRequest(**kwargs)
+ accepted = {name for name in signature.parameters if name != "self"}
+ return AgentRequest(**{key: value for key, value in kwargs.items() if key in accepted})
+
async def _transcribe_audio_attachments(
self,
context: MessageContext,
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 4d17b4afe..0c0c7afad 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -104,6 +104,10 @@ class ResolvedSessionIdTarget:
agent_backend: str
agent_variant: str
native_session_id: str
+ agent_id: Optional[str] = None
+ agent_name: Optional[str] = None
+ model: Optional[str] = None
+ reasoning_effort: Optional[str] = None
workdir: Optional[str] = None
session_anchor: Optional[str] = None
suppress_delivery: bool = False
@@ -120,8 +124,12 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None
row = conn.execute(
select(
agent_sessions.c.id,
+ agent_sessions.c.agent_id,
+ agent_sessions.c.agent_name,
agent_sessions.c.agent_backend,
agent_sessions.c.agent_variant,
+ agent_sessions.c.model,
+ agent_sessions.c.reasoning_effort,
agent_sessions.c.session_anchor,
agent_sessions.c.workdir,
agent_sessions.c.native_session_id,
@@ -166,6 +174,10 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None
),
agent_backend=str(row["agent_backend"] or ""),
agent_variant=str(row["agent_variant"] or ""),
+ agent_id=row["agent_id"],
+ agent_name=row["agent_name"],
+ model=row["model"],
+ reasoning_effort=row["reasoning_effort"],
native_session_id=str(row["native_session_id"] or ""),
workdir=row["workdir"],
session_anchor=str(row["session_anchor"] or ""),
@@ -266,6 +278,9 @@ class TaskExecutionRequest:
deliver_key: Optional[str] = None
prompt: Optional[str] = None
message: Optional[str] = None
+ source_kind: Optional[str] = None
+ source_actor: Optional[str] = None
+ parent_run_id: Optional[str] = None
agent_name: Optional[str] = None
agent_id: Optional[str] = None
agent_backend: Optional[str] = None
@@ -289,6 +304,9 @@ class TaskExecutionRequest:
deliver_key=payload.get("deliver_key"),
prompt=payload.get("prompt"),
message=payload.get("message") or payload.get("prompt"),
+ source_kind=payload.get("source_kind"),
+ source_actor=payload.get("source_actor"),
+ parent_run_id=payload.get("parent_run_id"),
agent_name=payload.get("agent_name"),
agent_id=payload.get("agent_id"),
agent_backend=payload.get("agent_backend"),
@@ -531,7 +549,7 @@ class TaskExecutionStore:
def enqueue(self, request: TaskExecutionRequest) -> TaskExecutionRequest:
if self._sqlite is not None:
payload = request.to_dict()
- payload["status"] = "pending"
+ payload["status"] = "queued"
payload["updated_at"] = request.created_at
self._sqlite.enqueue_run(payload)
return request
@@ -549,8 +567,69 @@ class TaskExecutionStore:
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_task_run(
+ self,
+ task_id: str,
+ *,
+ source_kind: str = "cli",
+ task: Optional[ScheduledTask] = None,
+ ) -> TaskExecutionRequest:
+ if task is None:
+ return self.enqueue(
+ TaskExecutionRequest(
+ id=uuid4().hex[:12],
+ request_type="scheduled",
+ task_id=task_id,
+ source_kind=source_kind,
+ )
+ )
+ return self.enqueue_definition_run(
+ definition_id=task.id,
+ run_type="scheduled",
+ source_kind=source_kind,
+ session_key=task.session_key,
+ session_id=task.session_id,
+ post_to=task.post_to,
+ deliver_key=task.deliver_key,
+ prompt=task.prompt,
+ agent_name=task.agent_name,
+ session_policy=task.session_policy,
+ )
+
+ def enqueue_definition_run(
+ self,
+ *,
+ definition_id: str,
+ run_type: str,
+ source_kind: str,
+ session_key: str,
+ session_id: Optional[str],
+ post_to: Optional[str],
+ deliver_key: Optional[str],
+ prompt: str,
+ agent_name: Optional[str],
+ session_policy: Optional[str],
+ source_actor: Optional[str] = None,
+ parent_run_id: Optional[str] = None,
+ ) -> TaskExecutionRequest:
+ return self.enqueue(
+ TaskExecutionRequest(
+ id=uuid4().hex[:12],
+ request_type=run_type,
+ task_id=definition_id,
+ session_key=session_key,
+ session_id=session_id,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ prompt=prompt,
+ message=prompt,
+ source_kind=source_kind,
+ source_actor=source_actor,
+ parent_run_id=parent_run_id,
+ agent_name=agent_name,
+ session_policy=session_policy,
+ )
+ )
def enqueue_hook_send(
self,
@@ -562,17 +641,26 @@ class TaskExecutionStore:
deliver_key: Optional[str] = None,
agent_name: Optional[str] = None,
session_policy: Optional[str] = None,
+ run_type: str = "hook_send",
+ definition_id: Optional[str] = None,
+ source_kind: str = "cli",
+ source_actor: Optional[str] = None,
+ parent_run_id: Optional[str] = None,
) -> TaskExecutionRequest:
return self.enqueue(
TaskExecutionRequest(
id=uuid4().hex[:12],
- request_type="hook_send",
+ request_type=run_type,
+ task_id=definition_id,
session_key=session_key,
session_id=session_id,
post_to=post_to,
deliver_key=deliver_key,
prompt=prompt,
message=prompt,
+ source_kind=source_kind,
+ source_actor=source_actor,
+ parent_run_id=parent_run_id,
agent_name=agent_name,
session_policy=session_policy,
)
@@ -592,6 +680,9 @@ class TaskExecutionStore:
session_id: Optional[str] = None,
post_to: Optional[str] = None,
deliver_key: Optional[str] = None,
+ source_kind: str = "cli",
+ source_actor: Optional[str] = None,
+ parent_run_id: Optional[str] = None,
) -> TaskExecutionRequest:
return self.enqueue(
TaskExecutionRequest(
@@ -603,6 +694,9 @@ class TaskExecutionStore:
deliver_key=deliver_key,
prompt=message,
message=message,
+ source_kind=source_kind,
+ source_actor=source_actor,
+ parent_run_id=parent_run_id,
agent_name=agent_name,
agent_id=agent_id,
agent_backend=agent_backend,
@@ -617,7 +711,7 @@ class TaskExecutionStore:
return [
TaskExecutionRequest.from_dict(item)
for item in self._sqlite.list_runs(status="pending")
- if item.get("request_type") in {"task_run", "hook_send", "agent_run"}
+ if item.get("request_type") in {"task_run", "hook_send", "agent_run", "scheduled", "watch", "webhook"}
]
self._ensure_dirs()
requests: list[TaskExecutionRequest] = []
@@ -685,7 +779,7 @@ class TaskExecutionStore:
def requeue(self, request_id: str) -> None:
if self._sqlite is not None:
- self._sqlite.update_run_status(request_id, status="pending", updated_at=_utc_now_iso())
+ self._sqlite.update_run_status(request_id, status="queued", updated_at=_utc_now_iso())
return
processing_path = self._request_path(request_id, state="processing")
pending_path = self._request_path(request_id, state="pending")
@@ -709,7 +803,7 @@ class TaskExecutionStore:
if self._sqlite is not None:
self._sqlite.update_run_status(
request.id,
- status="completed" if ok else "failed",
+ status="succeeded" if ok else "failed",
error=error,
completed_at=_utc_now_iso(),
updated_at=_utc_now_iso(),
@@ -887,84 +981,93 @@ 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)
+ queued = self.request_store.enqueue_task_run(task.id, source_kind="scheduler", task=task)
+ request = self.request_store.claim(queued.id)
+ if request is None:
+ return
+ await self._execute_claimed_request(request)
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
- should_complete = True
- task_id = request.task_id
- session_key = request.session_key
- session_id = request.session_id
- 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
- session_id = task.session_id
- error = await self._execute_task(task, execution_id=request.id, disable_one_shot=False)
- elif request.request_type == "hook_send":
- if not (request.session_id or request.session_key) or not request.prompt:
- raise ValueError("hook request requires session_id or session_key, plus prompt")
- if request.session_policy == "create_per_run":
- session_id = self._reserve_runtime_session(
- agent_name=request.agent_name,
- deliver_key=request.deliver_key,
- )
- session_key = ""
- error = await self._execute_request(
- session_key=session_key,
- session_id=session_id,
- post_to=request.post_to,
- deliver_key=request.deliver_key,
- prompt=request.prompt,
- execution_id=request.id,
- trigger_kind="hook",
+ await self._execute_claimed_request(request)
+
+ async def _execute_claimed_request(self, request: TaskExecutionRequest) -> None:
+ error: Optional[str] = None
+ should_complete = True
+ task_id = request.task_id
+ session_key = request.session_key
+ session_id = request.session_id
+ try:
+ if request.request_type in {"task_run", "scheduled"}:
+ 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
+ session_id = task.session_id
+ error = await self._execute_task(
+ task,
+ execution_id=request.id,
+ disable_one_shot=request.source_kind == "scheduler",
+ )
+ elif request.request_type in {"hook_send", "watch", "webhook"}:
+ if not (request.session_id or request.session_key) or not request.prompt:
+ raise ValueError("hook request requires session_id or session_key, plus prompt")
+ if request.session_policy == "create_per_run":
+ session_id = self._reserve_runtime_session(
agent_name=request.agent_name,
- )
- elif request.request_type == "agent_run":
- if not request.message:
- raise ValueError("agent run requires message")
- if not (request.session_id or request.session_key):
- raise ValueError("agent run currently requires session_id or a resolvable session target")
- error = await self._execute_request(
- session_key=request.session_key,
- session_id=request.session_id,
- post_to=request.post_to,
deliver_key=request.deliver_key,
- prompt=request.message,
- execution_id=request.id,
- trigger_kind="agent_run",
- agent_name=request.agent_name,
- )
- else:
- raise ValueError(f"unknown task request type: {request.request_type}")
- except asyncio.CancelledError:
- self.request_store.requeue(request.id)
- should_complete = False
- raise
- except Exception as exc:
- error = str(exc)
- logger.error("Task execution request %s failed: %s", request.id, exc, exc_info=True)
- finally:
- if should_complete:
- self.request_store.complete(
- request,
- ok=not error,
- error=error,
- task_id=task_id,
- session_key=session_key,
- session_id=session_id,
)
+ session_key = ""
+ error = await self._execute_request(
+ session_key=session_key,
+ session_id=session_id,
+ post_to=request.post_to,
+ deliver_key=request.deliver_key,
+ prompt=request.prompt,
+ execution_id=request.id,
+ task_id=task_id,
+ trigger_kind=request.request_type if request.request_type != "hook_send" else "hook",
+ agent_name=request.agent_name,
+ )
+ elif request.request_type == "agent_run":
+ if not request.message:
+ raise ValueError("agent run requires message")
+ if not (request.session_id or request.session_key):
+ raise ValueError("agent run currently requires session_id or a resolvable session target")
+ error = await self._execute_request(
+ session_key=request.session_key,
+ session_id=request.session_id,
+ post_to=request.post_to,
+ deliver_key=request.deliver_key,
+ prompt=request.message,
+ execution_id=request.id,
+ trigger_kind="agent_run",
+ agent_name=request.agent_name,
+ )
+ else:
+ raise ValueError(f"unknown task request type: {request.request_type}")
+ except asyncio.CancelledError:
+ self.request_store.requeue(request.id)
+ should_complete = False
+ raise
+ except Exception as exc:
+ error = str(exc)
+ logger.error("Task execution request %s failed: %s", request.id, exc, exc_info=True)
+ finally:
+ if should_complete:
+ self.request_store.complete(
+ request,
+ ok=not error,
+ error=error,
+ task_id=task_id,
+ session_key=session_key,
+ session_id=session_id,
+ )
async def _execute_task(
self,
@@ -1133,8 +1236,12 @@ class ScheduledTaskService:
"agent_session_target": (
{
"id": target_info.session_id,
+ "agent_id": target_info.agent_id,
+ "agent_name": target_info.agent_name,
"agent_backend": target_info.agent_backend,
"agent_variant": target_info.agent_variant,
+ "model": target_info.model,
+ "reasoning_effort": target_info.reasoning_effort,
"native_session_id": target_info.native_session_id,
"workdir": target_info.workdir,
"session_anchor": target_info.session_anchor,
@@ -1257,6 +1364,10 @@ class ScheduledTaskService:
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 trigger_kind == "watch":
+ return f"watch:{task_id}:{execution_id}" if task_id else f"watch:{execution_id}"
+ if trigger_kind == "webhook":
+ return f"webhook:{task_id}:{execution_id}" if task_id else f"webhook:{execution_id}"
if trigger_kind == "agent_run":
return f"agent_run:{execution_id}"
if task_id:
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index afbfa2531..3352c8e42 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -18,9 +18,10 @@ from config import paths
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
from storage.migrations import run_migrations
-from storage.models import agents
+from storage.models import agent_sessions, agents, run_definitions, scope_settings, state_meta
DEFAULT_AGENT_NAME = "default"
+DEFAULT_AGENT_META_KEY = "default_agent_name"
SUPPORTED_AGENT_BACKENDS = {"codex", "claude", "opencode"}
_UNSET = object()
@@ -202,6 +203,29 @@ class VibeAgentStore:
result = conn.execute(agents.delete().where(agents.c.normalized_name == normalized))
return bool(result.rowcount)
+ def reference_counts(self, name: str) -> dict[str, int]:
+ normalized = normalize_agent_name(name)
+ agent = self.get(normalized)
+ if agent is None:
+ return {}
+ with self.engine.connect() as conn:
+ scope_count = conn.execute(
+ select(scope_settings.c.scope_id).where(scope_settings.c.agent_name == agent.name)
+ ).fetchall()
+ session_count = conn.execute(
+ select(agent_sessions.c.id).where(agent_sessions.c.agent_name == agent.name)
+ ).fetchall()
+ definition_count = conn.execute(
+ select(run_definitions.c.id)
+ .where(run_definitions.c.agent_name == agent.name)
+ .where(run_definitions.c.deleted_at.is_(None))
+ ).fetchall()
+ return {
+ "scopes": len(scope_count),
+ "sessions": len(session_count),
+ "definitions": len(definition_count),
+ }
+
def import_candidates(self, candidates: Iterable[AgentImportCandidate]) -> AgentImportResult:
imported: list[VibeAgent] = []
skipped: list[dict[str, Any]] = []
@@ -230,14 +254,46 @@ class VibeAgentStore:
def ensure_default_agent(self, *, backend: str = "claude") -> VibeAgent:
existing = self.get(DEFAULT_AGENT_NAME)
if existing:
+ self.set_default_agent_name(existing.name)
return existing
- return self.create(
+ agent = self.create(
name=DEFAULT_AGENT_NAME,
backend=backend,
description="Default Vibe Remote agent.",
source="builtin",
metadata={"builtin": True},
)
+ self.set_default_agent_name(agent.name)
+ return agent
+
+ def get_default_agent_name(self) -> Optional[str]:
+ with self.engine.connect() as conn:
+ value = conn.execute(
+ select(state_meta.c.value_json).where(state_meta.c.key == DEFAULT_AGENT_META_KEY).limit(1)
+ ).scalar_one_or_none()
+ payload = _json_loads(value, None)
+ return str(payload).strip() if payload else None
+
+ def set_default_agent_name(self, name: str) -> None:
+ agent = self.require(name)
+ now = _utc_now_iso()
+ with self.engine.begin() as conn:
+ conn.execute(state_meta.delete().where(state_meta.c.key == DEFAULT_AGENT_META_KEY))
+ conn.execute(
+ state_meta.insert().values(
+ key=DEFAULT_AGENT_META_KEY,
+ value_json=_json_dumps(agent.name),
+ updated_at=now,
+ )
+ )
+
+ def get_default_agent(self) -> Optional[VibeAgent]:
+ name = self.get_default_agent_name()
+ if name:
+ agent = self.get(name)
+ if agent is not None:
+ return agent
+ return self.get(DEFAULT_AGENT_NAME)
@staticmethod
def _from_row(row: Any) -> VibeAgent:
diff --git a/core/watches.py b/core/watches.py
index 63e6e9d29..9c3226d4b 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -52,6 +52,7 @@ class ManagedWatch:
command: list[str] = field(default_factory=list)
shell_command: Optional[str] = None
prefix: Optional[str] = None
+ message: Optional[str] = None
cwd: Optional[str] = None
mode: str = "once"
timeout_seconds: float = 21600.0
@@ -84,6 +85,7 @@ class ManagedWatch:
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,
+ message=(str(payload["message"]).strip() if payload.get("message") 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=_payload_float(payload, "timeout_seconds", 21600.0),
@@ -203,6 +205,7 @@ class ManagedWatchStore:
session_id: Optional[str] = None,
agent_name: Optional[str] = None,
session_policy: Optional[str] = None,
+ message: Optional[str] = None,
) -> ManagedWatch:
watch = ManagedWatch(
id=uuid4().hex[:12],
@@ -214,6 +217,7 @@ class ManagedWatchStore:
command=command,
shell_command=shell_command,
prefix=prefix,
+ message=message or prefix,
cwd=cwd,
mode=mode,
timeout_seconds=timeout_seconds,
@@ -265,6 +269,7 @@ class ManagedWatchStore:
deliver_key: Optional[str],
agent_name: Optional[str] = None,
session_policy: Optional[str] = None,
+ message: Optional[str] = None,
) -> ManagedWatch:
watch = self._watches[watch_id]
watch.name = name
@@ -277,6 +282,7 @@ class ManagedWatchStore:
watch.command = command
watch.shell_command = shell_command
watch.prefix = prefix
+ watch.message = message or prefix
watch.cwd = cwd
watch.mode = mode
watch.timeout_seconds = timeout_seconds
@@ -483,7 +489,7 @@ class ManagedWatchService:
if remaining_lifetime <= 0:
self._enqueue_hook(
watch,
- prefix="Watch stopped after reaching its lifetime timeout.",
+ prefix=watch.message or watch.prefix or "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)."
@@ -518,7 +524,7 @@ class ManagedWatchService:
)
if result.exit_code == 0:
- prompt = _build_prompt(watch.prefix, result.stdout)
+ prompt = _build_prompt(watch.message or watch.prefix, result.stdout)
if prompt:
self._enqueue_hook(watch, prompt=prompt)
self.store.mark_cycle_result(
@@ -617,6 +623,9 @@ class ManagedWatchService:
prompt=final_prompt,
agent_name=watch.agent_name,
session_policy=watch.session_policy,
+ run_type="watch",
+ definition_id=watch.id,
+ source_kind="watch",
)
def _enqueue_failure_hook(self, watch: ManagedWatch, *, exit_code: int, error_text: str) -> None:
@@ -633,7 +642,7 @@ class ManagedWatchService:
f"Review the error below, fix the waiter or its dependencies, then recreate the watch if monitoring should continue.\n"
f"Error: {error_text}"
)
- self._enqueue_hook(watch, prefix=watch.prefix, body=body)
+ self._enqueue_hook(watch, prefix=watch.message or watch.prefix, body=body)
def _build_prompt(prefix: Optional[str], body: Optional[str]) -> str:
diff --git a/docs/CLI.md b/docs/CLI.md
index 26e847918..897d5459c 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -197,19 +197,19 @@ automation should use `vibe agent run`.
Create, update, inspect, pause, resume, or remove a managed background watch. A watch
runs a long-lived waiter command (for example a build or a status poll) and,
-when the command finishes successfully, prepends `--prefix` to the captured
-stdout and delivers it through the chosen session as a follow-up message.
+when the command reaches a reportable state, combines `--message` with the
+captured stdout and creates a follow-up Agent Run through the chosen session.
```bash
vibe watch add \
--session-id sesk8m4q2p7x \
- --prefix 'Test run finished. Summarize the failures and propose next steps.' \
+ --message 'Test run finished. Summarize the failures and propose next steps.' \
-- ./scripts/run_tests.sh
# Alternative: pass the command through a shell with --shell
vibe watch add \
--session-id sesk8m4q2p7x \
- --prefix 'Build done. Summarize.' \
+ --message 'Build done. Summarize.' \
--shell 'make build && ./scripts/post_build.sh'
vibe watch list --brief
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 304a03e24..f2c872c05 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -177,6 +177,40 @@ vibe agent run --async --create-session --deliver-key slack::channel::C999 --age
`vibe hook send` 仅作为 deprecated 兼容入口保留。新的自动化入口应使用
`vibe agent run`。
+### `vibe watch`
+
+创建、查看、更新、暂停、恢复或删除一个被管理的后台 watch。watch 会运行一个
+waiter 命令(例如构建脚本或状态轮询)。当命令进入可报告状态时,Vibe Remote
+会把 `--message` 和 waiter stdout 组合起来,并通过选定 Session 创建一次跟进
+Agent Run。
+
+```bash
+vibe watch add \
+ --session-id sesk8m4q2p7x \
+ --message 'Test run finished. Summarize the failures and propose next steps.' \
+ -- ./scripts/run_tests.sh
+
+# 也可以通过 --shell 传入一整段 shell 命令
+vibe watch add \
+ --session-id sesk8m4q2p7x \
+ --message 'Build done. Summarize.' \
+ --shell 'make build && ./scripts/post_build.sh'
+
+vibe watch list --brief
+vibe watch show <watch-id>
+vibe watch update <watch-id> --name 'Watch deployment' --timeout 1200
+vibe watch pause <watch-id>
+vibe watch resume <watch-id>
+vibe watch remove <watch-id>
+```
+
+waiter 命令放在 `--` 后面;或者通过 `--shell` 传入一整段 shell 字符串。
+完整参数请看 `vibe watch add --help`,包括 `--timeout`、`--lifetime-timeout`、
+`--forever`、`--retry-exit-code`、`--retry-delay`、`--post-to channel`、
+`--deliver-key` 和 `--name`。watch 与 `vibe task`、`vibe agent run` 共用
+`--session-id`、`--post-to` 和 `--deliver-key` 语义。需要可管理、可暂停、可查看的
+后台等待任务时,优先使用 `vibe watch`,不要随手起 `nohup`。
+
### `vibe version`
显示已安装的版本。
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index e34112439..f68de2e58 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -30,7 +30,7 @@ Vibe Remote exposes two command families:
The two families solve different problems:
- in-chat commands control conversations, working directories, session resume, DM binding, and backend auth repair
-- host CLI commands control the local service process, diagnostics, upgrades, scheduled tasks, and async hooks
+- host CLI commands control the local service process, diagnostics, upgrades, and Agent Harness automation
## 2. In-Chat Commands
diff --git a/docs/plans/agent-run-harness.md b/docs/plans/agent-run-harness.md
index 5a1bcb03b..dfbae8c20 100644
--- a/docs/plans/agent-run-harness.md
+++ b/docs/plans/agent-run-harness.md
@@ -609,7 +609,7 @@ task definition columns.
`vibe watch` manages condition trigger definitions.
```bash
-vibe watch add --agent release-reviewer --prefix "CI finished" -- python wait.py
+vibe watch add --agent release-reviewer --message "CI finished" -- python wait.py
```
When the waiter succeeds or reaches a terminal failure, it creates a
diff --git a/docs/plans/agent-run-harness.zh.md b/docs/plans/agent-run-harness.zh.md
index 24b216223..0ec97a09f 100644
--- a/docs/plans/agent-run-harness.zh.md
+++ b/docs/plans/agent-run-harness.zh.md
@@ -579,7 +579,7 @@ schedule 触发时,从 task definition 的一等列复制快照,创建一条
`vibe watch` 管理 condition trigger definitions。
```bash
-vibe watch add --agent release-reviewer --prefix "CI finished" -- python wait.py
+vibe watch add --agent release-reviewer --message "CI finished" -- python wait.py
```
waiter 成功或进入 terminal failure 时,创建一条 `agent_runs` 记录。
diff --git a/docs/plans/distribution-growth.md b/docs/plans/distribution-growth.md
index a1d2b74e2..ebcfa8007 100644
--- a/docs/plans/distribution-growth.md
+++ b/docs/plans/distribution-growth.md
@@ -2,7 +2,7 @@
## Background
-Vibe Remote already has a stronger product experience than a simple bridge: setup wizard, multi-platform routing, session resume, remote Web UI access, scheduled tasks, and async hooks. The public surface does not make those strengths obvious quickly enough, and the current distribution story still reads like a Python package rather than a developer CLI.
+Vibe Remote already has a stronger product experience than a simple bridge: setup wizard, multi-platform routing, session resume, remote Web UI access, and the Agent Harness for scheduled tasks, watches, and async Agent Runs. The public surface does not make those strengths obvious quickly enough, and the current distribution story still reads like a Python package rather than a developer CLI.
## Goal
diff --git a/skills/background-watch-hook/SKILL.md b/skills/background-watch-hook/SKILL.md
index 491aed01e..df9f25a95 100644
--- a/skills/background-watch-hook/SKILL.md
+++ b/skills/background-watch-hook/SKILL.md
@@ -1,8 +1,8 @@
---
name: background-watch-hook
slug: background-watch-hook
-description: Use `vibe watch` to run a background waiter that returns to the same conversation later. Best for reviews, CI, files, logs, and other wait-now-continue-later workflows.
-version: 0.6.1
+description: Use `vibe watch` to run a managed Harness waiter that returns to the same conversation later. Best for reviews, CI, files, logs, and other wait-now-continue-later workflows.
+version: 0.7.0
---
# Background Watch Hook
@@ -26,7 +26,7 @@ Prefer `vibe watch` when the wait should be inspectable, pausable, resumable, or
## Main Tools
- `vibe watch add`
- Main entrypoint. Starts a managed background watch and sends a follow-up hook after the waiter succeeds or reaches a terminal failure.
+ Main entrypoint. Starts a managed background watch and creates a follow-up Agent Run after the waiter succeeds or reaches a terminal failure.
- `vibe watch list`, `vibe watch show`, `vibe watch update`, `vibe watch pause`, `vibe watch resume`, `vibe watch remove`
Use these to inspect and manage the watch after creation.
- `scripts/wait_pr.py`
@@ -37,7 +37,7 @@ Prefer `vibe watch` when the wait should be inspectable, pausable, resumable, or
Use `vibe watch add` first. Most tasks only need:
1. the target Agent Session ID
-2. a short action-oriented prefix
+2. a short action-oriented message
3. a blocking waiter command
Generic shape:
@@ -45,7 +45,7 @@ Generic shape:
```bash
vibe watch add \
--session-id "<session-id>" \
- --prefix "<what the next turn should do>" \
+ --message "<what the next Agent Run should do>" \
--name "<optional label>" \
-- \
<waiter command ...>
@@ -56,14 +56,15 @@ Default behavior:
- returns immediately
- keeps the waiter managed by Vibe Remote
- lets the agent inspect or stop the watch later
-- sends a follow-up after the waiter succeeds or reaches a terminal failure
+- creates a follow-up Agent Run after the waiter succeeds or reaches a terminal failure
Use `--forever` when the same waiter should re-arm after each detected event instead of exiting after one follow-up.
## `vibe watch` Parameters To Remember
- `--session-id`: which Agent Session the follow-up should continue
-- `--prefix`: the instruction text prepended before waiter stdout in the follow-up; when both exist they are joined with a blank line
+- `--message`: the instruction template for the follow-up Agent Run created from waiter output
+- `--prefix`: legacy alias for older watch instructions; prefer `--message` in new watches
- `--name`: optional label for later management
- `--forever`: re-arm after each detected event
- `--timeout`: per-cycle timeout
@@ -99,7 +100,7 @@ Delay:
vibe watch add \
--session-id "sesk8m4q2p7x" \
--name "Delay callback" \
- --prefix "The delayed check completed. Continue from the result below." \
+ --message "The delayed check completed. Continue from the result below." \
-- \
bash -lc 'sleep 120; echo "Timer finished after 120 seconds."'
```
@@ -110,7 +111,7 @@ File appears:
vibe watch add \
--session-id "sesk8m4q2p7x" \
--name "Wait for export file" \
- --prefix "The export file is ready. Inspect it and continue." \
+ --message "The export file is ready. Inspect it and continue." \
-- \
bash -lc 'while [ ! -f /tmp/export.json ]; do sleep 10; done; echo "Detected /tmp/export.json"'
```
@@ -121,7 +122,7 @@ Log match:
vibe watch add \
--session-id "sesk8m4q2p7x" \
--name "Watch app log" \
- --prefix "The expected log pattern appeared. Inspect the event and continue." \
+ --message "The expected log pattern appeared. Inspect the event and continue." \
--forever \
-- \
bash -lc 'tail -Fn0 /tmp/app.log | while read -r line; do case "$line" in *READY*) echo "$line"; break;; esac; done'
@@ -174,7 +175,7 @@ One-shot watch:
vibe watch add \
--session-id "sesk8m4q2p7x" \
--name "Watch PR 151 reviews" \
- --prefix "PR #151 has new review activity. Fetch the latest review state, summarize actionable items, and continue handling them if needed." \
+ --message "PR #151 has new review activity. Fetch the latest review state, summarize actionable items, and continue handling them if needed." \
-- \
uv run --no-project scripts/wait_pr.py \
--repo cyhhao/vibe-remote \
@@ -188,7 +189,7 @@ Catch up on existing activity first:
vibe watch add \
--session-id "sesk8m4q2p7x" \
--name "Catch up PR 151 reviews" \
- --prefix "PR #151 already has review activity. Fetch the latest review state and continue handling it if needed." \
+ --message "PR #151 already has review activity. Fetch the latest review state and continue handling it if needed." \
-- \
uv run --no-project scripts/wait_pr.py \
--repo cyhhao/vibe-remote \
@@ -205,7 +206,7 @@ vibe watch add \
--forever \
--timeout 21600 \
--lifetime-timeout 86400 \
- --prefix "PR #151 has new review activity. Fetch the latest review state, summarize actionable items, and continue handling them if needed." \
+ --message "PR #151 has new review activity. Fetch the latest review state, summarize actionable items, and continue handling them if needed." \
-- \
uv run --no-project scripts/wait_pr.py \
--repo cyhhao/vibe-remote \
@@ -228,7 +229,7 @@ New PRs in a repository:
vibe watch add \
--session-id "sesk8m4q2p7x" \
--name "Watch new PRs" \
- --prefix "The repository has new pull requests. Review the new PRs and continue as needed." \
+ --message "The repository has new pull requests. Review the new PRs and continue as needed." \
-- \
uv run --no-project scripts/wait_pr.py \
--repo cyhhao/vibe-remote \
@@ -249,7 +250,7 @@ GitHub Actions for a pushed commit:
vibe watch add \
--session-id "sesk8m4q2p7x" \
--name "Watch CI" \
- --prefix "GitHub Actions finished. Inspect the result below and continue with the deployment or fix failures." \
+ --message "GitHub Actions finished. Inspect the result below and continue with the deployment or fix failures." \
-- \
uv run --no-project scripts/wait_action.py \
--repo cyhhao/sub2api \
@@ -262,8 +263,8 @@ vibe watch add \
## Practical Advice
-- Keep prefixes action-oriented. Tell the next turn what to do with the waiter result.
-- If this is the first time using `vibe watch add`, read `vibe watch add --help` first; the help text explains both argument syntax and runtime behavior such as how `--prefix` and waiter stdout become the follow-up message.
+- Keep messages action-oriented. Tell the next turn what to do with the waiter result.
+- If this is the first time using `vibe watch add`, read `vibe watch add --help` first; the help text explains both argument syntax and runtime behavior such as how `--message` and waiter stdout become the follow-up Agent Run input.
- Prefer `vibe watch` over ad-hoc detached shells when the wait should survive the current turn cleanly.
- Treat GitHub as just one example waiter, not the main point of the skill.
- If a watch is no longer useful, remove it instead of leaving stale background work behind.
diff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.md
index 6ec9151e9..a75fe977b 100644
--- a/skills/use-vibe-remote/SKILL.md
+++ b/skills/use-vibe-remote/SKILL.md
@@ -20,7 +20,8 @@ Typical requests include:
- pair, start, stop, or inspect Vibe Cloud remote Web UI access
- create, update, 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`
+- run a one-shot Agent job with `vibe agent run`, including async background runs
+- inspect or cancel concrete Agent Run records with `vibe runs`
- check or apply Vibe Remote updates (`vibe check-update`, `vibe upgrade`)
- inspect logs, run doctor, check service status, or explain where Vibe Remote stores state
- decide whether a requested change belongs in Vibe Remote config or in the host backend's own config
@@ -157,7 +158,7 @@ Vibe Remote stores runtime data under `~/.vibe_remote/` by default (or `VIBE_REM
- `~/.vibe_remote/screenshots/` — default output directory for `vibe screenshot`
- `~/.vibe_remote/state/user_preferences.md` — shared long-term preference file (safe to read and update)
-Scheduled tasks and watches are managed through `vibe task` / `vibe watch` (or their API endpoints), not by editing their persistence files. Everything else under `state/` and `runtime/` is internal — treat it as opaque.
+Agent harness state is managed through `vibe agent run`, `vibe task`, `vibe watch`, and `vibe runs` (or their API endpoints), not by editing persistence files. Everything else under `state/` and `runtime/` is internal — treat it as opaque.
## API Endpoint Reference
@@ -747,46 +748,59 @@ For an expiring code:
Do not expose bind codes unless the user explicitly asks for them.
-## Scheduled Tasks and Watches
+## Agent Harness: Runs, Tasks, and Watches
-Use scheduled tasks and watches when the user wants Vibe Remote to inject a prompt later or repeatedly into an existing chat scope, or wait on a background condition before sending a follow-up.
+Use the harness commands when the user wants an agent to leave the current turn and continue later, repeatedly, or in the background. The mental model is:
+
+- `vibe agent run`: run one concrete Agent job now; add `--async` when it should continue in the background
+- `vibe task`: save a time trigger that creates Agent Runs later
+- `vibe watch`: save a condition trigger that waits for a process, file, log, CI, review, or other signal, then creates a follow-up Agent Run
+- `vibe runs`: inspect and cancel concrete run records
+
+Agents should prefer these managed harness commands over ad-hoc detached shells when the work should be inspectable, resumable, or report back to the conversation.
Preferred CLI shape:
-- recurring task: `vibe task add --session-id '<session-id>' --cron '<expr>' --prompt '...'`
-- one-off task: `vibe task add --session-id '<session-id>' --at '<ISO-8601>' --prompt '...'`
+- one-shot direct run: `vibe agent run --agent '<agent-name>' --message '...'`
+- one-shot async run: `vibe agent run --async --session-id '<session-id>' --message '...'`
+- recurring task: `vibe task add --session-id '<session-id>' --cron '<expr>' --message '...'`
+- one-off task: `vibe task add --session-id '<session-id>' --at '<ISO-8601>' --message '...'`
- immediate rerun: `vibe task run <id>`
-- one-shot async hook: `vibe hook send --session-id '<session-id>' --prompt '...'`
-- managed background watch: `vibe watch add --session-id '<session-id>' --prefix '...' -- <cmd>` (or `--shell '<cmd>'` to pass a single shell string)
+- managed background watch: `vibe watch add --session-id '<session-id>' --message '...' -- <cmd>` (or `--shell '<cmd>'` to pass a single shell string)
- update a watch: `vibe watch update <id> --name '...' --timeout 1200`
+- inspect a run: `vibe runs show <run-id>`
+- cancel a run: `vibe runs cancel <run-id>`
-Delivery controls (apply to `vibe task add`, `vibe hook send`, and `vibe watch add`):
+Delivery controls (apply to `vibe agent run --create-session`, `vibe task add`, and `vibe watch add`):
- `session_id` controls which Agent Session Vibe Remote continues using
- when you want to keep the current session, use the current Agent Session ID shown in the prompt
- if the current turn does not expose a usable Agent Session ID, ask the user to retry from an active Vibe Remote session instead of guessing
-- use `--post-to channel` when the task, hook, or watch should keep the same Agent Session but publish to the parent channel
+- use `--post-to channel` when the task or watch should keep the same Agent Session but publish to the parent channel
- use `--deliver-key '<key>'` only when delivery must go to a different explicit target than the continued session
- do not combine `--post-to` and `--deliver-key` in the same command
-- `vibe task add` stores the text from `--prompt` or `--prompt-file` and injects it each time the task runs
-- `vibe hook send` queues the text from `--prompt` or `--prompt-file` once without storing a task
-- `vibe watch add` uses `--prefix` as follow-up instruction text; on a successful cycle Vibe Remote prepends it before waiter stdout, joined with a blank line when both exist
+- `--message` and `--message-file` are the current user-message flags for task, watch, and agent-run commands
+- `vibe task add` stores the message template and creates Agent Runs when the time trigger fires
+- `vibe agent run --async` queues one Agent Run immediately without storing a task definition
+- `vibe watch add` uses `--message` as the instruction template for the Agent Run created after the waiter reaches a reportable state
Legacy compatibility:
- `--session-key` is still accepted for old scripts; do not use it in new examples or instructions unless the user explicitly asks for legacy targeting
+- `--prompt` / `--prompt-file` are deprecated compatibility inputs. Do not use them in new invocations; use `--message` / `--message-file`.
+- `vibe hook send` is deprecated. Do not use it for new one-shot async work; use `vibe agent run --async`.
Operational guidance:
- use `vibe task list` before editing or deleting an existing task; use `vibe watch list` before touching a managed watch
-- if this is the first time using `vibe task add`, `vibe hook send`, or `vibe watch add`, read the matching `--help` output first — watches accept additional flags like `--shell`, `--timeout` (per-cycle), `--lifetime-timeout` (overall), `--forever`, `--retry-exit-code`, and `--retry-delay`
-- use `vibe task update <id>` to keep the same task ID while changing name, schedule, prompt, or target
+- if this is the first time using `vibe task add`, `vibe agent run`, `vibe runs`, or `vibe watch add`, read the matching `--help` output first — watches accept additional flags like `--shell`, `--timeout` (per-cycle), `--lifetime-timeout` (overall), `--forever`, `--retry-exit-code`, and `--retry-delay`
+- use `vibe task update <id>` to keep the same task ID while changing name, schedule, message, agent, or target
- use `vibe watch update <id> ...` when you must rename, retarget, or change the waiter/options
- use `vibe task list --brief` and `vibe watch list --brief` for scheduling-focused summaries
- `vibe task list` hides completed one-shot tasks by default; use `vibe task list --all` when you need full history
-- use `vibe task show <id>` or `vibe watch show <id>` to inspect stored fields and derived runtime state (such as `next_run_at` or `pid`)
+- use `vibe task show <id>`, `vibe watch show <id>`, or `vibe runs show <run-id>` to inspect stored fields and runtime state
- use `vibe task pause` / `vibe task resume` and `vibe watch pause` / `vibe watch resume` to disable a task or watch without deleting it
-- treat `warnings` from task, hook, or watch commands as delivery-risk hints to fix proactively
+- treat `warnings` from task, watch, agent-run, or runs commands as delivery-risk hints to fix proactively
## Backend Capability Matrix
@@ -933,15 +947,16 @@ Scheduled tasks:
- `vibe task add`, `vibe task update`, `vibe task list [--all|--brief]`, `vibe task show <id>`, `vibe task run <id>`, `vibe task pause <id>`, `vibe task resume <id>`, `vibe task remove <id>`
-Async hooks:
+Agent runs:
-- `vibe hook send` — one-shot prompt injection without persisting a task
+- `vibe agent run` — run one Agent job now; add `--async` for one-shot background work
+- `vibe runs list`, `vibe runs show <id>`, `vibe runs cancel <id>` — inspect and manage concrete Agent Run records
Watches:
- `vibe watch add`, `vibe watch update <id>`, `vibe watch list [--brief]`, `vibe watch show <id>`, `vibe watch pause <id>`, `vibe watch resume <id>`, `vibe watch remove <id>`
-For any subcommand, prefer `<command> --help` before composing a new invocation. The delivery flags shared by all three commands are `--session-id`, `--post-to`, and `--deliver-key`. The remaining surface differs: `vibe task add` and `vibe hook send` take `--prompt` / `--prompt-file`; `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; and `vibe watch add` takes its own set (`--prefix`, `--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). Do not copy task or hook flags into a watch invocation, and do not pass `--name` to `vibe hook send`.
+For any subcommand, prefer `<command> --help` before composing a new invocation. The delivery flags shared by harness commands are `--session-id`, `--post-to`, and `--deliver-key`, with command-specific mutual exclusion rules. Use `--message` / `--message-file` for user messages. `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; `vibe agent run` takes `--async`; and `vibe watch add` takes its own waiter options (`--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). Do not copy flags between task, watch, and agent-run commands without checking help.
## Troubleshooting
diff --git a/storage/background.py b/storage/background.py
index e28eec351..e3cef5e21 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -33,6 +33,28 @@ def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
+RUN_STATUS_ALIASES: dict[str, str] = {
+ "pending": "queued",
+ "queued": "queued",
+ "processing": "running",
+ "running": "running",
+ "completed": "succeeded",
+ "succeeded": "succeeded",
+ "failed": "failed",
+ "canceled": "canceled",
+}
+
+
+def normalize_run_status(status: Any) -> str:
+ return RUN_STATUS_ALIASES.get(str(status or "").strip(), str(status or "").strip() or "queued")
+
+
+def _status_query_values(status: str) -> list[str]:
+ normalized = normalize_run_status(status)
+ values = [raw for raw, public in RUN_STATUS_ALIASES.items() if public == normalized]
+ return values or [normalized]
+
+
class SQLiteBackgroundTaskStore:
def __init__(self, db_path: Optional[Path] = None):
self.db_path = db_path or paths.get_sqlite_state_path()
@@ -141,7 +163,7 @@ class SQLiteBackgroundTaskStore:
def list_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:
stmt = select(agent_runs)
if status:
- stmt = stmt.where(agent_runs.c.status == status)
+ stmt = stmt.where(agent_runs.c.status.in_(_status_query_values(status)))
stmt = stmt.order_by(agent_runs.c.created_at, agent_runs.c.id)
with self.engine.connect() as conn:
return [self._run_from_row(row) for row in conn.execute(stmt).mappings()]
@@ -154,20 +176,42 @@ class SQLiteBackgroundTaskStore:
def cancel_run(self, run_id: str, *, requested_at: Optional[str] = None) -> bool:
now = requested_at or _utc_now_iso()
with self.engine.begin() as conn:
+ row = conn.execute(select(agent_runs.c.status).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
+ if not row:
+ return False
+ status = normalize_run_status(row["status"])
+ values: dict[str, Any] = {
+ "cancel_requested": 1,
+ "cancel_requested_at": now,
+ "updated_at": now,
+ }
+ if status == "queued":
+ values["status"] = "canceled"
+ values["completed_at"] = now
result = conn.execute(
update(agent_runs)
.where(agent_runs.c.id == run_id)
- .values(cancel_requested=1, cancel_requested_at=now, updated_at=now)
+ .values(**values)
)
return bool(result.rowcount)
def claim_pending_run(self, run_id: str, *, started_at: str) -> Optional[dict[str, Any]]:
with self.engine.begin() as conn:
+ row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
+ if not row:
+ return None
+ if bool(row["cancel_requested"]) or normalize_run_status(row["status"]) == "canceled":
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(status="canceled", completed_at=started_at, updated_at=started_at)
+ )
+ return None
result = conn.execute(
update(agent_runs)
.where(agent_runs.c.id == run_id)
- .where(agent_runs.c.status == "pending")
- .values(status="processing", started_at=started_at, updated_at=started_at)
+ .where(agent_runs.c.status.in_(_status_query_values("queued")))
+ .values(status="running", started_at=started_at, updated_at=started_at)
)
if not result.rowcount:
return None
@@ -274,8 +318,9 @@ class SQLiteBackgroundTaskStore:
with self.engine.begin() as conn:
conn.execute(
update(agent_runs)
- .where(agent_runs.c.status == "processing")
- .values(status="pending", started_at=None, pid=None)
+ .where(agent_runs.c.status.in_(_status_query_values("running")))
+ .where(agent_runs.c.run_type != "watch_runtime")
+ .values(status="queued", started_at=None, pid=None)
)
def write_watch_runtime(self, payload: dict[str, Any], *, updated_at: str) -> None:
@@ -284,8 +329,8 @@ class SQLiteBackgroundTaskStore:
conn.execute(
update(agent_runs)
.where(agent_runs.c.run_type == "watch_runtime")
- .where(agent_runs.c.status.in_(["running", "pending"]))
- .values(status="completed", completed_at=updated_at, updated_at=updated_at)
+ .where(agent_runs.c.status.in_(_status_query_values("running") + _status_query_values("queued")))
+ .values(status="succeeded", completed_at=updated_at, updated_at=updated_at)
)
for watch_id, runtime_payload in watches.items():
if not isinstance(runtime_payload, dict):
@@ -420,7 +465,7 @@ class SQLiteBackgroundTaskStore:
"id": payload["id"],
"definition_id": payload.get("definition_id") or payload.get("task_id"),
"run_type": payload.get("request_type") or payload.get("run_type") or "hook_send",
- "status": payload.get("status") or "pending",
+ "status": normalize_run_status(payload.get("status")),
"source_kind": payload.get("source_kind"),
"source_actor": payload.get("source_actor"),
"parent_run_id": payload.get("parent_run_id"),
@@ -518,7 +563,7 @@ class SQLiteBackgroundTaskStore:
"id": row["id"],
"request_type": row["run_type"],
"run_type": row["run_type"],
- "status": row["status"],
+ "status": normalize_run_status(row["status"]),
"definition_id": row["definition_id"],
"task_id": row["definition_id"],
"source_kind": row["source_kind"],
@@ -552,7 +597,7 @@ class SQLiteBackgroundTaskStore:
"completed_at": row["completed_at"],
"updated_at": row["updated_at"],
"metadata": _json_loads(row["metadata_json"], {}),
- "ok": None if row["completed_at"] is None else row["status"] == "completed",
+ "ok": None if row["completed_at"] is None else normalize_run_status(row["status"]) == "succeeded",
}
@staticmethod
diff --git a/storage/importer.py b/storage/importer.py
index fc95784f5..47011a930 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -526,7 +526,7 @@ def _import_watches(conn: Connection, source: Path) -> int:
def _import_task_requests(conn: Connection, root: Path) -> int:
count = 0
- for status_dir, status in (("pending", "pending"), ("processing", "pending"), ("completed", "completed")):
+ for status_dir, status in (("pending", "queued"), ("processing", "queued"), ("completed", "succeeded")):
directory = root / status_dir
if not directory.exists():
continue
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index ed121c7f5..3b5dff96b 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -46,6 +46,11 @@ def _parse_agent_run(argv: list[str]):
return parser.parse_args(["agent", "run", *argv])
+def _parse_agent(argv: list[str]):
+ parser = cli.build_parser()
+ return parser.parse_args(["agent", *argv])
+
+
def _capture_stderr_json(func, *args):
stderr = io.StringIO()
with redirect_stderr(stderr):
@@ -134,12 +139,13 @@ def test_hook_send_help_describes_runtime_effects(capsys) -> None:
assert exc.value.code == 0
captured = capsys.readouterr()
- assert "If this is your first time using this command, read this whole help entry before queuing a hook." in captured.out
- assert "`vibe hook send` queues one asynchronous turn without persisting a scheduled task." in captured.out
+ assert "`vibe hook send` is a compatibility entrypoint." in captured.out
+ assert "New automation should use `vibe agent run --async`." in captured.out
+ assert "`vibe hook send` queues one deprecated asynchronous compatibility turn" in captured.out
assert "`--post-to channel` changes where the message is posted, not which session is continued." in captured.out
assert "`--message` and `--message-file` provide the one-shot async user message that will be queued immediately." in captured.out
assert "--session-id" in captured.out
- assert "vibe hook send --session-id sesk8m4q2p7x" in captured.out
+ assert "vibe agent run --async --session-id sesk8m4q2p7x" in captured.out
def test_task_list_help_mentions_completed_one_shots_hidden_by_default(capsys) -> None:
@@ -176,11 +182,11 @@ def test_hook_send_help_includes_examples_and_threadless_guidance(capsys) -> Non
assert exc.value.code == 0
captured = capsys.readouterr()
- assert "`vibe hook send` queues one asynchronous turn" in captured.out
+ assert "`vibe hook send` queues one deprecated asynchronous compatibility turn" in captured.out
assert "--post-to" in captured.out
assert "--deliver-key" in captured.out
assert "--session-id" in captured.out
- assert "vibe hook send --session-id sesk8m4q2p7x" in captured.out
+ assert "vibe agent run --async --session-id sesk8m4q2p7x" in captured.out
def test_task_add_parse_error_is_structured_json(capsys) -> None:
@@ -841,6 +847,91 @@ def test_agent_run_rejects_backend_mismatch_for_existing_session(tmp_path: Path)
assert payload["code"] == "agent_session_backend_mismatch"
+def test_agent_run_existing_session_uses_session_agent_when_agent_omitted(tmp_path: Path, capsys) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ from storage.sessions_service import SQLiteSessionsService
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ session_id = service.reserve_private_agent_session(
+ platform="slack",
+ agent_backend="codex",
+ agent_name="worker",
+ session_anchor="slack_private-agent-test",
+ )
+ finally:
+ service.close()
+ args = _parse_agent_run(["--async", "--session-id", session_id, "--message", "hello"])
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["agent"] == "worker"
+ queued = json.loads((request_store.pending_dir / f"{payload['run_id']}.json").read_text())
+ assert queued["agent_name"] == "worker"
+
+
+def test_agent_run_rejects_async_wait_timeout_combo() -> None:
+ args = _parse_agent_run(["--agent", "worker", "--async", "--wait-timeout", "5", "--message", "hello"])
+
+ result, payload = _capture_stderr_json(cli.cmd_agent_run, args)
+
+ assert result == 1
+ assert payload["code"] == "conflicting_wait_policy"
+
+
+def test_agent_create_accepts_effort_alias(tmp_path: Path, capsys) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ args = _parse_agent(["create", "worker", "--backend", "codex", "--effort", "high"])
+
+ with patch("vibe.cli._agent_store", return_value=agent_store):
+ result = cli.cmd_agent_create(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["agent"]["reasoning_effort"] == "high"
+
+
+def test_agent_import_name_filters_global_candidates(tmp_path: Path, capsys) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ keep = tmp_path / "reviewer.md"
+ skip = tmp_path / "builder.md"
+ keep.write_text("---\nname: reviewer\n---\nReview carefully.", encoding="utf-8")
+ skip.write_text("---\nname: builder\n---\nBuild things.", encoding="utf-8")
+ args = _parse_agent(["import", "--from", "codex", "--name", "reviewer"])
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli.iter_global_agent_files", return_value=[(keep, "codex"), (skip, "codex")]),
+ ):
+ result = cli.cmd_agent_import(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert [agent["name"] for agent in payload["imported"]] == ["reviewer"]
+ assert agent_store.get("builder") is None
+
+
+def test_default_agent_pointer_is_created(tmp_path: Path) -> None:
+ agent_store = cli.VibeAgentStore(tmp_path / "state" / "vibe.sqlite")
+ agent = agent_store.ensure_default_agent(backend="codex")
+
+ assert agent.name == "default"
+ assert agent_store.get_default_agent_name() == "default"
+ assert agent_store.get_default_agent().backend == "codex"
+
+
def test_task_add_rejects_deprecated_prompt_argument() -> None:
args = _parse_task_add(
[
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 65d4c27f9..8d6ecdc6e 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -190,6 +190,34 @@ def test_watch_add_creates_shell_watch(tmp_path: Path, capsys) -> None:
assert payload["watch"]["retry_exit_codes"] == [75]
+def test_watch_add_accepts_message_template(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",
+ "--message",
+ "Summarize the waiter output.",
+ "--shell",
+ "echo done",
+ ]
+ )
+
+ 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),
+ patch("vibe.cli._wait_for_watch_startup", side_effect=lambda *args, **kwargs: _startup_ok(store, runtime_store, args[2])),
+ ):
+ result = cli.cmd_watch_add(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["watch"]["message"] == "Summarize the waiter output."
+ assert payload["watch"]["prefix"] is None
+
+
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")
@@ -658,3 +686,24 @@ def test_watch_update_no_changes_returns_structured_error(tmp_path: Path) -> Non
assert result == 1
assert payload["code"] == "no_watch_changes"
+
+
+def test_watch_add_rejects_deprecated_prompt_argument() -> None:
+ args = _parse_watch_add(
+ [
+ "--session-key",
+ "slack::channel::C123",
+ "--prompt",
+ "hello",
+ "--",
+ "python3",
+ "wait.py",
+ ]
+ )
+
+ 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"] == "deprecated_prompt_argument"
+ assert "--message" in payload["hint"]
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 20bdd7423..258c074df 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -167,7 +167,7 @@ def test_task_execution_store_uses_sqlite_runs_when_root_is_default(tmp_path: Pa
sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
saved = sqlite.get_run(request.id)
assert not (tmp_path / "state" / "task_requests").exists()
- assert saved["status"] == "completed"
+ assert saved["status"] == "succeeded"
assert saved["session_id"] == "sesk8m4q2p7x"
assert saved["session_key"] == "slack::channel::C123"
@@ -194,7 +194,7 @@ def test_sqlite_complete_persists_resolved_run_target(tmp_path: Path) -> None:
saved = sqlite.get_run(request.id)
assert saved is not None
- assert saved["status"] == "completed"
+ assert saved["status"] == "succeeded"
assert saved["task_id"] == "task-1"
assert saved["session_key"] == "slack::channel::C456"
assert saved["session_id"] == "sesk8m4q2p7x"
@@ -217,7 +217,25 @@ def test_sqlite_claim_only_claims_pending_runs_once(tmp_path: Path) -> None:
assert first_claim is not None
assert first_claim.request_type == "hook_send"
assert second_claim is None
- assert sqlite.get_run(request.id)["status"] == "processing"
+ assert sqlite.get_run(request.id)["status"] == "running"
+
+
+def test_sqlite_cancel_pending_run_marks_canceled(tmp_path: Path) -> None:
+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
+ store = TaskExecutionStore(tmp_path / "task_requests")
+ store._sqlite = sqlite
+ request = store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="hello",
+ agent_name="default",
+ )
+
+ assert store.cancel_run(request.id) is True
+
+ saved = sqlite.get_run(request.id)
+ assert saved["status"] == "canceled"
+ assert saved["cancel_requested"] is True
+ assert store.claim(request.id) is None
def test_store_round_trip_persists_task(tmp_path: Path) -> None:
@@ -330,8 +348,8 @@ def test_sqlite_remove_task_soft_deletes_task_but_keeps_runs(tmp_path: Path) ->
sqlite.enqueue_run(
{
"id": "run-1",
- "request_type": "task_run",
- "status": "completed",
+ "request_type": "scheduled",
+ "status": "succeeded",
"task_id": task.id,
"session_id": "sesk8m4q2p7x",
"created_at": "2026-05-15T00:00:00+00:00",
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index a51b43c29..dc1cc5b6e 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -389,7 +389,7 @@ def test_ensure_sqlite_state_imports_background_json(tmp_path: Path) -> None:
("scheduled", "sesk8m4q2p7x", "slack::channel::C123"),
("watch", "sesk8m4q2p7x", "slack::channel::C123"),
]
- assert runs == [("hook_send", "pending", "sesk8m4q2p7x")]
+ assert runs == [("hook_send", "queued", "sesk8m4q2p7x")]
def test_custom_state_paths_do_not_bootstrap_default_home(tmp_path: Path, monkeypatch) -> None:
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index 08dc88fb3..bc7537fd8 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -1167,3 +1167,37 @@ def test_telegram_list_chats_returns_discovered_groups(tmp_path, monkeypatch):
assert [chat["id"] for chat in result["channels"]] == ["-1001"]
assert result["summary"]["visible_count"] == 1
assert result["summary"]["hidden_private_count"] == 1
+
+
+def test_vibe_agent_api_crud_and_settings_catalog(tmp_path, monkeypatch):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))
+
+ created = api.create_vibe_agent(
+ {
+ "name": "reviewer",
+ "backend": "codex",
+ "description": "Review releases",
+ "model": "gpt-5.4",
+ "reasoning_effort": "high",
+ "system_prompt": "Review carefully.",
+ }
+ )
+ default_result = api.set_default_vibe_agent("reviewer")
+ listed = api.get_vibe_agents()
+ settings = api.get_settings("slack")
+ updated = api.update_vibe_agent("reviewer", {"model": "gpt-5.5"})
+
+ assert created["ok"] is True
+ assert default_result["default_agent_name"] == "reviewer"
+ assert [agent["name"] for agent in listed["agents"]] == ["reviewer"]
+ assert settings["agent_catalog"]["default_agent_name"] == "reviewer"
+ assert settings["agent_catalog"]["agents"][0]["backend"] == "codex"
+ assert updated["agent"]["model"] == "gpt-5.5"
+
+
+def test_vibe_agent_api_rejects_backend_update(tmp_path, monkeypatch):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))
+ api.create_vibe_agent({"name": "worker", "backend": "codex"})
+
+ with pytest.raises(ValueError, match="backend is immutable"):
+ api.update_vibe_agent("worker", {"backend": "claude"})
diff --git a/tests/test_ui_server_install.py b/tests/test_ui_server_install.py
index 8787689c9..d24b579bb 100644
--- a/tests/test_ui_server_install.py
+++ b/tests/test_ui_server_install.py
@@ -143,6 +143,40 @@ def test_install_job_fails_when_runtime_refresh_fails(monkeypatch):
assert result["restart"] == {"ok": False, "message": "refresh timeout"}
+def test_vibe_agent_routes_return_structured_client_errors(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))
+ client = app.test_client()
+
+ missing = client.get("/agents/missing")
+ assert missing.status_code == 404
+ assert missing.get_json()["code"] == "agent_not_found"
+
+ headers = csrf_headers(client)
+ created = client.post(
+ "/agents",
+ json={"name": "worker", "backend": "codex"},
+ headers=headers,
+ )
+ assert created.status_code == 200
+
+ duplicate = client.post(
+ "/agents",
+ json={"name": "worker", "backend": "codex"},
+ headers=headers,
+ )
+ assert duplicate.status_code == 409
+ assert duplicate.get_json()["code"] == "agent_already_exists"
+
+ immutable = client.request(
+ "PATCH",
+ "/agents/worker",
+ json={"backend": "claude"},
+ headers=headers,
+ )
+ assert immutable.status_code == 400
+ assert immutable.get_json()["code"] == "invalid_agent_request"
+
+
def test_install_job_dedupes_running_backend(monkeypatch):
calls: list[str] = []
release = threading.Event()
diff --git a/ui/src/components/shared/RoutingConfigPanel.tsx b/ui/src/components/shared/RoutingConfigPanel.tsx
index 93728d568..ec7216e59 100644
--- a/ui/src/components/shared/RoutingConfigPanel.tsx
+++ b/ui/src/components/shared/RoutingConfigPanel.tsx
@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react';
-import { FolderOpen, HelpCircle } from 'lucide-react';
+import { Bot, FolderOpen, HelpCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { Combobox } from '../ui/combobox';
@@ -13,6 +13,7 @@ import { CompactSelect } from '../settings/SettingsPrimitives';
export interface RoutingConfigValue {
custom_cwd: string;
routing: {
+ agent_name?: string | null;
agent_backend: string | null;
opencode_agent?: string | null;
opencode_model?: string | null;
@@ -38,6 +39,14 @@ export interface RoutingConfigPanelProps {
/** Platform key used to derive inherited @mention default (e.g., 'slack', 'discord'). */
inheritsFromKey?: string;
/** Backend lookup data — pass already-loaded values from the parent. */
+ vibeAgents?: {
+ name: string;
+ description?: string | null;
+ backend: string;
+ model?: string | null;
+ reasoning_effort?: string | null;
+ }[];
+ defaultAgentName?: string | null;
opencodeOptions?: any;
claudeAgents?: { id: string; name: string }[];
claudeModels?: string[];
@@ -75,6 +84,8 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
globalConfig,
showRequireMention = true,
inheritsFromKey,
+ vibeAgents = [],
+ defaultAgentName,
opencodeOptions,
claudeAgents = [],
claudeModels = [],
@@ -87,7 +98,10 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
const { t } = useTranslation();
const defaultBackend = globalConfig?.agents?.default_backend || 'opencode';
- const effectiveBackend = value.routing.agent_backend || defaultBackend;
+ const selectedVibeAgent = vibeAgents.find((agent) => agent.name === value.routing.agent_name) || null;
+ const defaultVibeAgent = vibeAgents.find((agent) => agent.name === defaultAgentName) || null;
+ const inheritedVibeAgent = selectedVibeAgent || defaultVibeAgent;
+ const effectiveBackend = inheritedVibeAgent?.backend || value.routing.agent_backend || defaultBackend;
const getOpenCodeReasoningOptions = (modelKey: string) => {
const lookup = opencodeOptions?.reasoning_options || {};
@@ -126,7 +140,7 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
}
};
- // Top row: working dir + backend (+ optional require_mention) — dynamic grid columns
+ // Top row: working dir + Vibe Agent (+ optional require_mention) — dynamic grid columns
const topGridCols = showRequireMention ? 'md:grid-cols-3' : 'md:grid-cols-2';
return (
@@ -154,23 +168,50 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
</div>
</div>
- {/* Backend */}
+ {/* Vibe Agent */}
<div className="space-y-1">
- <label className="text-xs font-medium uppercase text-muted">{t('channelList.backend')}</label>
+ <label className="text-xs font-medium uppercase text-muted">{t('channelList.agent')}</label>
<div className="relative">
<span className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2">
- <BackendIcon backend={effectiveBackend} variant="glyph" size={14} />
+ <Bot size={14} className="text-muted" />
</span>
<CompactSelect
- value={effectiveBackend}
- onChange={(e) => onChange({ routing: { ...value.routing, agent_backend: e.target.value } })}
+ value={value.routing.agent_name || ''}
+ onChange={(e) => {
+ const nextName = e.target.value || null;
+ const nextAgent = vibeAgents.find((agent) => agent.name === nextName) || null;
+ onChange({
+ routing: {
+ ...value.routing,
+ agent_name: nextName,
+ agent_backend: nextAgent?.backend || null,
+ },
+ });
+ }}
className="w-full pl-9 pr-3"
>
- <option value="opencode">OpenCode</option>
- <option value="claude">ClaudeCode</option>
- <option value="codex">Codex</option>
+ <option value="">
+ {defaultVibeAgent ? `${t('common.default')} · ${defaultVibeAgent.name}` : t('common.default')}
+ </option>
+ {vibeAgents.map((agent) => (
+ <option key={agent.name} value={agent.name}>
+ {agent.name}
+ {agent.backend ? ` · ${agent.backend}` : ''}
+ {agent.model ? ` / ${agent.model}` : ''}
+ </option>
+ ))}
</CompactSelect>
</div>
+ {inheritedVibeAgent && (
+ <div className="flex items-center gap-1.5 text-[11px] text-muted">
+ <BackendIcon backend={inheritedVibeAgent.backend} variant="glyph" size={12} />
+ <span className="truncate">
+ {inheritedVibeAgent.backend}
+ {inheritedVibeAgent.model ? ` / ${inheritedVibeAgent.model}` : ''}
+ {inheritedVibeAgent.reasoning_effort ? ` / ${inheritedVibeAgent.reasoning_effort}` : ''}
+ </span>
+ </div>
+ )}
</div>
{/* Require @mention (channels only) */}
@@ -275,8 +316,8 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
</div>
</div>
- {/* Backend-specific settings */}
- {effectiveBackend === 'opencode' && (
+ {/* Legacy backend-specific settings remain for scopes without a Vibe Agent. */}
+ {!inheritedVibeAgent && effectiveBackend === 'opencode' && (
<div className="space-y-3">
<div className="text-xs font-medium uppercase text-muted">{t('channelList.opencodeSettings')}</div>
<div className="grid grid-cols-1 gap-3 rounded-xl border border-border bg-surface/80 p-3 md:grid-cols-3">
@@ -343,7 +384,7 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
</div>
)}
- {effectiveBackend === 'claude' && (
+ {!inheritedVibeAgent && effectiveBackend === 'claude' && (
<div className="space-y-3">
<div className="text-xs font-medium uppercase text-muted">{t('channelList.claudeSettings')}</div>
<div className="grid grid-cols-1 gap-3 rounded-xl border border-border bg-surface/80 p-3 md:grid-cols-3">
@@ -398,7 +439,7 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
</div>
)}
- {effectiveBackend === 'codex' && (
+ {!inheritedVibeAgent && effectiveBackend === 'codex' && (
<div className="space-y-3">
<div className="text-xs font-medium uppercase text-muted">{t('channelList.codexSettings')}</div>
<div className="grid grid-cols-1 gap-3 rounded-xl border border-border bg-surface/80 p-3 md:grid-cols-3">
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index 95ca0553f..847357fe6 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -54,6 +54,7 @@ interface ChannelConfig {
show_message_types: string[];
custom_cwd: string;
routing: {
+ agent_name?: string | null;
agent_backend: string | null;
opencode_agent?: string | null;
opencode_model?: string | null;
@@ -151,6 +152,12 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const [allChannelsByPlatform, setAllChannelsByPlatform] = useState<Record<string, any[]>>({});
const [allConfigsByPlatform, setAllConfigsByPlatform] = useState<Record<string, Record<string, ChannelConfig>>>({});
const [allLoading, setAllLoading] = useState(false);
+ const vibeAgents = config.agent_catalog?.agents || [];
+ const defaultAgentName = config.agent_catalog?.default_agent_name || null;
+ const agentByName = useMemo(
+ () => Object.fromEntries(vibeAgents.map((agent: any) => [agent.name, agent])),
+ [vibeAgents]
+ );
useEffect(() => {
return () => {
@@ -202,6 +209,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
try {
const settings = await api.getSettings(targetPlatform);
if (!cancelled) {
+ setConfig((current: any) => ({ ...current, agent_catalog: settings.agent_catalog || current.agent_catalog }));
setConfigs(settings.channels || {});
}
} catch {
@@ -239,6 +247,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const defaultPlatform = forcedPlatform || getEnabledPlatforms(c).find((p) => platformSupportsChannels(c, p)) || c?.platform || 'slack';
setPagePlatform(defaultPlatform);
api.getSettings(defaultPlatform).then(s => {
+ setConfig((current: any) => ({ ...current, agent_catalog: s.agent_catalog || current.agent_catalog }));
setConfigs(s.channels || {});
if (defaultPlatform === 'discord') {
const allowlist = getDiscordGuildAllowlist(s);
@@ -680,6 +689,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
show_message_types: ['assistant'],
custom_cwd: '',
routing: {
+ agent_name: null,
agent_backend: null,
opencode_agent: null,
opencode_model: null,
@@ -1273,7 +1283,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
};
const rowKey = `${channelPlatform}::${channel.id}`;
const expanded = expandedChannelId === rowKey;
- const effectiveBackend = channelConfig.routing.agent_backend || defaultBackend;
+ const selectedAgent = agentByName[channelConfig.routing.agent_name || ''] || agentByName[defaultAgentName || ''];
+ const effectiveBackend = selectedAgent?.backend || channelConfig.routing.agent_backend || defaultBackend;
const effectiveCwd = channelConfig.custom_cwd || config.runtime?.default_cwd || '~/work';
const opencodeOptions = opencodeOptionsByCwd[effectiveCwd];
const claudeAgents = claudeAgentsByCwd[effectiveCwd] || [];
@@ -1288,6 +1299,9 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
: effectiveBackend === 'codex'
? channelConfig.routing.codex_model
: channelConfig.routing.opencode_model;
+ const agentSummary = selectedAgent
+ ? `${selectedAgent.name}${selectedAgent.model ? ` / ${selectedAgent.model}` : ''}`
+ : `${effectiveBackend === 'claude' ? 'Claude' : effectiveBackend === 'codex' ? 'Codex' : 'OpenCode'}${backendModel ? ` / ${backendModel}` : ''}`;
return (
<div
@@ -1336,7 +1350,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
</span>
<span className="block truncate text-[11px] text-muted">
{channelEnabled
- ? `${effectiveBackend === 'claude' ? 'Claude' : effectiveBackend === 'codex' ? 'Codex' : 'OpenCode'}${backendModel ? ` / ${backendModel}` : ''} · ID: ${channel.id}`
+ ? `${agentSummary} · ID: ${channel.id}`
: `ID: ${channel.id}`}
</span>
</span>
@@ -1374,6 +1388,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
onChange={(patch) => updateRow(patch)}
onBrowseDirectory={() => setBrowsingCwdFor(rowKey)}
globalConfig={config}
+ vibeAgents={vibeAgents}
+ defaultAgentName={defaultAgentName}
showRequireMention={true}
inheritsFromKey={channelPlatform}
opencodeOptions={opencodeOptions}
@@ -1739,6 +1755,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
onChange={(patch) => updateConfig(channel.id, patch)}
onBrowseDirectory={() => setBrowsingCwdFor(channel.id)}
globalConfig={config}
+ vibeAgents={vibeAgents}
+ defaultAgentName={defaultAgentName}
showRequireMention={true}
inheritsFromKey={platform}
opencodeOptions={opencodeOptions}
diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsx
index db75404b5..d0624986b 100644
--- a/ui/src/components/steps/UserList.tsx
+++ b/ui/src/components/steps/UserList.tsx
@@ -32,6 +32,7 @@ interface UserConfig {
show_message_types: string[];
custom_cwd: string;
routing: {
+ agent_name?: string | null;
agent_backend: string | null;
opencode_agent?: string | null;
opencode_model?: string | null;
@@ -460,9 +461,22 @@ export const UserList: React.FC = () => {
const [refreshTrigger, setRefreshTrigger] = useState(0);
const enabledPlatforms = useMemo(() => getEnabledPlatforms(config), [config]);
+ const vibeAgents = config.agent_catalog?.agents || [];
+ const defaultAgentName = config.agent_catalog?.default_agent_name || null;
+ const agentByName = useMemo(
+ () => Object.fromEntries(vibeAgents.map((agent: any) => [agent.name, agent])),
+ [vibeAgents]
+ );
useEffect(() => {
- api.getConfig().then((loadedConfig) => setConfig(loadedConfig));
+ api.getConfig().then(async (loadedConfig) => {
+ try {
+ const settings = await api.getSettings(loadedConfig.platform);
+ setConfig({ ...loadedConfig, agent_catalog: settings.agent_catalog });
+ } catch {
+ setConfig(loadedConfig);
+ }
+ });
}, []);
const loadAllUsers = async () => {
@@ -633,6 +647,7 @@ export const UserList: React.FC = () => {
show_message_types: ['assistant'],
custom_cwd: '',
routing: {
+ agent_name: null,
agent_backend: null,
opencode_agent: null,
opencode_model: null,
@@ -720,7 +735,8 @@ export const UserList: React.FC = () => {
const expanded = expandedKey === u.key;
const userConfig = u.config;
const defaultBackend = config.agents?.default_backend || 'opencode';
- const effectiveBackend = userConfig.routing?.agent_backend || defaultBackend;
+ const selectedAgent = agentByName[userConfig.routing?.agent_name || ''] || agentByName[defaultAgentName || ''];
+ const effectiveBackend = selectedAgent?.backend || userConfig.routing?.agent_backend || defaultBackend;
const effectiveCwd = userConfig.custom_cwd || config.runtime?.default_cwd || '~/work';
const opencodeOptions = opencodeOptionsByCwd[effectiveCwd];
const claudeAgents = claudeAgentsByCwd[effectiveCwd] || [];
@@ -735,7 +751,9 @@ export const UserList: React.FC = () => {
: userConfig.routing.opencode_model;
const displayName = displayNameForUser(u);
const metaPrefix = userConfig.enabled
- ? `${backendLabel(effectiveBackend)}${backendModel ? `/${backendModel}` : ''}`
+ ? selectedAgent
+ ? `${selectedAgent.name}${selectedAgent.model ? `/${selectedAgent.model}` : ''}`
+ : `${backendLabel(effectiveBackend)}${backendModel ? `/${backendModel}` : ''}`
: t('userList.disabled', { defaultValue: 'Disabled' });
const updateRow = (patch: Partial<UserConfig>) => updateUser(u.platform, u.userId, patch);
@@ -854,6 +872,8 @@ export const UserList: React.FC = () => {
onChange={(patch) => updateRow(patch)}
onBrowseDirectory={() => setBrowsingCwdFor(u.key)}
globalConfig={config}
+ vibeAgents={vibeAgents}
+ defaultAgentName={defaultAgentName}
showRequireMention={false}
opencodeOptions={opencodeOptions}
claudeAgents={claudeAgents}
diff --git a/vibe/api.py b/vibe/api.py
index c2ba1507c..33ad8923c 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -52,6 +52,12 @@ from modules.agents.catalog import (
supports_web_oauth,
)
from modules.agents.subagent_router import list_codex_subagents
+from core.vibe_agents import (
+ VibeAgentStore,
+ iter_global_agent_files,
+ parse_agent_file,
+ validate_agent_backend,
+)
from core.process_isolation import isolated_subprocess_kwargs, signal_process_tree, KILL_SIGNAL
@@ -685,12 +691,196 @@ def get_agent_backend_catalog() -> dict:
return {"backends": agent_backend_catalog_payload()}
+def _vibe_agent_payload(agent, *, brief: bool = False) -> dict:
+ payload = agent.to_dict()
+ if brief:
+ return {
+ "id": payload["id"],
+ "name": payload["name"],
+ "description": payload["description"],
+ "backend": payload["backend"],
+ "model": payload["model"],
+ "reasoning_effort": payload["reasoning_effort"],
+ "source": payload["source"],
+ "updated_at": payload["updated_at"],
+ }
+ return payload
+
+
+def get_vibe_agents(*, backend: Optional[str] = None) -> dict:
+ store = VibeAgentStore()
+ try:
+ normalized_backend = validate_agent_backend(backend) if backend else None
+ agents = store.list_agents()
+ if normalized_backend:
+ agents = [agent for agent in agents if agent.backend == normalized_backend]
+ default_agent = store.get_default_agent()
+ return {
+ "ok": True,
+ "agents": [_vibe_agent_payload(agent, brief=True) for agent in agents],
+ "default_agent_name": default_agent.name if default_agent else None,
+ }
+ finally:
+ store.close()
+
+
+def get_vibe_agent(name: str) -> dict:
+ store = VibeAgentStore()
+ try:
+ agent = store.require(name)
+ default_agent = store.get_default_agent()
+ return {
+ "ok": True,
+ "agent": _vibe_agent_payload(agent),
+ "default_agent_name": default_agent.name if default_agent else None,
+ }
+ finally:
+ store.close()
+
+
+def create_vibe_agent(payload: dict) -> dict:
+ if not isinstance(payload, dict):
+ raise ValueError("Agent payload must be an object")
+ metadata = payload.get("metadata") or payload.get("metadata_json") or {}
+ if not isinstance(metadata, dict):
+ raise ValueError("Agent metadata must be an object")
+ store = VibeAgentStore()
+ try:
+ agent = store.create(
+ name=str(payload.get("name") or "").strip(),
+ backend=validate_agent_backend(str(payload.get("backend") or "")),
+ description=payload.get("description"),
+ model=payload.get("model"),
+ reasoning_effort=payload.get("reasoning_effort") or payload.get("effort"),
+ system_prompt=payload.get("system_prompt"),
+ metadata=metadata,
+ )
+ return {"ok": True, "agent": _vibe_agent_payload(agent)}
+ finally:
+ store.close()
+
+
+def update_vibe_agent(name: str, payload: dict) -> dict:
+ if not isinstance(payload, dict):
+ raise ValueError("Agent payload must be an object")
+ if "name" in payload and str(payload.get("name") or "").strip() and str(payload.get("name")).strip() != name:
+ raise ValueError("Agent name is immutable")
+ if "backend" in payload:
+ raise ValueError("Agent backend is immutable")
+
+ allowed_fields = {"description", "model", "reasoning_effort", "effort", "system_prompt", "metadata", "metadata_json"}
+ kwargs: dict[str, object] = {}
+ if "description" in payload:
+ kwargs["description"] = payload.get("description")
+ if "model" in payload:
+ kwargs["model"] = payload.get("model")
+ if "reasoning_effort" in payload or "effort" in payload:
+ kwargs["reasoning_effort"] = payload.get("reasoning_effort") or payload.get("effort")
+ if "system_prompt" in payload:
+ kwargs["system_prompt"] = payload.get("system_prompt")
+ if "metadata" in payload or "metadata_json" in payload:
+ metadata = payload.get("metadata") if "metadata" in payload else payload.get("metadata_json")
+ if metadata is None:
+ metadata = {}
+ if not isinstance(metadata, dict):
+ raise ValueError("Agent metadata must be an object")
+ kwargs["metadata"] = metadata
+ unknown = sorted(set(payload) - allowed_fields - {"name"})
+ if unknown:
+ raise ValueError(f"Unsupported Agent fields: {', '.join(unknown)}")
+ if not kwargs:
+ raise ValueError("No editable Agent fields were provided")
+
+ store = VibeAgentStore()
+ try:
+ agent = store.update(name, **kwargs)
+ return {"ok": True, "agent": _vibe_agent_payload(agent)}
+ finally:
+ store.close()
+
+
+def remove_vibe_agent(name: str) -> dict:
+ store = VibeAgentStore()
+ try:
+ counts = store.reference_counts(name)
+ if any(counts.values()):
+ return {
+ "ok": False,
+ "code": "agent_in_use",
+ "message": f"agent '{name}' is still referenced",
+ "references": counts,
+ }
+ removed = store.remove(name)
+ if not removed:
+ return {"ok": False, "code": "agent_not_found", "message": f"agent '{name}' not found"}
+ return {"ok": True, "removed_agent": name}
+ finally:
+ store.close()
+
+
+def set_default_vibe_agent(name: str) -> dict:
+ store = VibeAgentStore()
+ try:
+ store.set_default_agent_name(name)
+ agent = store.require(name)
+ return {"ok": True, "default_agent_name": agent.name, "agent": _vibe_agent_payload(agent, brief=True)}
+ finally:
+ store.close()
+
+
+def import_vibe_agents(payload: dict) -> dict:
+ if not isinstance(payload, dict):
+ raise ValueError("Import payload must be an object")
+ candidates = []
+ file_path = payload.get("file")
+ source = payload.get("from") or payload.get("from_source")
+ name = str(payload.get("name") or "").strip()
+ import_all = bool(payload.get("all"))
+
+ if file_path:
+ if source:
+ raise ValueError("Use either file or from, not both")
+ if name or import_all:
+ raise ValueError("name and all are only valid with from")
+ backend = validate_agent_backend(str(payload.get("backend") or ""))
+ candidates.append(parse_agent_file(Path(file_path).expanduser(), backend=backend))
+ else:
+ if source not in {"claude", "codex", "opencode"}:
+ raise ValueError("from must be one of: claude, codex, opencode")
+ if name and import_all:
+ raise ValueError("Use either name or all, not both")
+ for path, backend in iter_global_agent_files(str(source)):
+ candidate = parse_agent_file(path, backend=backend)
+ if name and candidate.name != name:
+ continue
+ candidates.append(candidate)
+ if name and not candidates:
+ return {
+ "ok": False,
+ "code": "agent_import_source_not_found",
+ "message": f"agent '{name}' was not found in {source} global agents",
+ }
+
+ store = VibeAgentStore()
+ try:
+ result = store.import_candidates(candidates)
+ return {
+ "ok": True,
+ "imported": [_vibe_agent_payload(agent, brief=True) for agent in result.imported],
+ "skipped": result.skipped,
+ }
+ finally:
+ store.close()
+
+
def get_settings(platform: Optional[str] = None) -> dict:
store = SettingsStore.get_instance()
target_platform = platform or _current_platform()
if target_platform == "discord":
_migrate_discord_guild_scope_from_config(store)
- return _settings_to_payload(store, platform=target_platform)
+ payload = _settings_to_payload(store, platform=target_platform)
+ payload["agent_catalog"] = get_vibe_agents()
+ return payload
def save_settings(payload: dict) -> dict:
diff --git a/vibe/cli.py b/vibe/cli.py
index fe4fe65ad..2e6ab4e01 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -21,6 +21,7 @@ from zoneinfo import ZoneInfo
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.date import DateTrigger
from tzlocal import get_localzone_name
+from sqlalchemy import select
from config import SettingsStore, paths
from config.v2_config import (
@@ -50,6 +51,10 @@ from vibe.upgrade import (
get_restart_invocation_command,
get_safe_cwd,
)
+from storage.db import create_sqlite_engine
+from storage.background import normalize_run_status
+from storage.models import scope_settings
+from storage.settings_service import make_scope_id
logger = logging.getLogger(__name__)
@@ -225,12 +230,16 @@ def _task_update_examples_text() -> str:
def _hook_send_examples_text() -> str:
return dedent(
"""\
+ Deprecated:
+ `vibe hook send` is a compatibility entrypoint.
+ New automation should use `vibe agent run --async`.
+
Session target:
Use --session-id with the current Agent Session ID, for example sesk8m4q2p7x.
Guidance:
- If this is your first time using this command, read this whole help entry before queuing a hook.
- `vibe hook send` queues one asynchronous turn without persisting a scheduled task.
+ If this is your first time creating an async one-shot run, use `vibe agent run --async --help`.
+ `vibe hook send` queues one deprecated asynchronous compatibility turn without persisting a scheduled task.
`--session-id` chooses which Agent Session Vibe Remote will continue using for that one async turn.
Keep the current session id when the hook should continue in the same session.
If no session id is available, trigger this from an active Vibe Remote conversation instead of guessing.
@@ -239,9 +248,8 @@ def _hook_send_examples_text() -> str:
`--message` and `--message-file` provide the one-shot async user message that will be queued immediately.
Examples:
- vibe hook send --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
- vibe hook send --session-id sesk8m4q2p7x --post-to channel --message 'Share the benchmark result in the channel.'
- vibe hook send --session-id sesk8m4q2p7x --deliver-key 'slack::channel::C999' --message 'Post the deployment summary in announcements.'
+ vibe agent run --async --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
+ vibe agent run --async --session-id sesk8m4q2p7x --message 'Share the benchmark result.'
"""
)
@@ -627,6 +635,35 @@ def _resolve_message_input(args, *, help_command: str, example_command: str) ->
)
+def _resolve_optional_message_input(
+ args,
+ *,
+ help_command: str,
+ example_command: str,
+ legacy_prefix: Optional[str] = None,
+) -> Optional[str]:
+ if getattr(args, "prompt", None) is not None or getattr(args, "prompt_file", None) is not None:
+ raise TaskCliError(
+ "--prompt is deprecated; use --message instead",
+ code="deprecated_prompt_argument",
+ hint="Use --message for the user message sent to the Agent, or --message-file for file input.",
+ example=f"{example_command} --message 'Review the waiter output.'",
+ help_command=help_command,
+ )
+ has_message = getattr(args, "message", None) is not None or getattr(args, "message_file", None) is not None
+ has_prefix = legacy_prefix is not None
+ if has_message and has_prefix:
+ raise TaskCliError(
+ "use either --message/--message-file or --prefix, not both",
+ code="conflicting_message_inputs",
+ hint="Use --message for new watches. --prefix is only a compatibility alias.",
+ help_command=help_command,
+ )
+ if has_message:
+ return _resolve_message_input(args, help_command=help_command, example_command=example_command)
+ return legacy_prefix
+
+
def _resolve_legacy_prompt_input(args, *, help_command: str, example_command: str) -> str:
prompt = (getattr(args, "prompt", None) or "").strip()
prompt_file = getattr(args, "prompt_file", None)
@@ -1123,6 +1160,70 @@ def _validate_agent_name_arg(agent_name: Optional[str]) -> Optional[str]:
return value
+def _resolve_scope_agent_name(session_key: str) -> Optional[str]:
+ if not session_key:
+ return None
+ try:
+ parsed = parse_session_key(session_key)
+ except ValueError:
+ return None
+ scope_id = make_scope_id(parsed.platform, parsed.scope_type, parsed.scope_id)
+ engine = create_sqlite_engine(paths.get_sqlite_state_path())
+ try:
+ with engine.connect() as conn:
+ value = conn.execute(
+ select(scope_settings.c.agent_name)
+ .where(scope_settings.c.scope_id == scope_id)
+ .limit(1)
+ ).scalar_one_or_none()
+ return str(value).strip() if value else None
+ finally:
+ engine.dispose()
+
+
+def _resolve_agent_for_target(
+ *,
+ agent_name: Optional[str],
+ session_id: Optional[str],
+ session_key: str,
+ help_command: str,
+):
+ store = _agent_store()
+ try:
+ requested = store.require(agent_name) if agent_name else None
+ if session_id:
+ target = resolve_session_id_target(session_id)
+ resolved = requested
+ if resolved is None and target.agent_name:
+ resolved = store.require(target.agent_name)
+ if resolved is not None and target.agent_backend and resolved.backend != target.agent_backend:
+ raise TaskCliError(
+ "agent backend does not match the existing session backend",
+ code="agent_session_backend_mismatch",
+ hint="Use an Agent with the same backend as the Session, or create a new Session.",
+ details={
+ "agent": resolved.name,
+ "agent_backend": resolved.backend,
+ "session_id": session_id,
+ "session_backend": target.agent_backend,
+ },
+ help_command=help_command,
+ )
+ return resolved
+
+ if requested is not None:
+ return requested
+
+ if session_key:
+ scope_agent_name = _resolve_scope_agent_name(session_key)
+ if scope_agent_name:
+ return store.require(scope_agent_name)
+
+ return store.get_default_agent()
+ finally:
+ store.close()
+
+
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 [])
@@ -1191,6 +1292,7 @@ def _watch_payload(watch, runtime_entry: Optional[dict[str, object]], *, brief:
"session_id": watch.session_id,
"session_key": watch.session_key,
"agent_name": watch.agent_name,
+ "message_preview": _task_message_preview(getattr(watch, "message", None) or watch.prefix or ""),
"timeout_seconds": watch.timeout_seconds,
"lifetime_timeout_seconds": watch.lifetime_timeout_seconds,
"enabled": watch.enabled,
@@ -1218,20 +1320,22 @@ def _agent_payload(agent, *, brief: bool = False) -> dict:
def _run_payload(run: dict, *, brief: bool = False) -> dict:
+ normalized = dict(run)
+ normalized["status"] = normalize_run_status(normalized.get("status"))
if brief:
return {
- "id": run.get("id"),
- "run_type": run.get("run_type") or run.get("request_type"),
- "status": run.get("status"),
- "agent_name": run.get("agent_name"),
- "session_id": run.get("session_id"),
- "definition_id": run.get("definition_id") or run.get("task_id"),
- "created_at": run.get("created_at"),
- "started_at": run.get("started_at"),
- "completed_at": run.get("completed_at"),
- "error": run.get("error"),
+ "id": normalized.get("id"),
+ "run_type": normalized.get("run_type") or normalized.get("request_type"),
+ "status": normalized.get("status"),
+ "agent_name": normalized.get("agent_name"),
+ "session_id": normalized.get("session_id"),
+ "definition_id": normalized.get("definition_id") or normalized.get("task_id"),
+ "created_at": normalized.get("created_at"),
+ "started_at": normalized.get("started_at"),
+ "completed_at": normalized.get("completed_at"),
+ "error": normalized.get("error"),
}
- return run
+ return normalized
def _seconds_since_iso(timestamp: object) -> float | None:
@@ -1328,12 +1432,18 @@ def cmd_task_add(args):
help_command="vibe task add --help",
example_command="vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *'",
)
- agent_name = _validate_agent_name_arg(getattr(args, "agent", None))
session_id, session_key = _resolve_session_target_args(
args,
required=session_policy == "existing",
help_command="vibe task add --help",
)
+ agent = _resolve_agent_for_target(
+ agent_name=getattr(args, "agent", None),
+ session_id=session_id,
+ session_key=session_key or getattr(args, "deliver_key", None) or "",
+ help_command="vibe task add --help",
+ )
+ agent_name = agent.name if agent else None
if session_policy == "create_once":
session_id = _reserve_definition_session(
agent_name=agent_name,
@@ -1654,6 +1764,22 @@ def cmd_task_update(args):
hint="Pass the Scope ID that owns the new Session.",
help_command="vibe task update --help",
)
+ if agent_name is None and session_policy != "existing":
+ agent = _resolve_agent_for_target(
+ agent_name=None,
+ session_id=None,
+ session_key=deliver_key or "",
+ help_command="vibe task update --help",
+ )
+ agent_name = agent.name if agent else None
+ elif agent_name is not None or session_id or session_key:
+ agent = _resolve_agent_for_target(
+ agent_name=agent_name,
+ session_id=session_id,
+ session_key=session_key,
+ help_command="vibe task update --help",
+ )
+ agent_name = agent.name if agent else None
if session_policy == "create_once" and (
getattr(args, "create_session", False) or not session_id
):
@@ -1752,7 +1878,7 @@ def cmd_task_run(task_id: str):
)
)
return 1
- request = _task_request_store().enqueue_task_run(task.id)
+ request = _task_request_store().enqueue_task_run(task.id, task=task)
_print_cli_payload(
"agent_run",
accepted=True,
@@ -1764,9 +1890,11 @@ def cmd_task_run(task_id: str):
run={
"id": request.id,
"status": "queued",
+ "run_type": request.request_type,
"definition_id": task.id,
"agent_name": task.agent_name,
"session_id": task.session_id,
+ "session_policy": task.session_policy,
},
)
return 0
@@ -1791,13 +1919,21 @@ def cmd_hook_send(args):
help_command="vibe hook send --help",
example_command="vibe hook send --session-id sesk8m4q2p7x",
)
+ agent = _resolve_agent_for_target(
+ agent_name=getattr(args, "agent", None),
+ session_id=session_id,
+ session_key=session_key,
+ help_command="vibe hook send --help",
+ )
request = _task_request_store().enqueue_hook_send(
session_key=session_key,
session_id=session_id,
post_to=args.post_to,
deliver_key=args.deliver_key,
prompt=message,
- agent_name=_validate_agent_name_arg(getattr(args, "agent", None)),
+ agent_name=agent.name if agent else None,
+ run_type="agent_run",
+ source_kind="cli",
)
warnings = _collect_target_warnings(session_target, delivery_target)
_print_cli_payload(
@@ -1810,10 +1946,12 @@ def cmd_hook_send(args):
session_key=session_key,
post_to=args.post_to,
deliver_key=args.deliver_key,
+ deprecation_warning="vibe hook send is deprecated; use vibe agent run --async instead.",
run={
"id": request.id,
"status": "queued",
"run_type": request.request_type,
+ "agent_name": agent.name if agent else None,
"session_id": session_id,
},
warnings=warnings,
@@ -1849,9 +1987,17 @@ def _parse_metadata_json(value: str | None) -> dict:
return payload
+def _add_json_noop(parser) -> None:
+ parser.add_argument("--json", action="store_true", help=argparse.SUPPRESS)
+
+
def cmd_agent_list(args):
store = _agent_store()
- agents = [_agent_payload(agent, brief=getattr(args, "brief", False)) for agent in store.list_agents()]
+ backend = getattr(args, "backend", None)
+ agents = store.list_agents()
+ if backend:
+ agents = [agent for agent in agents if agent.backend == backend]
+ agents = [_agent_payload(agent, brief=getattr(args, "brief", False)) for agent in agents]
_print_cli_payload("agents", agents=agents)
return 0
@@ -1926,7 +2072,16 @@ def cmd_agent_update(args):
def cmd_agent_remove(args):
try:
- removed = _agent_store().remove(args.name)
+ store = _agent_store()
+ counts = store.reference_counts(args.name)
+ if any(counts.values()):
+ raise TaskCliError(
+ f"agent '{args.name}' is still referenced",
+ code="agent_in_use",
+ hint="Reassign or remove the referencing scopes, sessions, tasks, or watches before deleting this Agent.",
+ details={"agent": args.name, "references": counts},
+ )
+ removed = store.remove(args.name)
if not removed:
raise TaskCliError(f"agent '{args.name}' not found", code="agent_not_found", details={"agent": args.name})
_print_cli_payload("agent", removed_agent=args.name)
@@ -1940,6 +2095,12 @@ def cmd_agent_import(args):
try:
candidates = []
if args.file:
+ if args.name or args.all:
+ raise TaskCliError(
+ "--name and --all are only valid with --from",
+ code="invalid_agent_import_filter",
+ help_command="vibe agent import --help",
+ )
if not args.backend:
raise TaskCliError(
"--backend is required when importing an arbitrary file",
@@ -1948,8 +2109,23 @@ def cmd_agent_import(args):
)
candidates.append(parse_agent_file(Path(args.file), backend=args.backend))
else:
+ if args.name and args.all:
+ raise TaskCliError(
+ "use either --name or --all, not both",
+ code="invalid_agent_import_filter",
+ help_command="vibe agent import --help",
+ )
for path, backend in iter_global_agent_files(args.from_source):
- candidates.append(parse_agent_file(path, backend=backend))
+ candidate = parse_agent_file(path, backend=backend)
+ if args.name and candidate.name != args.name:
+ continue
+ candidates.append(candidate)
+ if args.name and not candidates:
+ raise TaskCliError(
+ f"agent '{args.name}' was not found in {args.from_source} global agents",
+ code="agent_import_source_not_found",
+ details={"source": args.from_source, "name": args.name},
+ )
result = _agent_store().import_candidates(candidates)
_print_cli_payload(
"agents",
@@ -1966,6 +2142,13 @@ def _validate_run_session_policy(args, *, help_command: str) -> str:
session_id = (getattr(args, "session_id", None) or "").strip()
create_session = bool(getattr(args, "create_session", False))
create_per_run = bool(getattr(args, "create_session_per_run", False))
+ if bool(getattr(args, "async_run", False)) and getattr(args, "wait_timeout", None) is not None:
+ raise TaskCliError(
+ "use --async or --wait-timeout, not both",
+ code="conflicting_wait_policy",
+ hint="--async returns immediately. Remove --wait-timeout, or run synchronously without --async.",
+ help_command=help_command,
+ )
if session_id and (create_session or create_per_run):
raise TaskCliError(
"use either --session-id or --create-session, not both",
@@ -2188,9 +2371,9 @@ def cmd_agent_run(args):
hint="Use --create-session --deliver-key <scope-id> when a new delivered Session should be created.",
help_command="vibe agent run --help",
)
- agent = _agent_store().require(agent_name) if agent_name else None
session_id = (args.session_id or "").strip() or None
session_key = ""
+ agent = _agent_store().require(agent_name) if agent_name else None
if session_policy == "create":
session_id = _reserve_cli_session(agent=agent, deliver_key=args.deliver_key)
elif session_policy == "none":
@@ -2198,19 +2381,12 @@ def cmd_agent_run(args):
if session_id:
target = resolve_session_id_target(session_id)
session_key = target.session_key.to_key()
- if agent and target.agent_backend and agent.backend != target.agent_backend:
- raise TaskCliError(
- "agent backend does not match the existing session backend",
- code="agent_session_backend_mismatch",
- hint="Use an Agent with the same backend as the Session, or create a new Session.",
- details={
- "agent": agent.name,
- "agent_backend": agent.backend,
- "session_id": session_id,
- "session_backend": target.agent_backend,
- },
- help_command="vibe agent run --help",
- )
+ agent = _resolve_agent_for_target(
+ agent_name=agent_name or None,
+ session_id=session_id,
+ session_key=session_key,
+ help_command="vibe agent run --help",
+ )
if args.deliver_key:
_parse_validated_session_key(args.deliver_key, help_command="vibe agent run --help")
request_store = _task_request_store()
@@ -2259,12 +2435,13 @@ def _wait_for_run_result(store: TaskExecutionStore, run_id: str, *, wait_timeout
max_wait = wait_timeout if wait_timeout is not None else 1800.0
while True:
run = store.get_run(run_id)
- if run and run.get("status") in {"completed", "failed", "succeeded", "canceled"}:
+ if run and normalize_run_status(run.get("status")) in {"succeeded", "failed", "canceled"}:
return _run_payload(run)
elapsed = time.monotonic() - started
if elapsed >= max_wait:
run = run or {"id": run_id}
run["wait_state"] = "detached"
+ run["handoff_reason"] = "wait_limit_reached"
run["wait_elapsed_seconds"] = round(elapsed, 3)
run["accepted"] = True
run["async"] = True
@@ -2305,12 +2482,18 @@ def cmd_watch_add(args):
help_command="vibe watch add --help",
)
command, shell_command = _resolve_watch_command(args, help_command="vibe watch add --help")
- agent_name = _validate_agent_name_arg(getattr(args, "agent", None))
session_id, session_key = _resolve_session_target_args(
args,
required=session_policy == "existing",
help_command="vibe watch add --help",
)
+ agent = _resolve_agent_for_target(
+ agent_name=getattr(args, "agent", None),
+ session_id=session_id,
+ session_key=session_key or getattr(args, "deliver_key", None) or "",
+ help_command="vibe watch add --help",
+ )
+ agent_name = agent.name if agent else None
if session_policy == "create_once":
session_id = _reserve_definition_session(
agent_name=agent_name,
@@ -2335,6 +2518,13 @@ def cmd_watch_add(args):
help_command="vibe watch add --help",
)
cwd = _resolve_watch_cwd(args.cwd, help_command="vibe watch add --help")
+ prefix = _normalize_task_name(getattr(args, "prefix", None))
+ message = _resolve_optional_message_input(
+ args,
+ help_command="vibe watch add --help",
+ example_command="vibe watch add --session-id sesk8m4q2p7x",
+ legacy_prefix=prefix,
+ )
retry_exit_codes = sorted(set(args.retry_exit_code or [DEFAULT_RETRY_EXIT_CODE]))
store = _watch_store()
@@ -2344,7 +2534,8 @@ def cmd_watch_add(args):
session_id=session_id,
command=command,
shell_command=shell_command,
- prefix=_normalize_task_name(getattr(args, "prefix", None)),
+ prefix=prefix,
+ message=message,
cwd=cwd,
mode=mode,
timeout_seconds=float(args.timeout),
@@ -2506,6 +2697,18 @@ def cmd_watch_update(args):
else watch.prefix
)
)
+ message_changed = getattr(args, "message", None) is not None or getattr(args, "message_file", None) is not None
+ if message_changed:
+ message = _resolve_optional_message_input(
+ args,
+ help_command="vibe watch update --help",
+ example_command=f"vibe watch update {args.watch_id}",
+ legacy_prefix=None,
+ )
+ elif getattr(args, "prefix", None) is not None or getattr(args, "clear_prefix", False):
+ message = prefix
+ else:
+ message = getattr(watch, "message", None) or watch.prefix
if getattr(args, "clear_agent", False):
agent_name = None
elif getattr(args, "agent", None) is not None:
@@ -2557,6 +2760,22 @@ def cmd_watch_update(args):
hint="Pass the Scope ID that owns the new Session.",
help_command="vibe watch update --help",
)
+ if agent_name is None and session_policy != "existing":
+ agent = _resolve_agent_for_target(
+ agent_name=None,
+ session_id=None,
+ session_key=deliver_key or "",
+ help_command="vibe watch update --help",
+ )
+ agent_name = agent.name if agent else None
+ elif agent_name is not None or session_id or session_key:
+ agent = _resolve_agent_for_target(
+ agent_name=agent_name,
+ session_id=session_id,
+ session_key=session_key,
+ help_command="vibe watch update --help",
+ )
+ agent_name = agent.name if agent else None
if session_policy == "create_once" and (
getattr(args, "create_session", False) or not session_id
):
@@ -2584,6 +2803,7 @@ def cmd_watch_update(args):
"command": command,
"shell_command": shell_command,
"prefix": prefix,
+ "message": message,
"cwd": cwd,
"mode": mode,
"timeout_seconds": timeout_seconds,
@@ -2602,6 +2822,7 @@ def cmd_watch_update(args):
"command": watch.command,
"shell_command": watch.shell_command,
"prefix": watch.prefix,
+ "message": getattr(watch, "message", None) or watch.prefix,
"cwd": watch.cwd,
"mode": watch.mode,
"timeout_seconds": watch.timeout_seconds,
@@ -3628,9 +3849,12 @@ def build_parser():
agent_list_parser = agent_subparsers.add_parser("list", help="List Vibe Agents")
agent_list_parser.add_argument("--brief", action="store_true", help="Show compact Agent rows")
+ agent_list_parser.add_argument("--backend", choices=("codex", "claude", "opencode"), help="Filter by backend")
+ _add_json_noop(agent_list_parser)
agent_show_parser = agent_subparsers.add_parser("show", help="Show one Vibe Agent")
agent_show_parser.add_argument("name", help="Agent name")
+ _add_json_noop(agent_show_parser)
agent_create_parser = agent_subparsers.add_parser("create", help="Create a Vibe Agent")
agent_create_parser.add_argument("name", help="Globally unique Agent name")
@@ -3638,10 +3862,12 @@ def build_parser():
agent_create_parser.add_argument("--description")
agent_create_parser.add_argument("--model")
agent_create_parser.add_argument("--reasoning-effort")
+ agent_create_parser.add_argument("--effort", dest="reasoning_effort", help=argparse.SUPPRESS)
system_prompt_group = agent_create_parser.add_mutually_exclusive_group()
system_prompt_group.add_argument("--system-prompt")
system_prompt_group.add_argument("--system-prompt-file")
agent_create_parser.add_argument("--metadata", help="JSON object stored with the Agent")
+ _add_json_noop(agent_create_parser)
agent_update_parser = agent_subparsers.add_parser("update", help="Update editable Vibe Agent fields")
agent_update_parser.add_argument("name", help="Agent name. Name and backend are immutable.")
@@ -3650,21 +3876,27 @@ def build_parser():
agent_update_parser.add_argument("--model")
agent_update_parser.add_argument("--clear-model", action="store_true")
agent_update_parser.add_argument("--reasoning-effort")
+ agent_update_parser.add_argument("--effort", dest="reasoning_effort", help=argparse.SUPPRESS)
agent_update_parser.add_argument("--clear-reasoning-effort", action="store_true")
update_prompt_group = agent_update_parser.add_mutually_exclusive_group()
update_prompt_group.add_argument("--system-prompt")
update_prompt_group.add_argument("--system-prompt-file")
update_prompt_group.add_argument("--clear-system-prompt", action="store_true")
agent_update_parser.add_argument("--metadata", help="Replace metadata with a JSON object")
+ _add_json_noop(agent_update_parser)
agent_remove_parser = agent_subparsers.add_parser("remove", help="Remove a Vibe Agent")
agent_remove_parser.add_argument("name", help="Agent name")
+ _add_json_noop(agent_remove_parser)
agent_import_parser = agent_subparsers.add_parser("import", help="Import global or file-based Agents")
import_source_group = agent_import_parser.add_mutually_exclusive_group(required=True)
import_source_group.add_argument("--file", help="Import one markdown Agent file")
import_source_group.add_argument("--from", dest="from_source", choices=("claude", "codex", "opencode"))
agent_import_parser.add_argument("--backend", choices=("codex", "claude", "opencode"), help="Backend for --file imports")
+ agent_import_parser.add_argument("--name", help="Import one named global Agent from --from source")
+ agent_import_parser.add_argument("--all", action="store_true", help="Import all global Agents from --from source")
+ _add_json_noop(agent_import_parser)
agent_run_parser = agent_subparsers.add_parser(
"run",
@@ -3686,6 +3918,7 @@ def build_parser():
agent_message_group.add_argument("--message-file")
agent_message_group.add_argument("--prompt", help=argparse.SUPPRESS)
agent_message_group.add_argument("--prompt-file", help=argparse.SUPPRESS)
+ _add_json_noop(agent_run_parser)
runs_parser = subparsers.add_parser(
"runs",
@@ -3699,10 +3932,13 @@ def build_parser():
runs_list_parser = runs_subparsers.add_parser("list", help="List Agent runs")
runs_list_parser.add_argument("--status", help="Filter by run status")
runs_list_parser.add_argument("--brief", action="store_true", help="Show compact run rows")
+ _add_json_noop(runs_list_parser)
runs_show_parser = runs_subparsers.add_parser("show", help="Show one Agent run")
runs_show_parser.add_argument("run_id")
+ _add_json_noop(runs_show_parser)
runs_cancel_parser = runs_subparsers.add_parser("cancel", help="Request best-effort cancellation for one run")
runs_cancel_parser.add_argument("run_id")
+ _add_json_noop(runs_cancel_parser)
task_parser = subparsers.add_parser(
"task",
@@ -3762,6 +3998,7 @@ def build_parser():
prompt_group.add_argument("--prompt", help=argparse.SUPPRESS)
prompt_group.add_argument("--prompt-file", help=argparse.SUPPRESS)
task_add_parser.add_argument("--timezone", help="IANA timezone name used for --cron and naive --at values")
+ _add_json_noop(task_add_parser)
task_update_parser = task_subparsers.add_parser(
"update",
@@ -3807,6 +4044,7 @@ def build_parser():
task_update_parser.add_argument("--prompt", help=argparse.SUPPRESS)
task_update_parser.add_argument("--prompt-file", help=argparse.SUPPRESS)
task_update_parser.add_argument("--timezone", help="Replace the stored IANA timezone name")
+ _add_json_noop(task_update_parser)
task_subparsers.add_parser(
"list",
@@ -3827,6 +4065,7 @@ def build_parser():
action="store_true",
help="Show a compact scheduling-focused view instead of the full stored task payload",
)
+ _add_json_noop(task_list_parser)
_add_hidden_task_alias(task_subparsers, "ls", task_list_parser)
task_show_parser = task_subparsers.add_parser(
@@ -3838,6 +4077,7 @@ def build_parser():
error_help_command="vibe task show --help",
)
task_show_parser.add_argument("task_id", help="Task ID from 'vibe task list'")
+ _add_json_noop(task_show_parser)
task_pause_parser = task_subparsers.add_parser(
"pause",
@@ -3848,6 +4088,7 @@ def build_parser():
error_help_command="vibe task pause --help",
)
task_pause_parser.add_argument("task_id", help="Task ID from 'vibe task list'")
+ _add_json_noop(task_pause_parser)
task_resume_parser = task_subparsers.add_parser(
"resume",
@@ -3858,6 +4099,7 @@ def build_parser():
error_help_command="vibe task resume --help",
)
task_resume_parser.add_argument("task_id", help="Task ID from 'vibe task list'")
+ _add_json_noop(task_resume_parser)
task_run_parser = task_subparsers.add_parser(
"run",
@@ -3868,6 +4110,7 @@ def build_parser():
error_help_command="vibe task run --help",
)
task_run_parser.add_argument("task_id", help="Task ID from 'vibe task list'")
+ _add_json_noop(task_run_parser)
task_rm_parser = task_subparsers.add_parser(
"remove",
@@ -3878,22 +4121,23 @@ def build_parser():
error_help_command="vibe task remove --help",
)
task_rm_parser.add_argument("task_id", help="Task ID from 'vibe task list'")
+ _add_json_noop(task_rm_parser)
_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.",
+ help="Deprecated compatibility one-shot async hooks",
+ description="Deprecated compatibility entrypoint. Use 'vibe agent run --async' for new one-shot asynchronous turns.",
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe hook --help",
- error_hint="Run 'vibe hook send --help' for the async hook command shape.",
+ error_hint="Use 'vibe agent run --async --help' for the current async Agent Run 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 an Agent Session ID without storing a scheduled task.",
+ help="Deprecated compatibility async send",
+ description="Deprecated compatibility entrypoint. Use 'vibe agent run --async' for new one-shot asynchronous Agent Runs.",
epilog=_hook_send_examples_text(),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe hook send --help",
@@ -3923,6 +4167,7 @@ def build_parser():
hook_prompt_group.add_argument("--message-file", help="Read one-shot async user message from a UTF-8 text file")
hook_prompt_group.add_argument("--prompt", help=argparse.SUPPRESS)
hook_prompt_group.add_argument("--prompt-file", help=argparse.SUPPRESS)
+ _add_json_noop(hook_send_parser)
watch_parser = subparsers.add_parser(
"watch",
@@ -3974,6 +4219,11 @@ def build_parser():
"--prefix",
help="Optional follow-up instruction text prepended before waiter stdout, joined with a blank line when both exist.",
)
+ watch_message_group = watch_add_parser.add_mutually_exclusive_group()
+ watch_message_group.add_argument("--message", help="Follow-up user message template sent with waiter output")
+ watch_message_group.add_argument("--message-file", help="Read follow-up user message from a UTF-8 text file")
+ watch_message_group.add_argument("--prompt", help=argparse.SUPPRESS)
+ watch_message_group.add_argument("--prompt-file", help=argparse.SUPPRESS)
watch_add_parser.add_argument("--cwd", help="Working directory for the waiter process")
watch_add_parser.add_argument(
"--timeout",
@@ -4015,6 +4265,7 @@ def build_parser():
nargs=argparse.REMAINDER,
help="Waiter command to run after '--'. Example: vibe watch add ... -- python3 script.py --flag value",
)
+ _add_json_noop(watch_add_parser)
watch_update_parser = watch_subparsers.add_parser(
"update",
@@ -4060,6 +4311,11 @@ def build_parser():
help="Set follow-up instruction text prepended before waiter stdout.",
)
watch_update_parser.add_argument("--clear-prefix", action="store_true", help="Clear the stored follow-up prefix")
+ watch_update_message_group = watch_update_parser.add_mutually_exclusive_group()
+ watch_update_message_group.add_argument("--message", help="Replace the follow-up user message template")
+ watch_update_message_group.add_argument("--message-file", help="Read replacement follow-up user message from a UTF-8 text file")
+ watch_update_message_group.add_argument("--prompt", help=argparse.SUPPRESS)
+ watch_update_message_group.add_argument("--prompt-file", help=argparse.SUPPRESS)
watch_update_parser.add_argument("--cwd", help="Set working directory for the waiter process")
watch_update_parser.add_argument("--clear-cwd", action="store_true", help="Clear the stored waiter working directory")
watch_update_parser.add_argument("--timeout", type=float, help="Set per-cycle timeout in seconds")
@@ -4082,6 +4338,7 @@ def build_parser():
watch_update_parser.add_argument("--retry-delay", type=float, help="Set retry delay in seconds")
watch_update_parser.add_argument("--shell", help="Replace waiter with a shell command")
watch_update_parser.set_defaults(waiter_command=None)
+ _add_json_noop(watch_update_parser)
watch_list_parser = watch_subparsers.add_parser(
"list",
@@ -4096,6 +4353,7 @@ def build_parser():
action="store_true",
help="Show a compact watcher-focused view instead of the full stored watch payload",
)
+ _add_json_noop(watch_list_parser)
_add_hidden_task_alias(watch_subparsers, "ls", watch_list_parser)
watch_show_parser = watch_subparsers.add_parser(
@@ -4107,6 +4365,7 @@ def build_parser():
error_help_command="vibe watch show --help",
)
watch_show_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")
+ _add_json_noop(watch_show_parser)
watch_pause_parser = watch_subparsers.add_parser(
"pause",
@@ -4117,6 +4376,7 @@ def build_parser():
error_help_command="vibe watch pause --help",
)
watch_pause_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")
+ _add_json_noop(watch_pause_parser)
watch_resume_parser = watch_subparsers.add_parser(
"resume",
@@ -4127,6 +4387,7 @@ def build_parser():
error_help_command="vibe watch resume --help",
)
watch_resume_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")
+ _add_json_noop(watch_resume_parser)
watch_remove_parser = watch_subparsers.add_parser(
"remove",
@@ -4137,6 +4398,7 @@ def build_parser():
error_help_command="vibe watch remove --help",
)
watch_remove_parser.add_argument("watch_id", help="Watch ID from 'vibe watch list'")
+ _add_json_noop(watch_remove_parser)
_add_hidden_task_alias(watch_subparsers, "rm", watch_remove_parser)
return parser
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index d90bf133d..0a6ee15ef 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1185,6 +1185,97 @@ def agent_backends_get():
return jsonify(api.get_agent_backend_catalog())
+def _vibe_agent_error_response(exc: ValueError):
+ message = str(exc)
+ lowered = message.lower()
+ if "not found" in lowered:
+ return jsonify({"ok": False, "code": "agent_not_found", "message": message}), 404
+ if "already exists" in lowered:
+ return jsonify({"ok": False, "code": "agent_already_exists", "message": message}), 409
+ return jsonify({"ok": False, "code": "invalid_agent_request", "message": message}), 400
+
+
+def _vibe_agent_result_response(result: dict):
+ status = 200
+ if not result.get("ok", True):
+ code = result.get("code")
+ if code == "agent_in_use":
+ status = 409
+ elif code in {"agent_not_found", "agent_import_source_not_found"}:
+ status = 404
+ else:
+ status = 400
+ return jsonify(result), status
+
+
[email protected]("/agents", methods=["GET"])
+def vibe_agents_get():
+ from vibe import api
+
+ try:
+ return jsonify(api.get_vibe_agents(backend=request.args.get("backend") or None))
+ except ValueError as exc:
+ return _vibe_agent_error_response(exc)
+
+
[email protected]("/agents/<name>", methods=["GET"])
+def vibe_agent_get(name):
+ from vibe import api
+
+ try:
+ return jsonify(api.get_vibe_agent(name))
+ except ValueError as exc:
+ return _vibe_agent_error_response(exc)
+
+
[email protected]("/agents", methods=["POST"])
+def vibe_agents_post():
+ from vibe import api
+
+ try:
+ return jsonify(api.create_vibe_agent(request.json or {}))
+ except ValueError as exc:
+ return _vibe_agent_error_response(exc)
+
+
[email protected]("/agents/import", methods=["POST"])
+def vibe_agents_import_post():
+ from vibe import api
+
+ try:
+ return _vibe_agent_result_response(api.import_vibe_agents(request.json or {}))
+ except ValueError as exc:
+ return _vibe_agent_error_response(exc)
+
+
[email protected]("/agents/default", methods=["POST"])
+def vibe_agents_default_post():
+ from vibe import api
+
+ payload = request.json or {}
+ try:
+ return jsonify(api.set_default_vibe_agent(payload.get("name") or ""))
+ except ValueError as exc:
+ return _vibe_agent_error_response(exc)
+
+
[email protected]("/agents/<name>", methods=["PATCH"])
+def vibe_agent_patch(name):
+ from vibe import api
+
+ try:
+ return jsonify(api.update_vibe_agent(name, request.json or {}))
+ except ValueError as exc:
+ return _vibe_agent_error_response(exc)
+
+
[email protected]("/agents/<name>", methods=["DELETE"])
+def vibe_agent_delete(name):
+ from vibe import api
+
+ return _vibe_agent_result_response(api.remove_vibe_agent(name))
+
+
@app.route("/settings", methods=["GET"])
def settings_get():
# /settings doubles as a backend JSON API and a user-facing URL the SPA