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): implement agent run sessions

cyh316ec94db322
diff --git a/config/v2_sessions.py b/config/v2_sessions.py
index f016e3a07..87f6b250b 100644
--- a/config/v2_sessions.py
+++ b/config/v2_sessions.py
@@ -336,12 +336,22 @@ class SessionsStore:
session_anchor=thread_id,
)
- def ensure_agent_session_id(self, user_id: str, agent_name: str, thread_id: str) -> Optional[str]:
+ def ensure_agent_session_id(
+ self,
+ user_id: str,
+ agent_name: str,
+ thread_id: str,
+ *,
+ vibe_agent_id: str | None = None,
+ vibe_agent_name: str | None = None,
+ ) -> Optional[str]:
self._ensure_service()
agent_session_id = self._service.ensure_agent_session_id(
scope_key=user_id,
agent_name=agent_name,
session_anchor=thread_id,
+ vibe_agent_id=vibe_agent_id,
+ vibe_agent_name=vibe_agent_name,
)
self.get_agent_map(user_id, agent_name).setdefault(thread_id, "")
return agent_session_id
@@ -352,6 +362,9 @@ class SessionsStore:
agent_name: str,
thread_id: str,
session_id: Any,
+ *,
+ vibe_agent_id: str | None = None,
+ vibe_agent_name: str | None = None,
) -> Optional[str]:
self._ensure_service()
agent_session_id = self._service.bind_agent_session(
@@ -359,6 +372,8 @@ class SessionsStore:
agent_name=agent_name,
session_anchor=thread_id,
native_session_id=session_id,
+ vibe_agent_id=vibe_agent_id,
+ vibe_agent_name=vibe_agent_name,
)
self.get_agent_map(user_id, agent_name)[thread_id] = session_id
return agent_session_id
diff --git a/config/v2_settings.py b/config/v2_settings.py
index 7f2ecbfc8..7f1840b2a 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -76,6 +76,7 @@ def _infer_user_platform(user_id: str) -> str:
@dataclass
class RoutingSettings:
+ agent_name: Optional[str] = None
agent_backend: Optional[str] = None
# OpenCode settings
opencode_agent: Optional[str] = None
@@ -146,6 +147,7 @@ class SettingsState:
def _parse_routing(payload: dict) -> RoutingSettings:
"""Parse a routing settings dict into a RoutingSettings dataclass."""
return RoutingSettings(
+ agent_name=payload.get("agent_name") or payload.get("agent"),
agent_backend=payload.get("agent_backend"),
opencode_agent=payload.get("opencode_agent"),
opencode_model=payload.get("opencode_model"),
@@ -162,6 +164,7 @@ def _parse_routing(payload: dict) -> RoutingSettings:
def _routing_to_dict(routing: RoutingSettings) -> dict:
"""Serialize a RoutingSettings to dict."""
return {
+ "agent_name": routing.agent_name,
"agent_backend": routing.agent_backend,
"opencode_agent": routing.opencode_agent,
"opencode_model": routing.opencode_model,
diff --git a/core/controller.py b/core/controller.py
index eab307802..38bd57c13 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -30,6 +30,7 @@ from core.runtime_commands import RuntimeCommandWatcher
from core.scheduled_tasks import ScheduledTaskService
from core.update_checker import UpdateChecker
from core.watches import ManagedWatchService
+from core.vibe_agents import VibeAgent, VibeAgentStore
from vibe.i18n import get_supported_languages, t as i18n_t
logger = logging.getLogger(__name__)
@@ -67,6 +68,8 @@ class Controller:
# Validate default_backend against registered agents
self._validate_default_backend()
+ self.vibe_agent_store = VibeAgentStore()
+ self.vibe_agent_store.ensure_default_agent(backend=self.agent_router.global_default)
# Setup callbacks
self._setup_callbacks()
@@ -524,6 +527,10 @@ class Controller:
await self.message_dispatcher.clear_consolidated_message_id(context, trigger_message_id)
def resolve_agent_for_context(self, context: MessageContext) -> str:
+ vibe_agent = self.resolve_vibe_agent_for_context(context, required=False)
+ if vibe_agent and vibe_agent.backend in self.agent_service.agents:
+ return vibe_agent.backend
+
"""Unified agent resolution with dynamic override support.
Priority:
@@ -552,6 +559,29 @@ class Controller:
return resolved
+ def resolve_vibe_agent_for_context(
+ self,
+ context: MessageContext,
+ *,
+ override_agent_name: Optional[str] = None,
+ required: bool = True,
+ ) -> Optional[VibeAgent]:
+ settings_key = self._get_settings_key(context)
+ settings_manager = self.get_settings_manager_for_context(context)
+ routing = settings_manager.get_channel_routing(settings_key)
+ agent_name = override_agent_name or (routing.agent_name if routing else None)
+ if not agent_name:
+ if not required:
+ return None
+ agent_name = "default"
+ try:
+ return self.vibe_agent_store.require(agent_name)
+ except Exception as exc:
+ if required:
+ raise
+ logger.warning("Scope references Vibe Agent '%s' but it cannot be resolved: %s", agent_name, exc)
+ return None
+
def get_opencode_overrides(self, context: MessageContext) -> tuple[Optional[str], Optional[str], Optional[str]]:
"""Get OpenCode agent, model, and reasoning effort overrides for this channel.
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index bde007947..1b11b0dac 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -148,7 +148,13 @@ class MessageHandler(BaseHandler):
# hold references to older contexts
self.controller.update_thread_message_id(context)
- agent_name = self.controller.resolve_agent_for_context(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,
+ )
+ agent_name = vibe_agent.backend if vibe_agent else 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
@@ -285,6 +291,12 @@ class MessageHandler(BaseHandler):
subagent_key=matched_prefix,
subagent_model=subagent_model,
subagent_reasoning_effort=subagent_reasoning_effort,
+ vibe_agent_id=vibe_agent.id if vibe_agent else None,
+ vibe_agent_name=vibe_agent.name if vibe_agent else None,
+ vibe_agent_backend=vibe_agent.backend if vibe_agent else None,
+ vibe_agent_model=vibe_agent.model if vibe_agent else None,
+ vibe_agent_reasoning_effort=vibe_agent.reasoning_effort if vibe_agent else None,
+ vibe_agent_system_prompt=vibe_agent.system_prompt if vibe_agent else None,
processing_indicator=processing_indicator,
files=processed_files,
)
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 2a452aca2..3f53d06f6 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -105,6 +105,12 @@ class SessionHandler(BaseHandler):
def get_base_session_id(self, context: MessageContext, source: str = "human") -> str:
"""Get base session ID based on platform and context (without path)"""
platform = self._get_context_platform(context)
+ payload = context.platform_specific or {}
+ session_target = payload.get("agent_session_target")
+ if isinstance(session_target, dict):
+ reserved_anchor = str(session_target.get("session_anchor") or "").strip()
+ if reserved_anchor:
+ return reserved_anchor
is_dm = bool((context.platform_specific or {}).get("is_dm", False))
if self.should_allocate_scheduled_anchor(context, source=source):
return f"{platform}_scheduled-{uuid4().hex}"
@@ -403,6 +409,7 @@ class SessionHandler(BaseHandler):
subagent_name: Optional[str] = None,
subagent_model: Optional[str] = None,
subagent_reasoning_effort: Optional[str] = None,
+ agent_system_prompt: Optional[str] = None,
) -> ClaudeSDKClient:
"""Get existing Claude session or create a new one"""
payload = context.platform_specific or {}
@@ -509,7 +516,7 @@ class SessionHandler(BaseHandler):
agent_system_prompt: Optional[str] = None
agent_allowed_tools: Optional[list] = None
agent_model: Optional[str] = None
- if effective_agent:
+ if effective_agent and agent_system_prompt is None:
agent_data = self._load_agent_file(effective_agent, working_path)
if agent_data:
agent_system_prompt = agent_data.get("prompt")
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 2199a848a..a61f12650 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -14,6 +14,7 @@ from typing import Optional
from config.platform_registry import get_platform_descriptor
from modules.im import MessageContext
from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocks
+from storage.background import SQLiteBackgroundTaskStore
from vibe.i18n import t as i18n_t
logger = logging.getLogger(__name__)
@@ -109,6 +110,16 @@ class ConsolidatedMessageDispatcher:
self._consolidated_message_ids.pop(consolidated_key, None)
self._consolidated_message_buffers.pop(consolidated_key, None)
+ def _record_suppressed_run_message(self, context: MessageContext, text: str, message_id: str) -> None:
+ payload = context.platform_specific or {}
+ run_id = str(payload.get("task_execution_id") or "").strip()
+ if not run_id:
+ return
+ try:
+ SQLiteBackgroundTaskStore().record_run_message(run_id, text=text, message_id=message_id)
+ except Exception as err:
+ logger.warning("Failed to record suppressed run output for %s: %s", run_id, err)
+
async def clear_consolidated_message_id(
self,
context: MessageContext,
@@ -323,6 +334,13 @@ class ConsolidatedMessageDispatcher:
await self._clear_consolidated_state(context)
return None
+ if (context.platform_specific or {}).get("suppress_delivery"):
+ message_id = f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}"
+ if canonical_type == "result":
+ self._record_suppressed_run_message(context, text, message_id)
+ await self._clear_consolidated_state(context)
+ return message_id
+
if canonical_type == "notify":
target_context = self._get_target_context(context)
try:
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index bf99f7d6e..4d17b4afe 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -32,6 +32,15 @@ def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
+def _json_loads(value: str | None, default: Any) -> Any:
+ if not value:
+ return default
+ try:
+ return json.loads(value)
+ except (TypeError, ValueError):
+ return default
+
+
def _path_signature(path: Path) -> Optional[tuple[int, int, int]]:
try:
stat = path.stat()
@@ -96,6 +105,8 @@ class ResolvedSessionIdTarget:
agent_variant: str
native_session_id: str
workdir: Optional[str] = None
+ session_anchor: Optional[str] = None
+ suppress_delivery: bool = False
def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None) -> ResolvedSessionIdTarget:
@@ -117,6 +128,8 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None
scopes.c.platform,
scopes.c.scope_type,
scopes.c.native_id,
+ scopes.c.metadata_json.label("scope_metadata_json"),
+ agent_sessions.c.metadata_json.label("session_metadata_json"),
)
.join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True)
.where(agent_sessions.c.id == raw)
@@ -137,6 +150,12 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None
anchor = str(row["session_anchor"] or "")
thread_id = _thread_id_from_session_anchor(anchor, platform=platform, scope_id=scope_id)
+ session_metadata = _json_loads(row["session_metadata_json"], {})
+ scope_metadata = _json_loads(row["scope_metadata_json"], {})
+ suppress_delivery = bool(
+ (isinstance(session_metadata, dict) and session_metadata.get("no_delivery"))
+ or (isinstance(scope_metadata, dict) and scope_metadata.get("no_delivery"))
+ )
return ResolvedSessionIdTarget(
session_id=raw,
session_key=ParsedSessionKey(
@@ -149,6 +168,8 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None
agent_variant=str(row["agent_variant"] or ""),
native_session_id=str(row["native_session_id"] or ""),
workdir=row["workdir"],
+ session_anchor=str(row["session_anchor"] or ""),
+ suppress_delivery=suppress_delivery,
)
@@ -192,6 +213,8 @@ class ScheduledTask:
session_key: str
prompt: str
schedule_type: str
+ agent_name: Optional[str] = None
+ session_policy: Optional[str] = None
session_id: Optional[str] = None
post_to: Optional[str] = None
deliver_key: Optional[str] = None
@@ -215,6 +238,8 @@ class ScheduledTask:
session_key=str(payload.get("session_key") or ""),
prompt=str(payload.get("prompt") or ""),
schedule_type=str(payload.get("schedule_type") or ""),
+ agent_name=(str(payload["agent_name"]).strip() if payload.get("agent_name") else None),
+ session_policy=(str(payload["session_policy"]).strip() if payload.get("session_policy") else None),
session_id=(str(payload["session_id"]).strip() if payload.get("session_id") else None),
post_to=payload.get("post_to"),
deliver_key=payload.get("deliver_key"),
@@ -240,6 +265,13 @@ class TaskExecutionRequest:
post_to: Optional[str] = None
deliver_key: Optional[str] = None
prompt: Optional[str] = None
+ message: Optional[str] = None
+ agent_name: Optional[str] = None
+ agent_id: Optional[str] = None
+ agent_backend: Optional[str] = None
+ model: Optional[str] = None
+ reasoning_effort: Optional[str] = None
+ session_policy: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@@ -256,6 +288,13 @@ class TaskExecutionRequest:
post_to=payload.get("post_to"),
deliver_key=payload.get("deliver_key"),
prompt=payload.get("prompt"),
+ message=payload.get("message") or payload.get("prompt"),
+ agent_name=payload.get("agent_name"),
+ agent_id=payload.get("agent_id"),
+ agent_backend=payload.get("agent_backend"),
+ model=payload.get("model"),
+ reasoning_effort=payload.get("reasoning_effort"),
+ session_policy=payload.get("session_policy"),
)
@@ -348,6 +387,8 @@ class ScheduledTaskStore:
session_id: Optional[str] = None,
prompt: str,
schedule_type: str,
+ agent_name: Optional[str] = None,
+ session_policy: Optional[str] = None,
post_to: Optional[str] = None,
deliver_key: Optional[str] = None,
cron: Optional[str] = None,
@@ -361,6 +402,8 @@ class ScheduledTaskStore:
session_id=session_id,
prompt=prompt,
schedule_type=schedule_type,
+ agent_name=agent_name,
+ session_policy=session_policy or ("existing" if session_id or session_key else None),
post_to=post_to,
deliver_key=deliver_key,
cron=cron,
@@ -403,6 +446,8 @@ class ScheduledTaskStore:
run_at: Optional[str],
timezone_name: str,
session_id: Optional[str] = None,
+ agent_name: Optional[str] = None,
+ session_policy: Optional[str] = None,
) -> ScheduledTask:
task = self._tasks[task_id]
task.name = name
@@ -410,6 +455,10 @@ class ScheduledTaskStore:
task.session_id = session_id
task.prompt = prompt
task.schedule_type = schedule_type
+ task.agent_name = agent_name
+ if session_policy is None:
+ session_policy = task.session_policy or ("existing" if session_id or session_key else None)
+ task.session_policy = session_policy
task.post_to = post_to
task.deliver_key = deliver_key
task.cron = cron
@@ -511,6 +560,8 @@ class TaskExecutionStore:
prompt: str,
post_to: Optional[str] = None,
deliver_key: Optional[str] = None,
+ agent_name: Optional[str] = None,
+ session_policy: Optional[str] = None,
) -> TaskExecutionRequest:
return self.enqueue(
TaskExecutionRequest(
@@ -521,6 +572,43 @@ class TaskExecutionStore:
post_to=post_to,
deliver_key=deliver_key,
prompt=prompt,
+ message=prompt,
+ agent_name=agent_name,
+ session_policy=session_policy,
+ )
+ )
+
+ def enqueue_agent_run(
+ self,
+ *,
+ message: str,
+ agent_name: Optional[str] = None,
+ agent_id: Optional[str] = None,
+ agent_backend: Optional[str] = None,
+ model: Optional[str] = None,
+ reasoning_effort: Optional[str] = None,
+ session_policy: Optional[str] = None,
+ session_key: str = "",
+ session_id: Optional[str] = None,
+ post_to: Optional[str] = None,
+ deliver_key: Optional[str] = None,
+ ) -> TaskExecutionRequest:
+ return self.enqueue(
+ TaskExecutionRequest(
+ id=uuid4().hex[:12],
+ request_type="agent_run",
+ session_key=session_key,
+ session_id=session_id,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ prompt=message,
+ message=message,
+ agent_name=agent_name,
+ agent_id=agent_id,
+ agent_backend=agent_backend,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ session_policy=session_policy,
)
)
@@ -529,7 +617,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"}
+ if item.get("request_type") in {"task_run", "hook_send", "agent_run"}
]
self._ensure_dirs()
requests: list[TaskExecutionRequest] = []
@@ -544,6 +632,42 @@ class TaskExecutionStore:
requests.append(TaskExecutionRequest.from_dict(payload))
return sorted(requests, key=lambda item: (item.created_at, item.id))
+ def list_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:
+ if self._sqlite is not None:
+ return self._sqlite.list_runs(status=status)
+ runs: list[dict[str, Any]] = []
+ for state, directory in {
+ "pending": self.pending_dir,
+ "processing": self.processing_dir,
+ "completed": self.completed_dir,
+ }.items():
+ if status and status != state:
+ continue
+ if not directory.exists():
+ continue
+ for path in directory.glob("*.json"):
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ continue
+ if isinstance(payload, dict):
+ payload.setdefault("status", state)
+ runs.append(payload)
+ return sorted(runs, key=lambda item: (item.get("created_at") or "", item.get("id") or ""))
+
+ def get_run(self, run_id: str) -> Optional[dict[str, Any]]:
+ if self._sqlite is not None:
+ return self._sqlite.get_run(run_id)
+ for item in self.list_runs():
+ if item.get("id") == run_id:
+ return item
+ return None
+
+ def cancel_run(self, run_id: str) -> bool:
+ if self._sqlite is not None:
+ return self._sqlite.cancel_run(run_id)
+ return False
+
def claim(self, request_id: str) -> Optional[TaskExecutionRequest]:
if self._sqlite is not None:
now = _utc_now_iso()
@@ -791,14 +915,36 @@ class ScheduledTaskService:
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=request.session_key,
- session_id=request.session_id,
+ 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",
+ 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}")
@@ -828,16 +974,25 @@ class ScheduledTaskService:
disable_one_shot: bool,
) -> Optional[str]:
error: Optional[str] = None
+ session_id = task.session_id
+ session_key = task.session_key
try:
+ if task.session_policy == "create_per_run":
+ session_id = self._reserve_runtime_session(
+ agent_name=task.agent_name,
+ deliver_key=task.deliver_key,
+ )
+ session_key = ""
error = await self._execute_request(
- session_key=task.session_key,
- session_id=task.session_id,
+ session_key=session_key,
+ session_id=session_id,
post_to=task.post_to,
deliver_key=task.deliver_key,
prompt=task.prompt,
execution_id=execution_id,
task_id=task.id,
trigger_kind="scheduled",
+ agent_name=task.agent_name,
)
except asyncio.CancelledError:
self.reconcile_jobs()
@@ -849,6 +1004,41 @@ class ScheduledTaskService:
self.reconcile_jobs()
return error
+ def _reserve_runtime_session(self, *, agent_name: Optional[str], deliver_key: Optional[str]) -> str:
+ if not deliver_key:
+ raise ValueError("session creation requires deliver_key")
+ from config import paths as config_paths
+ from core.vibe_agents import VibeAgentStore
+ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
+ from storage.sessions_service import SQLiteSessionsService
+
+ target = parse_session_key(deliver_key)
+ ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(config_paths.get_state_dir()))
+ agent_store = VibeAgentStore()
+ try:
+ agent = agent_store.get(agent_name) if agent_name else None
+ finally:
+ agent_store.close()
+ if agent_name and agent is None:
+ raise ValueError(f"agent '{agent_name}' not found")
+ agent_backend = agent.backend if agent else self.controller.agent_router.global_default
+ service = SQLiteSessionsService(config_paths.get_sqlite_state_path())
+ try:
+ session_id = service.reserve_agent_session(
+ scope_key=target.session_scope,
+ agent_backend=agent_backend,
+ session_anchor=f"{target.platform}_agent-{uuid4().hex[:12]}",
+ agent_id=agent.id if agent else None,
+ agent_name=agent.name if agent else None,
+ model=agent.model if agent else None,
+ reasoning_effort=agent.reasoning_effort if agent else None,
+ )
+ finally:
+ service.close()
+ if not session_id:
+ raise ValueError("failed to reserve runtime session")
+ return session_id
+
async def _execute_request(
self,
@@ -861,6 +1051,7 @@ class ScheduledTaskService:
task_id: Optional[str] = None,
trigger_kind: str,
session_id: Optional[str] = None,
+ agent_name: Optional[str] = None,
) -> Optional[str]:
target_info = resolve_session_id_target(session_id) if session_id else None
target = target_info.session_key if target_info else parse_session_key(session_key or "")
@@ -876,6 +1067,7 @@ class ScheduledTaskService:
task_id=task_id,
trigger_kind=trigger_kind,
session_id=session_id,
+ agent_name=agent_name,
target_info=target_info,
)
return await self.controller.message_handler.handle_scheduled_message(
@@ -893,6 +1085,7 @@ class ScheduledTaskService:
task_id: Optional[str] = None,
trigger_kind: str = "scheduled",
session_id: Optional[str] = None,
+ agent_name: Optional[str] = None,
target_info: Optional[ResolvedSessionIdTarget] = None,
) -> MessageContext:
platform = target.platform
@@ -935,6 +1128,8 @@ class ScheduledTaskService:
"scheduled_delivery_alias": delivery_strategy,
"task_execution_id": execution_id,
"task_trigger_kind": trigger_kind,
+ "vibe_agent_name": agent_name,
+ "suppress_delivery": bool(target_info.suppress_delivery) if target_info else False,
"agent_session_target": (
{
"id": target_info.session_id,
@@ -942,6 +1137,8 @@ class ScheduledTaskService:
"agent_variant": target_info.agent_variant,
"native_session_id": target_info.native_session_id,
"workdir": target_info.workdir,
+ "session_anchor": target_info.session_anchor,
+ "suppress_delivery": target_info.suppress_delivery,
}
if target_info
else None
@@ -1060,6 +1257,8 @@ 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 == "agent_run":
+ return f"agent_run:{execution_id}"
if task_id:
return f"scheduled:{task_id}:{execution_id}"
return f"scheduled:{execution_id}"
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
index 9695e8645..a0e60f79e 100644
--- a/core/system_prompt_injection.py
+++ b/core/system_prompt_injection.py
@@ -73,7 +73,7 @@ _SCHEDULED_TASKS_PROMPT = """\
## 3. Scheduled tasks, watches, and hooks
Use `vibe task add` for saved work that should run later on a schedule or at one exact time.
Use `vibe watch add` for managed background waiters that should keep running until a condition is met and then send a follow-up.
-Use `vibe hook send --session-id ... --prompt ...` for one-shot asynchronous sends without saving a task or watch.
+Use `vibe agent run --async --session-id ... --message ...` for one-shot asynchronous sends without saving a task or watch.
Current conversation targeting:
- Current session id: `{default_session_id}`
@@ -85,8 +85,8 @@ Rules:
- Use `vibe watch list`, `vibe watch show`, `vibe watch pause`, `vibe watch resume`, and `vibe watch remove` to manage background work after creation.
- Prefer `vibe watch add` over ad-hoc `nohup` or shell-detached jobs when the user wants a managed background task.
- If `--timezone` is omitted, the task uses the local system timezone at creation time.
-- Use `--prompt "..."` or `--prompt-file <path>` for task and hook content. Use `--prefix "..."` on watches for the follow-up instruction that is prepended before waiter stdout; when both exist, Vibe Remote joins them with a blank line.
-- If this is your first time using these commands, read `vibe task add --help`, `vibe watch add --help`, or `vibe hook send --help` before creating anything. The help text and relevant skills explain not just the argument syntax but also runtime effects such as how follow-up messages are built and how tasks or watches are stored and managed.
+- Use `--message "..."` or `--message-file <path>` for task and agent-run content. Use `--prefix "..."` on watches for the follow-up instruction that is prepended before waiter stdout; when both exist, Vibe Remote joins them with a blank line.
+- If this is your first time using these commands, read `vibe task add --help`, `vibe watch add --help`, or `vibe agent run --help` before creating anything. The help text and relevant skills explain not just the argument syntax but also runtime effects such as how follow-up messages are built and how tasks or watches are stored and managed.
"""
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
new file mode 100644
index 000000000..afbfa2531
--- /dev/null
+++ b/core/vibe_agents.py
@@ -0,0 +1,332 @@
+"""Vibe-owned Agent catalog and import helpers."""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import asdict, dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Iterable, Optional
+from uuid import uuid4
+
+import yaml
+from sqlalchemy import select
+from sqlalchemy.exc import IntegrityError
+
+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
+
+DEFAULT_AGENT_NAME = "default"
+SUPPORTED_AGENT_BACKENDS = {"codex", "claude", "opencode"}
+_UNSET = object()
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def normalize_agent_name(name: str) -> str:
+ normalized = re.sub(r"[^a-z0-9_-]+", "-", str(name or "").strip().lower()).strip("-_")
+ if not normalized:
+ raise ValueError("agent name is required")
+ return normalized
+
+
+def validate_agent_backend(backend: str) -> str:
+ value = str(backend or "").strip().lower()
+ if value not in SUPPORTED_AGENT_BACKENDS:
+ supported = ", ".join(sorted(SUPPORTED_AGENT_BACKENDS))
+ raise ValueError(f"unsupported agent backend: {backend}. Supported backends: {supported}")
+ return value
+
+
+def _json_dumps(value: Any) -> str:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
+
+
+def _json_loads(value: str | None, default: Any) -> Any:
+ if not value:
+ return default
+ try:
+ return json.loads(value)
+ except (TypeError, ValueError):
+ return default
+
+
+@dataclass(frozen=True)
+class VibeAgent:
+ id: str
+ name: str
+ normalized_name: str
+ backend: str
+ description: Optional[str] = None
+ model: Optional[str] = None
+ reasoning_effort: Optional[str] = None
+ system_prompt: Optional[str] = None
+ source: str = "user"
+ source_ref: Optional[str] = None
+ metadata: dict[str, Any] = field(default_factory=dict)
+ created_at: str = field(default_factory=_utc_now_iso)
+ updated_at: str = field(default_factory=_utc_now_iso)
+
+ def to_dict(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+@dataclass(frozen=True)
+class AgentImportCandidate:
+ name: str
+ backend: str
+ description: Optional[str] = None
+ model: Optional[str] = None
+ reasoning_effort: Optional[str] = None
+ system_prompt: Optional[str] = None
+ source: str = "import"
+ source_ref: Optional[str] = None
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class AgentImportResult:
+ imported: list[VibeAgent]
+ skipped: list[dict[str, Any]]
+
+
+class VibeAgentStore:
+ def __init__(self, db_path: Optional[Path] = None):
+ self.db_path = db_path or paths.get_sqlite_state_path()
+ self.db_path.parent.mkdir(parents=True, exist_ok=True)
+ if db_path is None:
+ ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
+ else:
+ run_migrations(self.db_path)
+ self.engine = create_sqlite_engine(self.db_path)
+ self._probe = SqliteInvalidationProbe(self.engine)
+
+ def close(self) -> None:
+ self._probe.close()
+ self.engine.dispose()
+
+ def maybe_reload(self) -> bool:
+ return self._probe.has_external_write()
+
+ def list_agents(self) -> list[VibeAgent]:
+ with self.engine.connect() as conn:
+ rows = conn.execute(select(agents).order_by(agents.c.name)).mappings()
+ return [self._from_row(row) for row in rows]
+
+ def get(self, name: str) -> Optional[VibeAgent]:
+ normalized = normalize_agent_name(name)
+ with self.engine.connect() as conn:
+ row = conn.execute(
+ select(agents).where(agents.c.normalized_name == normalized).limit(1)
+ ).mappings().first()
+ return self._from_row(row) if row else None
+
+ def require(self, name: str) -> VibeAgent:
+ agent = self.get(name)
+ if agent is None:
+ raise ValueError(f"agent '{name}' not found")
+ return agent
+
+ def create(
+ self,
+ *,
+ name: str,
+ backend: str,
+ description: Optional[str] = None,
+ model: Optional[str] = None,
+ reasoning_effort: Optional[str] = None,
+ system_prompt: Optional[str] = None,
+ source: str = "user",
+ source_ref: Optional[str] = None,
+ metadata: Optional[dict[str, Any]] = None,
+ ) -> VibeAgent:
+ normalized = normalize_agent_name(name)
+ now = _utc_now_iso()
+ agent = VibeAgent(
+ id=uuid4().hex[:12],
+ name=str(name).strip(),
+ normalized_name=normalized,
+ backend=validate_agent_backend(backend),
+ description=_clean_optional(description),
+ model=_clean_optional(model),
+ reasoning_effort=_clean_optional(reasoning_effort),
+ system_prompt=_clean_optional(system_prompt),
+ source=str(source or "user"),
+ source_ref=_clean_optional(source_ref),
+ metadata=dict(metadata or {}),
+ created_at=now,
+ updated_at=now,
+ )
+ try:
+ with self.engine.begin() as conn:
+ conn.execute(agents.insert().values(**self._values(agent)))
+ except IntegrityError as exc:
+ raise ValueError(f"agent '{name}' already exists") from exc
+ return agent
+
+ def update(
+ self,
+ name: str,
+ *,
+ description: Any = _UNSET,
+ model: Any = _UNSET,
+ reasoning_effort: Any = _UNSET,
+ system_prompt: Any = _UNSET,
+ metadata: Any = _UNSET,
+ ) -> VibeAgent:
+ existing = self.require(name)
+ values: dict[str, Any] = {"updated_at": _utc_now_iso()}
+ if description is not _UNSET:
+ values["description"] = _clean_optional(description)
+ if model is not _UNSET:
+ values["model"] = _clean_optional(model)
+ if reasoning_effort is not _UNSET:
+ values["reasoning_effort"] = _clean_optional(reasoning_effort)
+ if system_prompt is not _UNSET:
+ values["system_prompt"] = _clean_optional(system_prompt)
+ if metadata is not _UNSET:
+ values["metadata_json"] = _json_dumps(dict(metadata or {}))
+ with self.engine.begin() as conn:
+ conn.execute(agents.update().where(agents.c.id == existing.id).values(**values))
+ return self.require(name)
+
+ def remove(self, name: str) -> bool:
+ normalized = normalize_agent_name(name)
+ with self.engine.begin() as conn:
+ result = conn.execute(agents.delete().where(agents.c.normalized_name == normalized))
+ return bool(result.rowcount)
+
+ def import_candidates(self, candidates: Iterable[AgentImportCandidate]) -> AgentImportResult:
+ imported: list[VibeAgent] = []
+ skipped: list[dict[str, Any]] = []
+ for candidate in candidates:
+ try:
+ if self.get(candidate.name):
+ skipped.append({"name": candidate.name, "reason": "name_conflict"})
+ continue
+ imported.append(
+ self.create(
+ name=candidate.name,
+ backend=candidate.backend,
+ description=candidate.description,
+ model=candidate.model,
+ reasoning_effort=candidate.reasoning_effort,
+ system_prompt=candidate.system_prompt,
+ source=candidate.source,
+ source_ref=candidate.source_ref,
+ metadata=candidate.metadata,
+ )
+ )
+ except Exception as exc:
+ skipped.append({"name": candidate.name, "reason": "invalid", "error": str(exc)})
+ return AgentImportResult(imported=imported, skipped=skipped)
+
+ def ensure_default_agent(self, *, backend: str = "claude") -> VibeAgent:
+ existing = self.get(DEFAULT_AGENT_NAME)
+ if existing:
+ return existing
+ return self.create(
+ name=DEFAULT_AGENT_NAME,
+ backend=backend,
+ description="Default Vibe Remote agent.",
+ source="builtin",
+ metadata={"builtin": True},
+ )
+
+ @staticmethod
+ def _from_row(row: Any) -> VibeAgent:
+ return VibeAgent(
+ id=row["id"],
+ name=row["name"],
+ normalized_name=row["normalized_name"],
+ backend=row["backend"],
+ description=row["description"],
+ model=row["model"],
+ reasoning_effort=row["reasoning_effort"],
+ system_prompt=row["system_prompt"],
+ source=row["source"],
+ source_ref=row["source_ref"],
+ metadata=_json_loads(row["metadata_json"], {}),
+ created_at=row["created_at"],
+ updated_at=row["updated_at"],
+ )
+
+ @staticmethod
+ def _values(agent: VibeAgent) -> dict[str, Any]:
+ return {
+ "id": agent.id,
+ "name": agent.name,
+ "normalized_name": agent.normalized_name,
+ "description": agent.description,
+ "backend": agent.backend,
+ "model": agent.model,
+ "reasoning_effort": agent.reasoning_effort,
+ "system_prompt": agent.system_prompt,
+ "source": agent.source,
+ "source_ref": agent.source_ref,
+ "metadata_json": _json_dumps(agent.metadata),
+ "created_at": agent.created_at,
+ "updated_at": agent.updated_at,
+ }
+
+
+def parse_agent_file(path: Path, *, backend: str) -> AgentImportCandidate:
+ backend = validate_agent_backend(backend)
+ raw = path.read_text(encoding="utf-8")
+ header: dict[str, Any] = {}
+ body = raw.strip()
+ if raw.startswith("---"):
+ parts = raw.split("---", 2)
+ if len(parts) >= 3:
+ header = yaml.safe_load(parts[1]) or {}
+ body = parts[2].strip()
+ name = str(header.get("name") or path.stem).strip()
+ description = header.get("description")
+ model = header.get("model")
+ reasoning_effort = header.get("reasoning_effort") or header.get("reasoningEffort")
+ metadata = {
+ key: value
+ for key, value in header.items()
+ if key not in {"name", "description", "model", "reasoning_effort", "reasoningEffort"}
+ }
+ return AgentImportCandidate(
+ name=name,
+ backend=backend,
+ description=str(description).strip() if description else None,
+ model=str(model).strip() if model else None,
+ reasoning_effort=str(reasoning_effort).strip() if reasoning_effort else None,
+ system_prompt=body or None,
+ source="file",
+ source_ref=str(path),
+ metadata=metadata,
+ )
+
+
+def iter_global_agent_files(source: str) -> list[tuple[Path, str]]:
+ source_key = str(source or "").strip().lower()
+ home = Path.home()
+ if source_key == "claude":
+ return [(path, "claude") for path in sorted((home / ".claude" / "agents").glob("*.md"))]
+ if source_key == "codex":
+ search_dirs = [home / ".codex" / "agents"]
+ return [(path, "codex") for directory in search_dirs for path in sorted(directory.glob("*.md"))]
+ if source_key == "opencode":
+ search_dirs = [
+ home / ".config" / "opencode" / "agent",
+ home / ".config" / "opencode" / "agents",
+ ]
+ return [(path, "opencode") for directory in search_dirs for path in sorted(directory.glob("*.md"))]
+ raise ValueError("--from must be one of: claude, codex, opencode")
+
+
+def _clean_optional(value: Any) -> Optional[str]:
+ if value is None:
+ return None
+ text = str(value).strip()
+ return text or None
diff --git a/core/watches.py b/core/watches.py
index 1e6042561..63e6e9d29 100644
--- a/core/watches.py
+++ b/core/watches.py
@@ -47,6 +47,8 @@ class ManagedWatch:
name: Optional[str]
session_key: str
session_id: Optional[str] = None
+ agent_name: Optional[str] = None
+ session_policy: Optional[str] = None
command: list[str] = field(default_factory=list)
shell_command: Optional[str] = None
prefix: Optional[str] = None
@@ -77,6 +79,8 @@ class ManagedWatch:
name=(str(payload["name"]).strip() if payload.get("name") is not None else None) or None,
session_key=str(payload.get("session_key") or ""),
session_id=(str(payload["session_id"]).strip() if payload.get("session_id") else None),
+ agent_name=(str(payload["agent_name"]).strip() if payload.get("agent_name") else None),
+ session_policy=(str(payload["session_policy"]).strip() if payload.get("session_policy") else None),
command=list(payload.get("command") or []),
shell_command=(str(payload["shell_command"]).strip() if payload.get("shell_command") else None) or None,
prefix=(str(payload["prefix"]).strip() if payload.get("prefix") else None) or None,
@@ -197,12 +201,16 @@ class ManagedWatchStore:
post_to: Optional[str],
deliver_key: Optional[str],
session_id: Optional[str] = None,
+ agent_name: Optional[str] = None,
+ session_policy: Optional[str] = None,
) -> ManagedWatch:
watch = ManagedWatch(
id=uuid4().hex[:12],
name=name,
session_key=session_key,
session_id=session_id,
+ agent_name=agent_name,
+ session_policy=session_policy or ("existing" if session_id or session_key else None),
command=command,
shell_command=shell_command,
prefix=prefix,
@@ -255,11 +263,17 @@ class ManagedWatchStore:
retry_delay_seconds: float,
post_to: Optional[str],
deliver_key: Optional[str],
+ agent_name: Optional[str] = None,
+ session_policy: Optional[str] = None,
) -> ManagedWatch:
watch = self._watches[watch_id]
watch.name = name
watch.session_key = session_key
watch.session_id = session_id
+ watch.agent_name = agent_name
+ if session_policy is None:
+ session_policy = watch.session_policy or ("existing" if session_id or session_key else None)
+ watch.session_policy = session_policy
watch.command = command
watch.shell_command = shell_command
watch.prefix = prefix
@@ -601,6 +615,8 @@ class ManagedWatchService:
post_to=watch.post_to,
deliver_key=watch.deliver_key,
prompt=final_prompt,
+ agent_name=watch.agent_name,
+ session_policy=watch.session_policy,
)
def _enqueue_failure_hook(self, watch: ManagedWatch, *, exit_code: int, error_text: str) -> None:
diff --git a/docs/CLI.md b/docs/CLI.md
index 4e45a90b8..26e847918 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -161,7 +161,7 @@ vibe screenshot --json
Create, inspect, update, run, pause, resume, or remove scheduled tasks.
```bash
-vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --prompt 'Share the hourly summary.'
+vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'
vibe task list --brief
vibe task update <task-id> --cron '*/30 * * * *'
vibe task run <task-id>
@@ -174,21 +174,24 @@ Use `vibe task add --help` and `vibe task update --help` for the full command su
- `--post-to channel` to publish into the parent channel while keeping thread context
- `--deliver-key` for an explicit delivery target
- `--cron` and `--at` scheduling
-- `--name`, `--timezone`, and prompt file support
+- `--name`, `--timezone`, and message file support
`--session-key` remains accepted for older scripts, but new tasks should use
the Agent Session ID shown in the active Vibe Remote prompt.
-### `vibe hook send`
+### `vibe agent run`
-Queue one asynchronous turn without storing a scheduled task definition.
+Run an Agent directly. Use `--async` for a queued background run without storing
+a scheduled task definition.
```bash
-vibe hook send --session-id sesk8m4q2p7x --prompt 'The export finished. Share the summary.'
-vibe hook send --session-id sesk8m4q2p7x --post-to channel --prompt 'Share the benchmark result in the channel.'
+vibe agent run --agent release-reviewer --message 'Review the latest deployment result.'
+vibe agent run --async --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
+vibe agent run --async --create-session --deliver-key slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'
```
-Use this when you want one delayed or background follow-up without persisting a task in `scheduled_tasks.json`.
+`vibe hook send` is kept only as a deprecated compatibility entrypoint. New
+automation should use `vibe agent run`.
### `vibe watch`
@@ -223,7 +226,7 @@ including `--timeout` (per-cycle timeout in seconds), `--lifetime-timeout`
(total wall-clock limit), `--forever`, `--retry-exit-code`, `--retry-delay`,
`--post-to channel`, `--deliver-key`, and `--name`. Watches share
`--session-id`, `--post-to`, and `--deliver-key` semantics with `vibe task`
-and `vibe hook send`. `vibe watch remove` hides the watch from management
+and `vibe agent run`. `vibe watch remove` hides the watch from management
views while preserving existing run history in SQLite. Prefer `vibe watch`
over ad-hoc `nohup` jobs when the
user wants a managed background task with a guaranteed follow-up message.
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index a0949ab45..304a03e24 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -146,7 +146,7 @@ vibe screenshot --json
创建、查看、更新、立即执行、暂停、恢复或删除定时任务。
```bash
-vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --prompt 'Share the hourly summary.'
+vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'
vibe task list --brief
vibe task update <task-id> --cron '*/30 * * * *'
vibe task run <task-id>
@@ -159,21 +159,23 @@ vibe task remove <task-id>
- 用 `--post-to channel` 在保留 thread 上下文的同时把消息发到父频道
- 用 `--deliver-key` 指定显式投递目标
- 用 `--cron` / `--at` 控制定时方式
-- 以及 `--name`、`--timezone`、`--prompt-file` 等参数
+- 以及 `--name`、`--timezone`、`--message-file` 等参数
`--session-key` 仍兼容旧脚本,但新任务应使用当前 Vibe Remote prompt
里展示的 Agent Session ID。
-### `vibe hook send`
+### `vibe agent run`
-队列化一次异步 turn,不会把任务定义持久化到 `scheduled_tasks.json`。
+直接运行一个 Agent。加 `--async` 时会队列化一次后台 run,但不会创建持久化任务定义。
```bash
-vibe hook send --session-id sesk8m4q2p7x --prompt 'The export finished. Share the summary.'
-vibe hook send --session-id sesk8m4q2p7x --post-to channel --prompt 'Share the benchmark result in the channel.'
+vibe agent run --agent release-reviewer --message 'Review the latest deployment result.'
+vibe agent run --async --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
+vibe agent run --async --create-session --deliver-key slack::channel::C999 --agent release-reviewer --message 'Post the deployment summary.'
```
-适合“只异步补发一次消息,不想保存成定时任务”的场景。
+`vibe hook send` 仅作为 deprecated 兼容入口保留。新的自动化入口应使用
+`vibe agent run`。
### `vibe version`
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index 4712819a9..e34112439 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -528,8 +528,9 @@ The `vibe` executable controls the local service and async automation features.
| `vibe version` | Show installed version |
| `vibe check-update` | Check for new version |
| `vibe upgrade` | Upgrade to latest version |
+| `vibe agent ...` | Manage Vibe Agents and run them directly |
+| `vibe runs ...` | Inspect and cancel Agent Run records |
| `vibe task ...` | Manage scheduled tasks |
-| `vibe hook send ...` | Queue one async hook without persisting a task |
### `vibe`
@@ -693,19 +694,22 @@ vibe upgrade
### `vibe task add`
```bash
-vibe task add --session-id <session_id> (--cron <expr> | --at <timestamp>) (--prompt <text> | --prompt-file <file>) [options]
+vibe task add (--session-id <session_id> | --create-session | --create-session-per-run) (--cron <expr> | --at <timestamp>) (--message <text> | --message-file <file>) [options]
```
Important options:
- `--name`
-- `--session-id` required for new tasks
+- `--session-id`
+- `--create-session`
+- `--create-session-per-run`
+- `--agent`
- `--post-to {thread,channel}`
- `--deliver-key`
- `--cron`
- `--at`
-- `--prompt`
-- `--prompt-file`
+- `--message`
+- `--message-file`
- `--timezone`
### `vibe task update`
@@ -719,13 +723,16 @@ Important options:
- `--name`
- `--clear-name`
- `--session-id`
+- `--create-session`
+- `--create-session-per-run`
+- `--agent`
- `--post-to {thread,channel}`
- `--deliver-key`
- `--reset-delivery`
- `--cron`
- `--at`
-- `--prompt`
-- `--prompt-file`
+- `--message`
+- `--message-file`
- `--timezone`
### `vibe task list`
@@ -764,23 +771,57 @@ vibe task run <task_id>
vibe task remove <task_id>
```
-## 5.3 `vibe hook send`
+## 5.3 `vibe agent`
+
+`vibe agent` manages Vibe-owned Agent definitions and runs Agents directly.
-Queue one asynchronous turn without creating a stored task definition.
+Agent definitions are globally named. `name` and `backend` are immutable after
+creation; description, model, reasoning effort, and system prompt can be edited.
-### Syntax
+### Supported subcommands
+
+| Subcommand | Purpose |
+| --- | --- |
+| `vibe agent list` | List Agents |
+| `vibe agent show <name>` | Show one Agent |
+| `vibe agent create` | Create an Agent |
+| `vibe agent update <name>` | Edit mutable Agent fields |
+| `vibe agent remove <name>` | Remove an Agent |
+| `vibe agent import` | Import global Agents or a portable Agent file |
+| `vibe agent run` | Run an Agent once |
+
+### `vibe agent run`
```bash
-vibe hook send --session-id <session_id> (--prompt <text> | --prompt-file <file>) [options]
+vibe agent run (--session-id <session_id> | --create-session)? (--message <text> | --message-file <file>) [options]
```
Important options:
-- `--session-id` required for new hooks
-- `--post-to {thread,channel}`
+- `--agent`
+- `--session-id`
+- `--create-session`
- `--deliver-key`
-- `--prompt`
-- `--prompt-file`
+- `--async`
+- `--message`
+- `--message-file`
+
+If neither `--session-id` nor `--create-session` is provided, the run uses a
+private no-delivery session and is best suited for sub-agent style calls.
+`--deliver-key` is only meaningful with `--create-session`.
+
+## 5.4 `vibe runs`
+
+`vibe runs` inspects concrete Agent Run records produced by tasks, watches, or
+direct Agent Run calls.
+
+### Supported subcommands
+
+| Subcommand | Purpose |
+| --- | --- |
+| `vibe runs list` | List recent runs |
+| `vibe runs show <run_id>` | Show one run |
+| `vibe runs cancel <run_id>` | Request cancellation |
## 6. Recommended Mental Model
@@ -793,7 +834,7 @@ Use the right command family for the job:
- Want to control the local daemon or troubleshoot installation:
- use `vibe`, `vibe status`, `vibe doctor`, `vibe upgrade`
- Want asynchronous automation:
- - use `vibe task ...` or `vibe hook send ...`
+ - use `vibe task ...`, `vibe watch ...`, or `vibe agent run --async ...`
## 7. Quick Examples
@@ -816,5 +857,5 @@ vibe
vibe status
vibe doctor
vibe task list --brief
-vibe hook send --session-id sesk8m4q2p7x --prompt 'Share the latest build summary.'
+vibe agent run --async --session-id sesk8m4q2p7x --message 'Share the latest build summary.'
```
diff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.md
index a802c5559..9c4428d1c 100644
--- a/docs/COMMANDS_ZH.md
+++ b/docs/COMMANDS_ZH.md
@@ -507,8 +507,9 @@ bind vr-a3x9k2
| `vibe version` | 查看当前版本 |
| `vibe check-update` | 检查是否有新版本 |
| `vibe upgrade` | 升级到最新版 |
+| `vibe agent ...` | 管理 Vibe Agent,并直接运行 Agent |
+| `vibe runs ...` | 查看和取消 Agent Run 记录 |
| `vibe task ...` | 管理定时任务 |
-| `vibe hook send ...` | 队列化一次异步 hook,不保存任务定义 |
### `vibe`
@@ -672,19 +673,22 @@ vibe upgrade
### `vibe task add`
```bash
-vibe task add --session-id <session_id> (--cron <表达式> | --at <时间戳>) (--prompt <文本> | --prompt-file <文件>) [options]
+vibe task add (--session-id <session_id> | --create-session | --create-session-per-run) (--cron <表达式> | --at <时间戳>) (--message <文本> | --message-file <文件>) [options]
```
重要参数:
- `--name`
-- `--session-id`,新任务应使用 Agent Session ID
+- `--session-id`
+- `--create-session`
+- `--create-session-per-run`
+- `--agent`
- `--post-to {thread,channel}`
- `--deliver-key`
- `--cron`
- `--at`
-- `--prompt`
-- `--prompt-file`
+- `--message`
+- `--message-file`
- `--timezone`
### `vibe task update`
@@ -698,13 +702,16 @@ vibe task update <task_id> [options]
- `--name`
- `--clear-name`
- `--session-id`
+- `--create-session`
+- `--create-session-per-run`
+- `--agent`
- `--post-to {thread,channel}`
- `--deliver-key`
- `--reset-delivery`
- `--cron`
- `--at`
-- `--prompt`
-- `--prompt-file`
+- `--message`
+- `--message-file`
- `--timezone`
### `vibe task list`
@@ -743,23 +750,56 @@ vibe task run <task_id>
vibe task remove <task_id>
```
-## 5.3 `vibe hook send`
+## 5.3 `vibe agent`
+
+`vibe agent` 用来管理 Vibe 自己的一等 Agent 定义,并直接运行 Agent。
-队列化一次异步 turn,但不会创建持久化任务定义。
+Agent 名称全局唯一。创建后 `name` 和 `backend` 不可修改;description、
+model、reasoning effort、system prompt 可以编辑。
-### 语法
+### 支持的子命令
+
+| 子命令 | 作用 |
+| --- | --- |
+| `vibe agent list` | 列出 Agent |
+| `vibe agent show <name>` | 查看单个 Agent |
+| `vibe agent create` | 创建 Agent |
+| `vibe agent update <name>` | 修改可编辑字段 |
+| `vibe agent remove <name>` | 删除 Agent |
+| `vibe agent import` | 导入全局 Agent 或通用 Agent 文件 |
+| `vibe agent run` | 运行一次 Agent |
+
+### `vibe agent run`
```bash
-vibe hook send --session-id <session_id> (--prompt <文本> | --prompt-file <文件>) [options]
+vibe agent run (--session-id <session_id> | --create-session)? (--message <文本> | --message-file <文件>) [options]
```
重要参数:
-- `--session-id`,新 hook 应使用 Agent Session ID
-- `--post-to {thread,channel}`
+- `--agent`
+- `--session-id`
+- `--create-session`
- `--deliver-key`
-- `--prompt`
-- `--prompt-file`
+- `--async`
+- `--message`
+- `--message-file`
+
+如果不传 `--session-id` 或 `--create-session`,run 会使用 private
+no-delivery session,更适合 sub-agent 调用。`--deliver-key` 只和
+`--create-session` 搭配使用。
+
+## 5.4 `vibe runs`
+
+`vibe runs` 用来查看由 task、watch 或直接 Agent Run 产生的一次次实际执行记录。
+
+### 支持的子命令
+
+| 子命令 | 作用 |
+| --- | --- |
+| `vibe runs list` | 列出最近 run |
+| `vibe runs show <run_id>` | 查看单个 run |
+| `vibe runs cancel <run_id>` | 请求取消 run |
## 6. 推荐心智模型
@@ -772,7 +812,7 @@ vibe hook send --session-id <session_id> (--prompt <文本> | --prompt-file <文
- 想管理本地守护进程或排查安装问题:
- 用 `vibe`、`vibe status`、`vibe doctor`、`vibe upgrade`
- 想做异步自动化:
- - 用 `vibe task ...` 或 `vibe hook send ...`
+ - 用 `vibe task ...`、`vibe watch ...` 或 `vibe agent run --async ...`
## 7. 快速示例
@@ -795,5 +835,5 @@ vibe
vibe status
vibe doctor
vibe task list --brief
-vibe hook send --session-id sesk8m4q2p7x --prompt 'Share the latest build summary.'
+vibe agent run --async --session-id sesk8m4q2p7x --message 'Share the latest build summary.'
```
diff --git a/docs/plans/agent-run-harness.md b/docs/plans/agent-run-harness.md
index 78cd33503..5a1bcb03b 100644
--- a/docs/plans/agent-run-harness.md
+++ b/docs/plans/agent-run-harness.md
@@ -92,11 +92,10 @@ Rules:
- `--async` returns after the run is queued.
- Without `--async`, the command waits for completion and prints the result.
-Optional execution controls:
+Execution controls:
-- `--cwd <path>` can override the working directory for this run. If omitted,
- use the scope/session workdir when a scope/session is present; otherwise use
- the caller's shell cwd.
+- The run uses the scope/session workdir when a scope/session is present;
+ otherwise it uses the service default workdir.
- `--wait-timeout <seconds>` controls how long a synchronous command waits; it
does not terminate the run. There is no fixed default wait limit; if a
synchronous run exceeds 30 minutes, the CLI returns an accepted response and
@@ -383,7 +382,8 @@ Runtime target resolution is:
backend matches the Session backend; reject on mismatch because cross-backend
continuation cannot preserve context.
6. Use the resolved Agent backend/model/effort/system prompt.
-7. Use the Scope/session workdir unless overridden by `--cwd` for this run.
+7. Use the Scope/session workdir when available; otherwise use the service
+ default workdir.
This makes `--agent` a command-level override of the Scope default Agent, not a
backend/model/effort override. When combined with `--session-id`, it only affects
@@ -791,7 +791,6 @@ Run inspection and management:
vibe runs show run123
vibe runs list
vibe runs cancel run123
-vibe runs logs run123
```
## Runtime And Recursion Policy
@@ -811,7 +810,7 @@ one place.
Synchronous runs have no fixed default wait limit. If execution exceeds 30
minutes, the CLI returns an async accepted response, keeps the `agent_runs` row
-running, and the user can continue through `vibe runs show/list/logs`. The
+running, and the user can continue through `vibe runs show/list`. The
30-minute threshold is a system protection threshold, not a user-visible default
timeout. `--wait-timeout` only changes how long the CLI waits; it does not mean
the run times out or stops automatically.
@@ -826,19 +825,13 @@ added before implementation:
## Webhook Direction
-Future webhook support follows the same run creation path:
+Future webhook support should follow the same run creation path:
```text
external webhook -> validate source -> build RunSpec/message payload -> create agent_run
```
-Possible CLI:
-
-```bash
-vibe agent webhook create --agent incident-triage --deliver-key slack::channel::C123
-```
-
-This can be designed later, but the schema should already leave room for
+The concrete CLI can be designed later, but the schema should already leave room for
`source.kind=webhook` and structured `payload_json`.
## Specification Summary
diff --git a/docs/plans/agent-run-harness.zh.md b/docs/plans/agent-run-harness.zh.md
index 8b3a766c3..24b216223 100644
--- a/docs/plans/agent-run-harness.zh.md
+++ b/docs/plans/agent-run-harness.zh.md
@@ -90,10 +90,10 @@ vibe agent run \
- `--async` 表示排队后立即返回。
- 不带 `--async` 时,命令等待完成并打印结果。
-可选执行控制:
+执行控制:
-- `--cwd <path>` 可以覆盖本次 run 的工作目录。未指定时,如果存在
- scope/session,就使用 scope/session workdir;否则使用调用方 shell cwd。
+- 如果存在 scope/session,run 使用 scope/session workdir;否则使用服务默认
+ workdir。
- `--wait-timeout <seconds>` 控制同步命令最多等待多久;它不终止 run。默认不设置
固定等待上限;如果同步 run 执行超过 30 分钟,CLI 应返回 accepted 结果并把
run 转为 async 管理。30 分钟是系统保护阈值,不是用户可见的默认 timeout。
@@ -366,7 +366,7 @@ CLI 不能安全推断当前 IM 上下文。Direct `vibe agent run --create-sess
5. 如果同时传了 `--agent` 和 `--session-id`,校验 Agent backend 和 Session
backend 一致;不一致时拒绝,因为跨 backend 无法保持上下文连续。
6. 使用解析出的 Agent backend/model/effort/system prompt。
-7. 使用 Scope/session workdir,除非本次 run 通过 `--cwd` 覆盖。
+7. 优先使用 Scope/session workdir;没有可用 workdir 时使用服务默认 workdir。
所以 `--agent` 是命令级的 Scope default Agent override,不是
backend/model/effort override;和 `--session-id` 组合时也只影响本次 run,不修改
@@ -755,7 +755,6 @@ Run 查看和管理:
vibe runs show run123
vibe runs list
vibe runs cancel run123
-vibe runs logs run123
```
## Runtime 和递归策略
@@ -773,7 +772,7 @@ runtime 执行。
cancellation 和 backend environment 都应该由同一条路径处理。
同步 run 默认没有固定等待上限。若执行超过 30 分钟,CLI 返回 async accepted
-响应,保留 `agent_runs` 里的运行状态,后续通过 `vibe runs show/list/logs`
+响应,保留 `agent_runs` 里的运行状态,后续通过 `vibe runs show/list`
管理。30 分钟是系统保护阈值,不是用户可见的默认 timeout。`--wait-timeout`
只改变 CLI 等待多久,不表示 run 执行超时或自动停止。
@@ -786,19 +785,13 @@ metadata 应记录 `parent_run_id`。实现前应加一个简单递归保护:
## Webhook 方向
-未来 webhook 支持也走同一条 run creation 路径:
+未来 webhook 支持也应该走同一条 run creation 路径:
```text
external webhook -> validate source -> build RunSpec/message payload -> create agent_run
```
-可能的 CLI:
-
-```bash
-vibe agent webhook create --agent incident-triage --deliver-key slack::channel::C123
-```
-
-这可以之后单独设计,但 schema 应该已经为 `source.kind=webhook` 和结构化
+具体 CLI 可以之后单独设计,但 schema 应该已经为 `source.kind=webhook` 和结构化
`payload_json` 留位置。
## 规范摘要
diff --git a/modules/agents/base.py b/modules/agents/base.py
index 10791dcc4..81b9138b9 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -30,6 +30,12 @@ class AgentRequest:
subagent_key: Optional[str] = None
subagent_model: Optional[str] = None
subagent_reasoning_effort: Optional[str] = None
+ vibe_agent_id: Optional[str] = None
+ vibe_agent_name: Optional[str] = None
+ vibe_agent_backend: Optional[str] = None
+ vibe_agent_model: Optional[str] = None
+ vibe_agent_reasoning_effort: Optional[str] = None
+ vibe_agent_system_prompt: Optional[str] = None
last_agent_message: Optional[str] = None
last_agent_message_parse_mode: Optional[str] = None
started_at: float = field(default_factory=time.monotonic)
@@ -95,7 +101,17 @@ class BaseAgent(ABC):
sessions = getattr(self, "sessions", None)
ensure = getattr(sessions, "ensure_agent_session_id", None)
if callable(ensure):
- agent_session_id = ensure(request.session_key, self.name, anchor)
+ kwargs = {}
+ if request.vibe_agent_id is not None:
+ kwargs["vibe_agent_id"] = request.vibe_agent_id
+ if request.vibe_agent_name is not None:
+ kwargs["vibe_agent_name"] = request.vibe_agent_name
+ agent_session_id = ensure(
+ request.session_key,
+ self.name,
+ anchor,
+ **kwargs,
+ )
else:
getter = getattr(sessions, "get_agent_session_row_id", None)
agent_session_id = (
@@ -122,7 +138,18 @@ class BaseAgent(ABC):
sessions = getattr(self, "sessions", None)
binder = getattr(sessions, "bind_agent_session", None)
if callable(binder):
- agent_session_id = binder(request.session_key, self.name, anchor, native_session_id)
+ kwargs = {}
+ if request.vibe_agent_id is not None:
+ kwargs["vibe_agent_id"] = request.vibe_agent_id
+ if request.vibe_agent_name is not None:
+ kwargs["vibe_agent_name"] = request.vibe_agent_name
+ agent_session_id = binder(
+ request.session_key,
+ self.name,
+ anchor,
+ native_session_id,
+ **kwargs,
+ )
else:
setter = getattr(sessions, "set_agent_session_mapping", None)
if callable(setter):
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index ba5ccd673..9c340995d 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -64,8 +64,12 @@ class ClaudeAgent(BaseAgent):
client = await self.session_handler.get_or_create_claude_session(
context,
subagent_name=request.subagent_name,
- subagent_model=request.subagent_model,
- subagent_reasoning_effort=request.subagent_reasoning_effort,
+ subagent_model=request.subagent_model or getattr(request, "vibe_agent_model", None),
+ subagent_reasoning_effort=(
+ request.subagent_reasoning_effort
+ or getattr(request, "vibe_agent_reasoning_effort", None)
+ ),
+ agent_system_prompt=getattr(request, "vibe_agent_system_prompt", None),
)
runtime_base_session_id = getattr(client, "_vibe_runtime_base_session_id", runtime_base_session_id)
runtime_session_key = getattr(client, "_vibe_runtime_session_key", runtime_session_key)
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index c0977cb4d..a1a8302cd 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -527,10 +527,13 @@ class CodexAgent(BaseAgent):
request_subagent = getattr(request, "subagent_name", None)
request_model = getattr(request, "subagent_model", None)
request_effort = getattr(request, "subagent_reasoning_effort", None)
+ vibe_model = getattr(request, "vibe_agent_model", None)
+ vibe_effort = getattr(request, "vibe_agent_reasoning_effort", None)
+ vibe_instructions = getattr(request, "vibe_agent_system_prompt", None)
effective_agent = request_subagent or routing_agent
- explicit_model = request_model or routing_model
- explicit_effort = request_effort or routing_effort
+ explicit_model = request_model or vibe_model or routing_model
+ explicit_effort = request_effort or vibe_effort or routing_effort
agent_definition: Optional[SubagentDefinition] = None
if effective_agent:
@@ -543,7 +546,7 @@ class CodexAgent(BaseAgent):
effective_model = explicit_model or (agent_definition.model if agent_definition else None) or self.codex_config.default_model
effective_effort = explicit_effort or (agent_definition.reasoning_effort if agent_definition else None)
- developer_instructions = agent_definition.developer_instructions if agent_definition else None
+ developer_instructions = vibe_instructions or (agent_definition.developer_instructions if agent_definition else None)
return effective_agent, effective_model, effective_effort, developer_instructions
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 406306964..b510b1e07 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -206,6 +206,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
try:
override_agent, override_model, override_reasoning = self.controller.get_opencode_overrides(request.context)
+ override_model = request.vibe_agent_model or override_model
+ override_reasoning = request.vibe_agent_reasoning_effort or override_reasoning
override_agent = request.subagent_name or override_agent
if request.subagent_name:
@@ -275,6 +277,8 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
context=request.context,
fallback_platform=platform,
)
+ if request.vibe_agent_system_prompt:
+ system_prompt_injection = f"{request.vibe_agent_system_prompt}\n\n{system_prompt_injection}"
request_tools = {"question": False} if platform == "wechat" else None
diff --git a/modules/sessions_facade.py b/modules/sessions_facade.py
index 8afd34070..a7aa5448a 100644
--- a/modules/sessions_facade.py
+++ b/modules/sessions_facade.py
@@ -34,8 +34,18 @@ class SessionsFacade:
agent_name: str,
thread_id: str,
session_id: str,
+ *,
+ vibe_agent_id: str | None = None,
+ vibe_agent_name: str | None = None,
) -> None:
- self.sessions_store.bind_agent_session(self._normalize_user_id(user_id), agent_name, thread_id, session_id)
+ self.sessions_store.bind_agent_session(
+ self._normalize_user_id(user_id),
+ agent_name,
+ thread_id,
+ session_id,
+ vibe_agent_id=vibe_agent_id,
+ vibe_agent_name=vibe_agent_name,
+ )
logger.info("Stored %s session mapping for %s: %s -> %s", agent_name, user_id, thread_id, session_id)
def get_agent_session_id(
@@ -65,11 +75,20 @@ class SessionsFacade:
user_id: Union[int, str],
agent_name: str,
thread_id: str,
+ *,
+ vibe_agent_id: str | None = None,
+ vibe_agent_name: str | None = None,
) -> Optional[str]:
user_key = self._normalize_user_id(user_id)
ensure = getattr(self.sessions_store, "ensure_agent_session_id", None)
if callable(ensure):
- return ensure(user_key, agent_name, thread_id)
+ return ensure(
+ user_key,
+ agent_name,
+ thread_id,
+ vibe_agent_id=vibe_agent_id,
+ vibe_agent_name=vibe_agent_name,
+ )
return self.get_agent_session_row_id(user_key, thread_id, agent_name)
def bind_agent_session(
@@ -78,9 +97,19 @@ class SessionsFacade:
agent_name: str,
thread_id: str,
session_id: Any,
+ *,
+ vibe_agent_id: str | None = None,
+ vibe_agent_name: str | None = None,
) -> Optional[str]:
user_key = self._normalize_user_id(user_id)
- return self.sessions_store.bind_agent_session(user_key, agent_name, thread_id, session_id)
+ return self.sessions_store.bind_agent_session(
+ user_key,
+ agent_name,
+ thread_id,
+ session_id,
+ vibe_agent_id=vibe_agent_id,
+ vibe_agent_name=vibe_agent_name,
+ )
def clear_agent_session_mapping(
self,
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index 391995481..1fbd4118a 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -28,6 +28,7 @@ def _routing_to_dict(routing: Optional[RoutingSettings]) -> dict:
def _routing_from_dict(payload: Optional[dict]) -> RoutingSettings:
data = payload or {}
return RoutingSettings(
+ agent_name=data.get("agent_name") or data.get("agent"),
agent_backend=data.get("agent_backend"),
opencode_agent=data.get("opencode_agent"),
opencode_model=data.get("opencode_model"),
diff --git a/storage/alembic/versions/20260501_0001_initial_sqlite_state.py b/storage/alembic/versions/20260501_0001_initial_sqlite_state.py
index bcbfe3ae5..378ea80ae 100644
--- a/storage/alembic/versions/20260501_0001_initial_sqlite_state.py
+++ b/storage/alembic/versions/20260501_0001_initial_sqlite_state.py
@@ -23,6 +23,25 @@ def upgrade() -> None:
sa.Column("value_json", sa.Text(), nullable=False),
sa.Column("updated_at", sa.String(), nullable=False),
)
+ op.create_table(
+ "agents",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("name", sa.String(), nullable=False),
+ sa.Column("normalized_name", sa.String(), nullable=False),
+ sa.Column("description", sa.Text(), nullable=True),
+ sa.Column("backend", sa.String(), nullable=False),
+ sa.Column("model", sa.String(), nullable=True),
+ sa.Column("reasoning_effort", sa.String(), nullable=True),
+ sa.Column("system_prompt", sa.Text(), nullable=True),
+ sa.Column("source", sa.String(), nullable=False),
+ sa.Column("source_ref", sa.Text(), nullable=True),
+ sa.Column("metadata_json", sa.Text(), nullable=False),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("updated_at", sa.String(), nullable=False),
+ sa.UniqueConstraint("normalized_name", name="uq_agents_normalized_name"),
+ )
+ op.create_index("ix_agents_backend", "agents", ["backend"])
+ op.create_index("ix_agents_updated", "agents", ["updated_at"])
op.create_table(
"scopes",
sa.Column("id", sa.String(), primary_key=True),
@@ -49,6 +68,7 @@ def upgrade() -> None:
sa.Column("enabled", sa.Integer(), nullable=False),
sa.Column("role", sa.String(), nullable=True),
sa.Column("workdir", sa.Text(), nullable=True),
+ sa.Column("agent_name", sa.String(), nullable=True),
sa.Column("agent_backend", sa.String(), nullable=True),
sa.Column("agent_variant", sa.String(), nullable=True),
sa.Column("model", sa.String(), nullable=True),
@@ -78,6 +98,8 @@ def upgrade() -> None:
"agent_sessions",
sa.Column("id", sa.String(), primary_key=True),
sa.Column("scope_id", sa.String(), sa.ForeignKey("scopes.id", ondelete="SET NULL"), nullable=True),
+ sa.Column("agent_id", sa.String(), nullable=True),
+ sa.Column("agent_name", sa.String(), nullable=True),
sa.Column("agent_backend", sa.String(), nullable=False),
sa.Column("agent_variant", sa.String(), nullable=False),
sa.Column("model", sa.String(), nullable=True),
@@ -130,4 +152,5 @@ def downgrade() -> None:
op.drop_table("auth_codes")
op.drop_table("scope_settings")
op.drop_table("scopes")
+ op.drop_table("agents")
op.drop_table("state_meta")
diff --git a/storage/alembic/versions/20260515_0002_background_tasks.py b/storage/alembic/versions/20260515_0002_background_tasks.py
index 5c6ac59a7..48710d7e9 100644
--- a/storage/alembic/versions/20260515_0002_background_tasks.py
+++ b/storage/alembic/versions/20260515_0002_background_tasks.py
@@ -1,4 +1,4 @@
-"""background task and run tables
+"""run definition and agent run tables
Revision ID: 20260515_0002
Revises: 20260501_0001
@@ -18,13 +18,17 @@ depends_on = None
def upgrade() -> None:
op.create_table(
- "background_tasks",
+ "run_definitions",
sa.Column("id", sa.String(), primary_key=True),
- sa.Column("task_type", sa.String(), nullable=False),
+ sa.Column("definition_type", sa.String(), nullable=False),
sa.Column("name", sa.Text(), nullable=True),
+ sa.Column("agent_name", sa.String(), nullable=True),
+ sa.Column("session_policy", sa.String(), nullable=True),
sa.Column("session_id", sa.String(), nullable=True),
sa.Column("legacy_session_key", sa.Text(), nullable=True),
sa.Column("prompt", sa.Text(), nullable=True),
+ sa.Column("message", sa.Text(), nullable=True),
+ sa.Column("message_payload_json", sa.Text(), nullable=True),
sa.Column("schedule_type", sa.String(), nullable=True),
sa.Column("cron", sa.Text(), nullable=True),
sa.Column("run_at", sa.String(), nullable=True),
@@ -50,23 +54,41 @@ def upgrade() -> None:
sa.Column("last_run_at", sa.String(), nullable=True),
sa.Column("last_error", sa.Text(), nullable=True),
sa.Column("last_exit_code", sa.Integer(), nullable=True),
+ sa.Column("last_run_id", sa.String(), nullable=True),
sa.Column("metadata_json", sa.Text(), nullable=False),
)
- op.create_index("ix_background_tasks_type_enabled", "background_tasks", ["task_type", "enabled"])
- op.create_index("ix_background_tasks_session", "background_tasks", ["session_id"])
- op.create_index("ix_background_tasks_updated", "background_tasks", ["updated_at"])
+ op.create_index("ix_run_definitions_type_enabled", "run_definitions", ["definition_type", "enabled"])
+ op.create_index("ix_run_definitions_session", "run_definitions", ["session_id"])
+ op.create_index("ix_run_definitions_agent", "run_definitions", ["agent_name"])
+ op.create_index("ix_run_definitions_updated", "run_definitions", ["updated_at"])
op.create_table(
- "background_runs",
+ "agent_runs",
sa.Column("id", sa.String(), primary_key=True),
- sa.Column("task_id", sa.String(), nullable=True),
+ sa.Column("definition_id", sa.String(), nullable=True),
sa.Column("run_type", sa.String(), nullable=False),
sa.Column("status", sa.String(), nullable=False),
+ sa.Column("source_kind", sa.String(), nullable=True),
+ sa.Column("source_actor", sa.Text(), nullable=True),
+ sa.Column("parent_run_id", sa.String(), nullable=True),
+ sa.Column("agent_name", sa.String(), nullable=True),
+ sa.Column("agent_id", sa.String(), nullable=True),
+ sa.Column("agent_backend", sa.String(), nullable=True),
+ sa.Column("model", sa.String(), nullable=True),
+ sa.Column("reasoning_effort", sa.String(), nullable=True),
+ sa.Column("session_policy", sa.String(), nullable=True),
sa.Column("session_id", sa.String(), nullable=True),
sa.Column("legacy_session_key", sa.Text(), nullable=True),
sa.Column("post_to", sa.String(), nullable=True),
sa.Column("deliver_key", sa.Text(), nullable=True),
sa.Column("prompt", sa.Text(), nullable=True),
+ sa.Column("message", sa.Text(), nullable=True),
+ sa.Column("message_payload_json", sa.Text(), nullable=True),
+ sa.Column("result_text", sa.Text(), nullable=True),
+ sa.Column("result_payload_json", sa.Text(), nullable=True),
+ sa.Column("message_ids_json", sa.Text(), nullable=True),
+ sa.Column("cancel_requested", sa.Integer(), nullable=False, server_default="0"),
+ sa.Column("cancel_requested_at", sa.String(), nullable=True),
sa.Column("pid", sa.Integer(), nullable=True),
sa.Column("exit_code", sa.Integer(), nullable=True),
sa.Column("error", sa.Text(), nullable=True),
@@ -78,11 +100,13 @@ def upgrade() -> None:
sa.Column("updated_at", sa.String(), nullable=False),
sa.Column("metadata_json", sa.Text(), nullable=False),
)
- op.create_index("ix_background_runs_task_created", "background_runs", ["task_id", "created_at"])
- op.create_index("ix_background_runs_status", "background_runs", ["status"])
- op.create_index("ix_background_runs_session_created", "background_runs", ["session_id", "created_at"])
+ op.create_index("ix_agent_runs_definition_created", "agent_runs", ["definition_id", "created_at"])
+ op.create_index("ix_agent_runs_status_created", "agent_runs", ["status", "created_at"])
+ op.create_index("ix_agent_runs_type_status_created", "agent_runs", ["run_type", "status", "created_at"])
+ op.create_index("ix_agent_runs_session_created", "agent_runs", ["session_id", "created_at"])
+ op.create_index("ix_agent_runs_agent_created", "agent_runs", ["agent_name", "created_at"])
def downgrade() -> None:
- op.drop_table("background_runs")
- op.drop_table("background_tasks")
+ op.drop_table("agent_runs")
+ op.drop_table("run_definitions")
diff --git a/storage/alembic/versions/20260522_0003_agent_runs_schema.py b/storage/alembic/versions/20260522_0003_agent_runs_schema.py
new file mode 100644
index 000000000..3388d45b8
--- /dev/null
+++ b/storage/alembic/versions/20260522_0003_agent_runs_schema.py
@@ -0,0 +1,134 @@
+"""agent catalog and run harness schema
+
+Revision ID: 20260522_0003
+Revises: 20260515_0002
+Create Date: 2026-05-22
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260522_0003"
+down_revision = "20260515_0002"
+branch_labels = None
+depends_on = None
+
+
+def _columns(table_name: str) -> set[str]:
+ bind = op.get_bind()
+ return {row[1] for row in bind.exec_driver_sql(f'pragma table_info("{table_name}")')}
+
+
+def _tables() -> set[str]:
+ bind = op.get_bind()
+ return {row[0] for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")}
+
+
+def _add_column_if_missing(table_name: str, column_name: str, column: sa.Column) -> None:
+ if column_name not in _columns(table_name):
+ op.add_column(table_name, column)
+
+
+def upgrade() -> None:
+ tables = _tables()
+ if "agents" not in tables:
+ op.create_table(
+ "agents",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("name", sa.String(), nullable=False),
+ sa.Column("normalized_name", sa.String(), nullable=False),
+ sa.Column("description", sa.Text(), nullable=True),
+ sa.Column("backend", sa.String(), nullable=False),
+ sa.Column("model", sa.String(), nullable=True),
+ sa.Column("reasoning_effort", sa.String(), nullable=True),
+ sa.Column("system_prompt", sa.Text(), nullable=True),
+ sa.Column("source", sa.String(), nullable=False),
+ sa.Column("source_ref", sa.Text(), nullable=True),
+ sa.Column("metadata_json", sa.Text(), nullable=False),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("updated_at", sa.String(), nullable=False),
+ sa.UniqueConstraint("normalized_name", name="uq_agents_normalized_name"),
+ )
+ op.create_index("ix_agents_backend", "agents", ["backend"], if_not_exists=True)
+ op.create_index("ix_agents_updated", "agents", ["updated_at"], if_not_exists=True)
+
+ tables = _tables()
+ if "background_tasks" in tables and "run_definitions" not in tables:
+ op.rename_table("background_tasks", "run_definitions")
+ if "background_runs" in tables and "agent_runs" not in tables:
+ op.rename_table("background_runs", "agent_runs")
+
+ if "scope_settings" in _tables():
+ _add_column_if_missing("scope_settings", "agent_name", sa.Column("agent_name", sa.String(), nullable=True))
+
+ if "agent_sessions" in _tables():
+ _add_column_if_missing("agent_sessions", "agent_id", sa.Column("agent_id", sa.String(), nullable=True))
+ _add_column_if_missing("agent_sessions", "agent_name", sa.Column("agent_name", sa.String(), nullable=True))
+ op.execute('update agent_sessions set agent_name = agent_variant where agent_name is null')
+
+ if "run_definitions" in _tables():
+ definition_columns = _columns("run_definitions")
+ if "definition_type" not in definition_columns and "task_type" in definition_columns:
+ op.alter_column("run_definitions", "task_type", new_column_name="definition_type")
+ _add_column_if_missing("run_definitions", "agent_name", sa.Column("agent_name", sa.String(), nullable=True))
+ _add_column_if_missing("run_definitions", "session_policy", sa.Column("session_policy", sa.String(), nullable=True))
+ _add_column_if_missing("run_definitions", "message", sa.Column("message", sa.Text(), nullable=True))
+ _add_column_if_missing(
+ "run_definitions",
+ "message_payload_json",
+ sa.Column("message_payload_json", sa.Text(), nullable=True),
+ )
+ _add_column_if_missing("run_definitions", "last_run_id", sa.Column("last_run_id", sa.String(), nullable=True))
+ _add_column_if_missing("run_definitions", "deleted_at", sa.Column("deleted_at", sa.String(), nullable=True))
+ op.execute('update run_definitions set message = prompt where message is null')
+ op.execute(
+ "update run_definitions set session_policy = "
+ "case when session_id is not null and session_id != '' then 'existing' else 'existing' end "
+ "where session_policy is null"
+ )
+ op.create_index("ix_run_definitions_type_enabled", "run_definitions", ["definition_type", "enabled"], if_not_exists=True)
+ op.create_index("ix_run_definitions_session", "run_definitions", ["session_id"], if_not_exists=True)
+ op.create_index("ix_run_definitions_agent", "run_definitions", ["agent_name"], if_not_exists=True)
+ op.create_index("ix_run_definitions_updated", "run_definitions", ["updated_at"], if_not_exists=True)
+
+ if "agent_runs" in _tables():
+ run_columns = _columns("agent_runs")
+ if "definition_id" not in run_columns and "task_id" in run_columns:
+ op.alter_column("agent_runs", "task_id", new_column_name="definition_id")
+ _add_column_if_missing("agent_runs", "source_kind", sa.Column("source_kind", sa.String(), nullable=True))
+ _add_column_if_missing("agent_runs", "source_actor", sa.Column("source_actor", sa.Text(), nullable=True))
+ _add_column_if_missing("agent_runs", "parent_run_id", sa.Column("parent_run_id", sa.String(), nullable=True))
+ _add_column_if_missing("agent_runs", "agent_name", sa.Column("agent_name", sa.String(), nullable=True))
+ _add_column_if_missing("agent_runs", "agent_id", sa.Column("agent_id", sa.String(), nullable=True))
+ _add_column_if_missing("agent_runs", "agent_backend", sa.Column("agent_backend", sa.String(), nullable=True))
+ _add_column_if_missing("agent_runs", "model", sa.Column("model", sa.String(), nullable=True))
+ _add_column_if_missing("agent_runs", "reasoning_effort", sa.Column("reasoning_effort", sa.String(), nullable=True))
+ _add_column_if_missing("agent_runs", "session_policy", sa.Column("session_policy", sa.String(), nullable=True))
+ _add_column_if_missing("agent_runs", "message", sa.Column("message", sa.Text(), nullable=True))
+ _add_column_if_missing("agent_runs", "message_payload_json", sa.Column("message_payload_json", sa.Text(), nullable=True))
+ _add_column_if_missing("agent_runs", "result_text", sa.Column("result_text", sa.Text(), nullable=True))
+ _add_column_if_missing("agent_runs", "result_payload_json", sa.Column("result_payload_json", sa.Text(), nullable=True))
+ _add_column_if_missing("agent_runs", "message_ids_json", sa.Column("message_ids_json", sa.Text(), nullable=True))
+ _add_column_if_missing(
+ "agent_runs",
+ "cancel_requested",
+ sa.Column("cancel_requested", sa.Integer(), nullable=False, server_default="0"),
+ )
+ _add_column_if_missing("agent_runs", "cancel_requested_at", sa.Column("cancel_requested_at", sa.String(), nullable=True))
+ op.execute('update agent_runs set message = prompt where message is null')
+ op.create_index("ix_agent_runs_definition_created", "agent_runs", ["definition_id", "created_at"], if_not_exists=True)
+ op.create_index("ix_agent_runs_status_created", "agent_runs", ["status", "created_at"], if_not_exists=True)
+ op.create_index(
+ "ix_agent_runs_type_status_created",
+ "agent_runs",
+ ["run_type", "status", "created_at"],
+ if_not_exists=True,
+ )
+ op.create_index("ix_agent_runs_session_created", "agent_runs", ["session_id", "created_at"], if_not_exists=True)
+ op.create_index("ix_agent_runs_agent_created", "agent_runs", ["agent_name", "created_at"], if_not_exists=True)
+
+
+def downgrade() -> None:
+ pass
diff --git a/storage/background.py b/storage/background.py
index ad0870c45..e28eec351 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -11,7 +11,7 @@ from sqlalchemy import insert, select, update
from config import paths
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.migrations import background_tables_ready, initialize_background_tables
-from storage.models import background_runs, background_tasks
+from storage.models import agent_runs, run_definitions
logger = logging.getLogger(__name__)
@@ -56,20 +56,20 @@ class SQLiteBackgroundTaskStore:
def list_scheduled_tasks(self) -> list[dict[str, Any]]:
with self.engine.connect() as conn:
rows = conn.execute(
- select(background_tasks)
- .where(background_tasks.c.task_type == "scheduled")
- .where(background_tasks.c.deleted_at.is_(None))
- .order_by(background_tasks.c.created_at, background_tasks.c.id)
+ select(run_definitions)
+ .where(run_definitions.c.definition_type == "scheduled")
+ .where(run_definitions.c.deleted_at.is_(None))
+ .order_by(run_definitions.c.created_at, run_definitions.c.id)
).mappings()
return [self._scheduled_task_from_row(row) for row in rows]
- def get_scheduled_task(self, task_id: str) -> Optional[dict[str, Any]]:
+ def get_scheduled_task(self, definition_id: str) -> Optional[dict[str, Any]]:
with self.engine.connect() as conn:
row = conn.execute(
- select(background_tasks)
- .where(background_tasks.c.task_type == "scheduled")
- .where(background_tasks.c.id == task_id)
- .where(background_tasks.c.deleted_at.is_(None))
+ select(run_definitions)
+ .where(run_definitions.c.definition_type == "scheduled")
+ .where(run_definitions.c.id == definition_id)
+ .where(run_definitions.c.deleted_at.is_(None))
.limit(1)
).mappings().first()
return self._scheduled_task_from_row(row) if row else None
@@ -78,19 +78,19 @@ class SQLiteBackgroundTaskStore:
values = self._scheduled_task_values(payload)
with self.engine.begin() as conn:
existing = conn.execute(
- select(background_tasks.c.id).where(background_tasks.c.id == values["id"]).limit(1)
+ select(run_definitions.c.id).where(run_definitions.c.id == values["id"]).limit(1)
).scalar_one_or_none()
if existing:
- conn.execute(update(background_tasks).where(background_tasks.c.id == values["id"]).values(**values))
+ conn.execute(update(run_definitions).where(run_definitions.c.id == values["id"]).values(**values))
else:
- conn.execute(insert(background_tasks).values(**values))
+ conn.execute(insert(run_definitions).values(**values))
- def remove_task(self, task_id: str, *, deleted_at: Optional[str] = None) -> bool:
+ def remove_task(self, definition_id: str, *, deleted_at: Optional[str] = None) -> bool:
with self.engine.begin() as conn:
result = conn.execute(
- update(background_tasks)
- .where(background_tasks.c.id == task_id)
- .where(background_tasks.c.deleted_at.is_(None))
+ update(run_definitions)
+ .where(run_definitions.c.id == definition_id)
+ .where(run_definitions.c.deleted_at.is_(None))
.values(deleted_at=deleted_at or _utc_now_iso())
)
return bool(result.rowcount)
@@ -98,20 +98,20 @@ class SQLiteBackgroundTaskStore:
def list_watches(self) -> list[dict[str, Any]]:
with self.engine.connect() as conn:
rows = conn.execute(
- select(background_tasks)
- .where(background_tasks.c.task_type == "watch")
- .where(background_tasks.c.deleted_at.is_(None))
- .order_by(background_tasks.c.created_at, background_tasks.c.id)
+ select(run_definitions)
+ .where(run_definitions.c.definition_type == "watch")
+ .where(run_definitions.c.deleted_at.is_(None))
+ .order_by(run_definitions.c.created_at, run_definitions.c.id)
).mappings()
return [self._watch_from_row(row) for row in rows]
def get_watch(self, watch_id: str) -> Optional[dict[str, Any]]:
with self.engine.connect() as conn:
row = conn.execute(
- select(background_tasks)
- .where(background_tasks.c.task_type == "watch")
- .where(background_tasks.c.id == watch_id)
- .where(background_tasks.c.deleted_at.is_(None))
+ select(run_definitions)
+ .where(run_definitions.c.definition_type == "watch")
+ .where(run_definitions.c.id == watch_id)
+ .where(run_definitions.c.deleted_at.is_(None))
.limit(1)
).mappings().first()
return self._watch_from_row(row) if row else None
@@ -120,48 +120,58 @@ class SQLiteBackgroundTaskStore:
values = self._watch_values(payload)
with self.engine.begin() as conn:
existing = conn.execute(
- select(background_tasks.c.id).where(background_tasks.c.id == values["id"]).limit(1)
+ select(run_definitions.c.id).where(run_definitions.c.id == values["id"]).limit(1)
).scalar_one_or_none()
if existing:
- conn.execute(update(background_tasks).where(background_tasks.c.id == values["id"]).values(**values))
+ conn.execute(update(run_definitions).where(run_definitions.c.id == values["id"]).values(**values))
else:
- conn.execute(insert(background_tasks).values(**values))
+ conn.execute(insert(run_definitions).values(**values))
def enqueue_run(self, payload: dict[str, Any]) -> None:
values = self._run_values(payload)
with self.engine.begin() as conn:
existing = conn.execute(
- select(background_runs.c.id).where(background_runs.c.id == values["id"]).limit(1)
+ select(agent_runs.c.id).where(agent_runs.c.id == values["id"]).limit(1)
).scalar_one_or_none()
if existing:
- conn.execute(update(background_runs).where(background_runs.c.id == values["id"]).values(**values))
+ conn.execute(update(agent_runs).where(agent_runs.c.id == values["id"]).values(**values))
else:
- conn.execute(insert(background_runs).values(**values))
+ conn.execute(insert(agent_runs).values(**values))
def list_runs(self, *, status: Optional[str] = None) -> list[dict[str, Any]]:
- stmt = select(background_runs)
+ stmt = select(agent_runs)
if status:
- stmt = stmt.where(background_runs.c.status == status)
- stmt = stmt.order_by(background_runs.c.created_at, background_runs.c.id)
+ stmt = stmt.where(agent_runs.c.status == 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()]
def get_run(self, run_id: str) -> Optional[dict[str, Any]]:
with self.engine.connect() as conn:
- row = conn.execute(select(background_runs).where(background_runs.c.id == run_id).limit(1)).mappings().first()
+ row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
return self._run_from_row(row) if row else None
+ 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:
+ result = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(cancel_requested=1, cancel_requested_at=now, updated_at=now)
+ )
+ 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:
result = conn.execute(
- update(background_runs)
- .where(background_runs.c.id == run_id)
- .where(background_runs.c.status == "pending")
+ 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)
)
if not result.rowcount:
return None
- row = conn.execute(select(background_runs).where(background_runs.c.id == run_id).limit(1)).mappings().first()
+ row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
return self._run_from_row(row) if row else None
def update_run_status(
@@ -177,9 +187,15 @@ class SQLiteBackgroundTaskStore:
stdout: Optional[str] = None,
stderr: Optional[str] = None,
pid: Optional[int] = None,
+ definition_id: Optional[str] = None,
task_id: Optional[str] = None,
session_key: Optional[str] = None,
session_id: Optional[str] = None,
+ result_text: Optional[str] = None,
+ result_payload: Optional[dict[str, Any]] = None,
+ message_ids: Optional[list[str]] = None,
+ cancel_requested: Optional[bool] = None,
+ cancel_requested_at: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
) -> None:
values: dict[str, Any] = {
@@ -200,22 +216,65 @@ class SQLiteBackgroundTaskStore:
values["stderr"] = stderr
if pid is not None:
values["pid"] = pid
- if task_id is not None:
- values["task_id"] = task_id
+ resolved_definition_id = definition_id or task_id
+ if resolved_definition_id is not None:
+ values["definition_id"] = resolved_definition_id
if session_key is not None:
values["legacy_session_key"] = session_key
if session_id is not None:
values["session_id"] = session_id
+ if result_text is not None:
+ values["result_text"] = result_text
+ if result_payload is not None:
+ values["result_payload_json"] = _json_dumps(result_payload)
+ if message_ids is not None:
+ values["message_ids_json"] = _json_dumps(message_ids)
+ if cancel_requested is not None:
+ values["cancel_requested"] = 1 if cancel_requested else 0
+ if cancel_requested_at is not None:
+ values["cancel_requested_at"] = cancel_requested_at
if metadata is not None:
values["metadata_json"] = _json_dumps(metadata)
with self.engine.begin() as conn:
- conn.execute(update(background_runs).where(background_runs.c.id == run_id).values(**values))
+ conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))
+
+ def record_run_message(
+ self,
+ run_id: str,
+ *,
+ text: str,
+ message_id: str | None = None,
+ updated_at: Optional[str] = None,
+ ) -> None:
+ now = updated_at or _utc_now_iso()
+ 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
+ existing_text = str(row["result_text"] or "")
+ incoming = str(text or "")
+ if existing_text and incoming:
+ result_text = f"{existing_text}\n\n{incoming}"
+ else:
+ result_text = existing_text or incoming
+ message_ids = _json_loads(row["message_ids_json"], [])
+ if message_id:
+ message_ids.append(message_id)
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(
+ result_text=result_text,
+ message_ids_json=_json_dumps(message_ids),
+ updated_at=now,
+ )
+ )
def recover_processing_runs(self) -> None:
with self.engine.begin() as conn:
conn.execute(
- update(background_runs)
- .where(background_runs.c.status == "processing")
+ update(agent_runs)
+ .where(agent_runs.c.status == "processing")
.values(status="pending", started_at=None, pid=None)
)
@@ -223,9 +282,9 @@ class SQLiteBackgroundTaskStore:
watches = payload.get("watches", {}) if isinstance(payload, dict) else {}
with self.engine.begin() as conn:
conn.execute(
- update(background_runs)
- .where(background_runs.c.run_type == "watch_runtime")
- .where(background_runs.c.status.in_(["running", "pending"]))
+ 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)
)
for watch_id, runtime_payload in watches.items():
@@ -237,7 +296,7 @@ class SQLiteBackgroundTaskStore:
"id": run_id,
"request_type": "watch_runtime",
"status": "running" if runtime_payload.get("running") else "completed",
- "task_id": watch_id,
+ "definition_id": watch_id,
"pid": runtime_payload.get("pid"),
"created_at": runtime_payload.get("started_at") or updated_at,
"started_at": runtime_payload.get("started_at"),
@@ -246,24 +305,24 @@ class SQLiteBackgroundTaskStore:
}
)
existing = conn.execute(
- select(background_runs.c.id).where(background_runs.c.id == run_id).limit(1)
+ select(agent_runs.c.id).where(agent_runs.c.id == run_id).limit(1)
).scalar_one_or_none()
if existing:
- conn.execute(update(background_runs).where(background_runs.c.id == run_id).values(**values))
+ conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))
else:
- conn.execute(insert(background_runs).values(**values))
+ conn.execute(insert(agent_runs).values(**values))
def load_watch_runtime(self) -> dict[str, Any]:
with self.engine.connect() as conn:
rows = conn.execute(
- select(background_runs)
- .where(background_runs.c.run_type == "watch_runtime")
- .where(background_runs.c.status == "running")
+ select(agent_runs)
+ .where(agent_runs.c.run_type == "watch_runtime")
+ .where(agent_runs.c.status == "running")
).mappings()
watches: dict[str, Any] = {}
for row in rows:
payload = _json_loads(row["metadata_json"], {})
- watch_id = row["task_id"]
+ watch_id = row["definition_id"]
if watch_id:
watches[str(watch_id)] = {
"running": True,
@@ -276,11 +335,15 @@ class SQLiteBackgroundTaskStore:
def _scheduled_task_values(self, payload: dict[str, Any]) -> dict[str, Any]:
return {
"id": payload["id"],
- "task_type": "scheduled",
+ "definition_type": "scheduled",
"name": payload.get("name"),
+ "agent_name": payload.get("agent_name"),
+ "session_policy": payload.get("session_policy") or ("existing" if payload.get("session_id") or payload.get("session_key") else None),
"session_id": payload.get("session_id"),
"legacy_session_key": payload.get("session_key") or None,
- "prompt": payload.get("prompt") or "",
+ "prompt": payload.get("prompt") or payload.get("message") or "",
+ "message": payload.get("message") or payload.get("prompt") or "",
+ "message_payload_json": self._message_payload_json(payload),
"schedule_type": payload.get("schedule_type") or "",
"cron": payload.get("cron"),
"run_at": payload.get("run_at"),
@@ -304,6 +367,7 @@ class SQLiteBackgroundTaskStore:
"last_finished_at": None,
"last_event_at": None,
"last_run_at": payload.get("last_run_at"),
+ "last_run_id": payload.get("last_run_id"),
"last_error": payload.get("last_error"),
"last_exit_code": None,
"metadata_json": _json_dumps({}),
@@ -312,11 +376,15 @@ class SQLiteBackgroundTaskStore:
def _watch_values(self, payload: dict[str, Any]) -> dict[str, Any]:
return {
"id": payload["id"],
- "task_type": "watch",
+ "definition_type": "watch",
"name": payload.get("name"),
+ "agent_name": payload.get("agent_name"),
+ "session_policy": payload.get("session_policy") or ("existing" if payload.get("session_id") or payload.get("session_key") else None),
"session_id": payload.get("session_id"),
"legacy_session_key": payload.get("session_key") or None,
"prompt": None,
+ "message": payload.get("message") or payload.get("prefix"),
+ "message_payload_json": self._message_payload_json(payload),
"schedule_type": None,
"cron": None,
"run_at": None,
@@ -347,16 +415,33 @@ class SQLiteBackgroundTaskStore:
def _run_values(self, payload: dict[str, Any]) -> dict[str, Any]:
created_at = payload.get("created_at") or payload.get("updated_at")
+ message = payload.get("message") or payload.get("prompt")
return {
"id": payload["id"],
- "task_id": payload.get("task_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",
+ "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"),
+ "model": payload.get("model") or payload.get("agent_model"),
+ "reasoning_effort": payload.get("reasoning_effort") or payload.get("agent_reasoning_effort"),
+ "session_policy": payload.get("session_policy"),
"session_id": payload.get("session_id"),
"legacy_session_key": payload.get("session_key") or payload.get("legacy_session_key"),
"post_to": payload.get("post_to"),
"deliver_key": payload.get("deliver_key"),
- "prompt": payload.get("prompt"),
+ "prompt": payload.get("prompt") or message,
+ "message": message,
+ "message_payload_json": self._message_payload_json(payload),
+ "result_text": payload.get("result_text"),
+ "result_payload_json": self._payload_json(payload, "result_payload", "result_payload_json"),
+ "message_ids_json": self._payload_json(payload, "message_ids", "message_ids_json"),
+ "cancel_requested": 1 if payload.get("cancel_requested") else 0,
+ "cancel_requested_at": payload.get("cancel_requested_at"),
"pid": payload.get("pid"),
"exit_code": payload.get("exit_code"),
"error": payload.get("error"),
@@ -374,9 +459,13 @@ class SQLiteBackgroundTaskStore:
return {
"id": row["id"],
"name": row["name"],
+ "agent_name": row["agent_name"],
+ "session_policy": row["session_policy"],
"session_key": row["legacy_session_key"] or "",
"session_id": row["session_id"],
"prompt": row["prompt"] or "",
+ "message": row["message"] or row["prompt"] or "",
+ "message_payload": _json_loads(row["message_payload_json"], None),
"schedule_type": row["schedule_type"] or "",
"post_to": row["post_to"],
"deliver_key": row["deliver_key"],
@@ -387,6 +476,7 @@ class SQLiteBackgroundTaskStore:
"created_at": row["created_at"],
"updated_at": row["updated_at"],
"last_run_at": row["last_run_at"],
+ "last_run_id": row["last_run_id"],
"last_error": row["last_error"],
}
@@ -395,11 +485,15 @@ class SQLiteBackgroundTaskStore:
return {
"id": row["id"],
"name": row["name"],
+ "agent_name": row["agent_name"],
+ "session_policy": row["session_policy"],
"session_key": row["legacy_session_key"] or "",
"session_id": row["session_id"],
"command": _json_loads(row["command_json"], []),
"shell_command": row["shell_command"],
"prefix": row["prefix"],
+ "message": row["message"] or row["prefix"],
+ "message_payload": _json_loads(row["message_payload_json"], None),
"cwd": row["cwd"],
"mode": row["mode"] or "once",
"timeout_seconds": float(row["timeout_seconds"] or 21600.0),
@@ -425,12 +519,29 @@ class SQLiteBackgroundTaskStore:
"request_type": row["run_type"],
"run_type": row["run_type"],
"status": row["status"],
- "task_id": row["task_id"],
+ "definition_id": row["definition_id"],
+ "task_id": row["definition_id"],
+ "source_kind": row["source_kind"],
+ "source_actor": row["source_actor"],
+ "parent_run_id": row["parent_run_id"],
+ "agent_name": row["agent_name"],
+ "agent_id": row["agent_id"],
+ "agent_backend": row["agent_backend"],
+ "model": row["model"],
+ "reasoning_effort": row["reasoning_effort"],
+ "session_policy": row["session_policy"],
"session_key": row["legacy_session_key"],
"session_id": row["session_id"],
"post_to": row["post_to"],
"deliver_key": row["deliver_key"],
"prompt": row["prompt"],
+ "message": row["message"] or row["prompt"],
+ "message_payload": _json_loads(row["message_payload_json"], None),
+ "result_text": row["result_text"],
+ "result_payload": _json_loads(row["result_payload_json"], None),
+ "message_ids": _json_loads(row["message_ids_json"], []),
+ "cancel_requested": bool(row["cancel_requested"]),
+ "cancel_requested_at": row["cancel_requested_at"],
"pid": row["pid"],
"exit_code": row["exit_code"],
"error": row["error"],
@@ -443,3 +554,15 @@ class SQLiteBackgroundTaskStore:
"metadata": _json_loads(row["metadata_json"], {}),
"ok": None if row["completed_at"] is None else row["status"] == "completed",
}
+
+ @staticmethod
+ def _message_payload_json(payload: dict[str, Any]) -> Optional[str]:
+ return SQLiteBackgroundTaskStore._payload_json(payload, "message_payload", "message_payload_json")
+
+ @staticmethod
+ def _payload_json(payload: dict[str, Any], object_key: str, json_key: str) -> Optional[str]:
+ if payload.get(json_key) is not None:
+ return payload.get(json_key)
+ if payload.get(object_key) is not None:
+ return _json_dumps(payload.get(object_key))
+ return None
diff --git a/storage/importer.py b/storage/importer.py
index 3caa4f5e0..fc95784f5 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -25,11 +25,12 @@ from storage.db import create_sqlite_engine
from storage.lock import MigrationFileLock
from storage.migrations import run_migrations
from storage.models import (
+ agents,
agent_sessions,
+ agent_runs,
auth_codes,
- background_runs,
- background_tasks,
imported_state_tables,
+ run_definitions,
runtime_records,
scope_settings,
scopes,
@@ -428,13 +429,17 @@ def _import_scheduled_tasks(conn: Connection, source: Path) -> int:
if not isinstance(item, dict):
continue
conn.execute(
- background_tasks.insert().values(
+ run_definitions.insert().values(
id=str(item.get("id") or ""),
- task_type="scheduled",
+ definition_type="scheduled",
name=item.get("name"),
+ agent_name=item.get("agent_name"),
+ session_policy="existing",
session_id=item.get("session_id"),
legacy_session_key=item.get("session_key") or None,
prompt=item.get("prompt") or "",
+ message=item.get("message") or item.get("prompt") or "",
+ message_payload_json=None,
schedule_type=item.get("schedule_type") or "",
cron=item.get("cron"),
run_at=item.get("run_at"),
@@ -460,6 +465,7 @@ def _import_scheduled_tasks(conn: Connection, source: Path) -> int:
last_run_at=item.get("last_run_at"),
last_error=item.get("last_error"),
last_exit_code=None,
+ last_run_id=None,
metadata_json=_json_dumps({}),
)
)
@@ -474,13 +480,17 @@ def _import_watches(conn: Connection, source: Path) -> int:
if not isinstance(item, dict):
continue
conn.execute(
- background_tasks.insert().values(
+ run_definitions.insert().values(
id=str(item.get("id") or ""),
- task_type="watch",
+ definition_type="watch",
name=item.get("name"),
+ agent_name=item.get("agent_name"),
+ session_policy="existing",
session_id=item.get("session_id"),
legacy_session_key=item.get("session_key") or None,
prompt=None,
+ message=item.get("message") or item.get("prefix"),
+ message_payload_json=None,
schedule_type=None,
cron=None,
run_at=None,
@@ -506,6 +516,7 @@ def _import_watches(conn: Connection, source: Path) -> int:
last_run_at=None,
last_error=item.get("last_error"),
last_exit_code=item.get("last_exit_code"),
+ last_run_id=None,
metadata_json=_json_dumps({}),
)
)
@@ -527,16 +538,32 @@ def _import_task_requests(conn: Connection, root: Path) -> int:
run_status = "failed" if status == "completed" and ok is False else status
created_at = item.get("created_at") or item.get("completed_at") or _utc_now_iso()
conn.execute(
- background_runs.insert().values(
+ agent_runs.insert().values(
id=str(item.get("id") or path.stem),
- task_id=item.get("task_id"),
+ definition_id=item.get("definition_id") or item.get("task_id"),
run_type=item.get("request_type") or "hook_send",
status=run_status,
+ source_kind="scheduler" if item.get("task_id") else "cli",
+ source_actor=None,
+ parent_run_id=None,
+ agent_name=item.get("agent_name"),
+ agent_id=None,
+ agent_backend=item.get("agent_backend"),
+ model=item.get("model"),
+ reasoning_effort=item.get("reasoning_effort"),
+ session_policy="existing" if item.get("session_id") else None,
session_id=item.get("session_id"),
legacy_session_key=item.get("session_key"),
post_to=item.get("post_to"),
deliver_key=item.get("deliver_key"),
prompt=item.get("prompt"),
+ message=item.get("message") or item.get("prompt"),
+ message_payload_json=None,
+ result_text=None,
+ result_payload_json=None,
+ message_ids_json=None,
+ cancel_requested=0,
+ cancel_requested_at=None,
pid=None,
exit_code=None,
error=item.get("error"),
@@ -564,16 +591,32 @@ def _import_watch_runtime(conn: Connection, source: Path) -> int:
continue
now = item.get("updated_at") or _utc_now_iso()
conn.execute(
- background_runs.insert().values(
+ agent_runs.insert().values(
id=f"runtime:{watch_id}",
- task_id=str(watch_id),
+ definition_id=str(watch_id),
run_type="watch_runtime",
status="running" if item.get("running") else "completed",
+ source_kind="watch",
+ source_actor=None,
+ parent_run_id=None,
+ agent_name=None,
+ agent_id=None,
+ agent_backend=None,
+ model=None,
+ reasoning_effort=None,
+ session_policy=None,
session_id=None,
legacy_session_key=None,
post_to=None,
deliver_key=None,
prompt=None,
+ message=None,
+ message_payload_json=None,
+ result_text=None,
+ result_payload_json=None,
+ message_ids_json=None,
+ cancel_requested=0,
+ cancel_requested_at=None,
pid=item.get("pid"),
exit_code=None,
error=None,
@@ -598,13 +641,14 @@ def _validate_import(conn: Connection, _counts: dict[str, int]) -> None:
def _current_counts(conn: Connection) -> dict[str, int]:
tables = {
+ "agents": agents,
"scopes": scopes,
"scope_settings": scope_settings,
"auth_codes": auth_codes,
"agent_sessions": agent_sessions,
"runtime_records": runtime_records,
- "background_tasks": background_tasks,
- "background_runs": background_runs,
+ "run_definitions": run_definitions,
+ "agent_runs": agent_runs,
}
return {key: int(conn.execute(select(func.count()).select_from(table)).scalar_one()) for key, table in tables.items()}
diff --git a/storage/migrations.py b/storage/migrations.py
index e829aea3f..cc468cd83 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -12,15 +12,45 @@ from storage.db import sqlite_url
INITIAL_REVISION = "20260501_0001"
INITIAL_TABLES = {
"state_meta",
+ "agents",
"scopes",
"scope_settings",
"auth_codes",
"agent_sessions",
"runtime_records",
}
-HEAD_TABLES = INITIAL_TABLES | {"background_tasks", "background_runs"}
+HEAD_TABLES = INITIAL_TABLES | {"run_definitions", "agent_runs"}
HEAD_REQUIRED_COLUMNS = {
- "background_tasks": {"deleted_at"},
+ "scope_settings": {"agent_name"},
+ "agent_sessions": {"agent_id", "agent_name"},
+ "run_definitions": {
+ "deleted_at",
+ "definition_type",
+ "agent_name",
+ "session_policy",
+ "message",
+ "message_payload_json",
+ "last_run_id",
+ },
+ "agent_runs": {
+ "definition_id",
+ "source_kind",
+ "source_actor",
+ "parent_run_id",
+ "agent_name",
+ "agent_id",
+ "agent_backend",
+ "model",
+ "reasoning_effort",
+ "session_policy",
+ "message",
+ "message_payload_json",
+ "result_text",
+ "result_payload_json",
+ "message_ids_json",
+ "cancel_requested",
+ "cancel_requested_at",
+ },
}
UNRELEASED_OLD_INITIAL_TABLES = [
"session_messages",
@@ -109,6 +139,13 @@ def _repair_unreleased_head_schema_drift(db_path: Path) -> None:
return
with sqlite3.connect(path) as conn:
+ tables = _table_names(conn)
+ _rename_legacy_background_tables(conn, tables)
+ tables = _table_names(conn)
+ if not (tables <= {"alembic_version", "agents"}):
+ _ensure_agents_table(conn, tables)
+ tables = _table_names(conn)
+ _repair_initial_required_columns(conn, tables)
tables = _table_names(conn)
if not HEAD_TABLES.issubset(tables):
return
@@ -128,14 +165,25 @@ def _stamp_existing_initial_schema(db_path: Path, cfg: Config) -> None:
return
with sqlite3.connect(path) as conn:
+ tables = _table_names(conn)
+ _rename_legacy_background_tables(conn, tables)
+ tables = _table_names(conn)
+ if not (tables <= {"alembic_version"}):
+ _ensure_agents_table(conn, tables)
+ tables = _table_names(conn)
+ _repair_initial_required_columns(conn, tables)
tables = _table_names(conn)
if not tables:
return
+ if not (tables - {"alembic_version", "agents"}):
+ return
if "alembic_version" in tables:
version = conn.execute("select version_num from alembic_version").fetchone()
if version is not None and version[0]:
return
missing_initial_tables = INITIAL_TABLES - tables
+ if not (tables & (INITIAL_TABLES - {"agents"})) and (tables & {"run_definitions", "agent_runs"}):
+ return
if missing_initial_tables and (tables & INITIAL_TABLES):
missing = ", ".join(sorted(missing_initial_tables))
raise RuntimeError(f"existing SQLite schema is incomplete; missing initial tables: {missing}")
@@ -178,13 +226,137 @@ def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) ->
if not HEAD_TABLES.issubset(tables):
return False
changed = False
- existing_columns = _column_names(conn, "background_tasks")
- if "deleted_at" not in existing_columns:
- conn.execute('alter table "background_tasks" add column "deleted_at" VARCHAR')
+ changed = _repair_initial_required_columns(conn, tables) or changed
+
+ definition_columns = _column_names(conn, "run_definitions")
+ if "definition_type" not in definition_columns and "task_type" in definition_columns:
+ conn.execute('alter table "run_definitions" rename column "task_type" to "definition_type"')
+ changed = True
+ definition_columns = _column_names(conn, "run_definitions")
+ for column, column_type in {
+ "deleted_at": "VARCHAR",
+ "agent_name": "VARCHAR",
+ "session_policy": "VARCHAR",
+ "message": "TEXT",
+ "message_payload_json": "TEXT",
+ "last_run_id": "VARCHAR",
+ }.items():
+ if column not in definition_columns:
+ conn.execute(f'alter table "run_definitions" add column "{column}" {column_type}')
+ changed = True
+ definition_columns = _column_names(conn, "run_definitions")
+ if "message" in definition_columns and "prompt" in definition_columns:
+ conn.execute('update "run_definitions" set message = prompt where message is null')
+ if "session_policy" in definition_columns:
+ conn.execute(
+ 'update "run_definitions" set session_policy = '
+ 'case when session_id is not null and session_id != "" then "existing" else "existing" end '
+ 'where session_policy is null'
+ )
+
+ run_columns = _column_names(conn, "agent_runs")
+ if "definition_id" not in run_columns and "task_id" in run_columns:
+ conn.execute('alter table "agent_runs" rename column "task_id" to "definition_id"')
+ changed = True
+ run_columns = _column_names(conn, "agent_runs")
+ for column, column_type in {
+ "source_kind": "VARCHAR",
+ "source_actor": "TEXT",
+ "parent_run_id": "VARCHAR",
+ "agent_name": "VARCHAR",
+ "agent_id": "VARCHAR",
+ "agent_backend": "VARCHAR",
+ "model": "VARCHAR",
+ "reasoning_effort": "VARCHAR",
+ "session_policy": "VARCHAR",
+ "message": "TEXT",
+ "message_payload_json": "TEXT",
+ "result_text": "TEXT",
+ "result_payload_json": "TEXT",
+ "message_ids_json": "TEXT",
+ "cancel_requested": "INTEGER not null default 0",
+ "cancel_requested_at": "VARCHAR",
+ }.items():
+ if column not in run_columns:
+ conn.execute(f'alter table "agent_runs" add column "{column}" {column_type}')
+ changed = True
+ run_columns = _column_names(conn, "agent_runs")
+ if "message" in run_columns and "prompt" in run_columns:
+ conn.execute('update "agent_runs" set message = prompt where message is null')
+ _ensure_new_background_indexes(conn)
+ return changed
+
+
+def _rename_legacy_background_tables(conn: sqlite3.Connection, tables: set[str]) -> bool:
+ changed = False
+ if "background_tasks" in tables and "run_definitions" not in tables:
+ conn.execute('alter table "background_tasks" rename to "run_definitions"')
+ changed = True
+ if "background_runs" in tables and "agent_runs" not in tables:
+ conn.execute('alter table "background_runs" rename to "agent_runs"')
changed = True
return changed
+def _ensure_agents_table(conn: sqlite3.Connection, tables: set[str]) -> bool:
+ if "agents" in tables:
+ return False
+ conn.execute(
+ """
+ create table agents (
+ id varchar primary key,
+ name varchar not null,
+ normalized_name varchar not null,
+ description text,
+ backend varchar not null,
+ model varchar,
+ reasoning_effort varchar,
+ system_prompt text,
+ source varchar not null,
+ source_ref text,
+ metadata_json text not null,
+ created_at varchar not null,
+ updated_at varchar not null,
+ constraint uq_agents_normalized_name unique (normalized_name)
+ )
+ """
+ )
+ conn.execute('create index if not exists ix_agents_backend on agents (backend)')
+ conn.execute('create index if not exists ix_agents_updated on agents (updated_at)')
+ return True
+
+
+def _repair_initial_required_columns(conn: sqlite3.Connection, tables: set[str]) -> bool:
+ changed = False
+ if "scope_settings" in tables:
+ columns = _column_names(conn, "scope_settings")
+ if "agent_name" not in columns:
+ conn.execute('alter table "scope_settings" add column "agent_name" VARCHAR')
+ changed = True
+ if "agent_sessions" in tables:
+ columns = _column_names(conn, "agent_sessions")
+ if "agent_id" not in columns:
+ conn.execute('alter table "agent_sessions" add column "agent_id" VARCHAR')
+ changed = True
+ if "agent_name" not in columns:
+ conn.execute('alter table "agent_sessions" add column "agent_name" VARCHAR')
+ changed = True
+ conn.execute('update "agent_sessions" set agent_name = agent_variant where agent_name is null')
+ return changed
+
+
+def _ensure_new_background_indexes(conn: sqlite3.Connection) -> None:
+ conn.execute('create index if not exists ix_run_definitions_type_enabled on run_definitions (definition_type, enabled)')
+ conn.execute('create index if not exists ix_run_definitions_session on run_definitions (session_id)')
+ conn.execute('create index if not exists ix_run_definitions_agent on run_definitions (agent_name)')
+ conn.execute('create index if not exists ix_run_definitions_updated on run_definitions (updated_at)')
+ conn.execute('create index if not exists ix_agent_runs_definition_created on agent_runs (definition_id, created_at)')
+ conn.execute('create index if not exists ix_agent_runs_status_created on agent_runs (status, created_at)')
+ conn.execute('create index if not exists ix_agent_runs_type_status_created on agent_runs (run_type, status, created_at)')
+ conn.execute('create index if not exists ix_agent_runs_session_created on agent_runs (session_id, created_at)')
+ conn.execute('create index if not exists ix_agent_runs_agent_created on agent_runs (agent_name, created_at)')
+
+
def _missing_head_schema_description(conn: sqlite3.Connection, tables: set[str]) -> str:
missing_parts = [f"tables {', '.join(sorted(HEAD_TABLES - tables))}"] if not HEAD_TABLES.issubset(tables) else []
for table, required_columns in HEAD_REQUIRED_COLUMNS.items():
diff --git a/storage/models.py b/storage/models.py
index dbdf5ca55..e362bdc6b 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -23,6 +23,27 @@ state_meta = Table(
Column("updated_at", String, nullable=False),
)
+agents = Table(
+ "agents",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column("name", String, nullable=False),
+ Column("normalized_name", String, nullable=False),
+ Column("description", Text, nullable=True),
+ Column("backend", String, nullable=False),
+ Column("model", String, nullable=True),
+ Column("reasoning_effort", String, nullable=True),
+ Column("system_prompt", Text, nullable=True),
+ Column("source", String, nullable=False),
+ Column("source_ref", Text, nullable=True),
+ Column("metadata_json", Text, nullable=False),
+ Column("created_at", String, nullable=False),
+ Column("updated_at", String, nullable=False),
+ UniqueConstraint("normalized_name", name="uq_agents_normalized_name"),
+ Index("ix_agents_backend", "backend"),
+ Index("ix_agents_updated", "updated_at"),
+)
+
scopes = Table(
"scopes",
metadata,
@@ -51,6 +72,7 @@ scope_settings = Table(
Column("enabled", Integer, nullable=False),
Column("role", String, nullable=True),
Column("workdir", Text, nullable=True),
+ Column("agent_name", String, nullable=True),
Column("agent_backend", String, nullable=True),
Column("agent_variant", String, nullable=True),
Column("model", String, nullable=True),
@@ -82,6 +104,8 @@ agent_sessions = Table(
metadata,
Column("id", String, primary_key=True),
Column("scope_id", String, ForeignKey("scopes.id", ondelete="SET NULL"), nullable=True),
+ Column("agent_id", String, nullable=True),
+ Column("agent_name", String, nullable=True),
Column("agent_backend", String, nullable=False),
Column("agent_variant", String, nullable=False),
Column("model", String, nullable=True),
@@ -120,15 +144,19 @@ runtime_records = Table(
Index("ix_runtime_records_workdir", "workdir"),
)
-background_tasks = Table(
- "background_tasks",
+run_definitions = Table(
+ "run_definitions",
metadata,
Column("id", String, primary_key=True),
- Column("task_type", String, nullable=False),
+ Column("definition_type", String, nullable=False),
Column("name", Text, nullable=True),
+ Column("agent_name", String, nullable=True),
+ Column("session_policy", String, nullable=True),
Column("session_id", String, nullable=True),
Column("legacy_session_key", Text, nullable=True),
Column("prompt", Text, nullable=True),
+ Column("message", Text, nullable=True),
+ Column("message_payload_json", Text, nullable=True),
Column("schedule_type", String, nullable=True),
Column("cron", Text, nullable=True),
Column("run_at", String, nullable=True),
@@ -154,24 +182,42 @@ background_tasks = Table(
Column("last_run_at", String, nullable=True),
Column("last_error", Text, nullable=True),
Column("last_exit_code", Integer, nullable=True),
+ Column("last_run_id", String, nullable=True),
Column("metadata_json", Text, nullable=False),
- Index("ix_background_tasks_type_enabled", "task_type", "enabled"),
- Index("ix_background_tasks_session", "session_id"),
- Index("ix_background_tasks_updated", "updated_at"),
+ Index("ix_run_definitions_type_enabled", "definition_type", "enabled"),
+ Index("ix_run_definitions_session", "session_id"),
+ Index("ix_run_definitions_agent", "agent_name"),
+ Index("ix_run_definitions_updated", "updated_at"),
)
-background_runs = Table(
- "background_runs",
+agent_runs = Table(
+ "agent_runs",
metadata,
Column("id", String, primary_key=True),
- Column("task_id", String, nullable=True),
+ Column("definition_id", String, nullable=True),
Column("run_type", String, nullable=False),
Column("status", String, nullable=False),
+ Column("source_kind", String, nullable=True),
+ Column("source_actor", Text, nullable=True),
+ Column("parent_run_id", String, nullable=True),
+ Column("agent_name", String, nullable=True),
+ Column("agent_id", String, nullable=True),
+ Column("agent_backend", String, nullable=True),
+ Column("model", String, nullable=True),
+ Column("reasoning_effort", String, nullable=True),
+ Column("session_policy", String, nullable=True),
Column("session_id", String, nullable=True),
Column("legacy_session_key", Text, nullable=True),
Column("post_to", String, nullable=True),
Column("deliver_key", Text, nullable=True),
Column("prompt", Text, nullable=True),
+ Column("message", Text, nullable=True),
+ Column("message_payload_json", Text, nullable=True),
+ Column("result_text", Text, nullable=True),
+ Column("result_payload_json", Text, nullable=True),
+ Column("message_ids_json", Text, nullable=True),
+ Column("cancel_requested", Integer, nullable=False, default=0),
+ Column("cancel_requested_at", String, nullable=True),
Column("pid", Integer, nullable=True),
Column("exit_code", Integer, nullable=True),
Column("error", Text, nullable=True),
@@ -182,14 +228,21 @@ background_runs = Table(
Column("completed_at", String, nullable=True),
Column("updated_at", String, nullable=False),
Column("metadata_json", Text, nullable=False),
- Index("ix_background_runs_task_created", "task_id", "created_at"),
- Index("ix_background_runs_status", "status"),
- Index("ix_background_runs_session_created", "session_id", "created_at"),
+ Index("ix_agent_runs_definition_created", "definition_id", "created_at"),
+ Index("ix_agent_runs_status_created", "status", "created_at"),
+ Index("ix_agent_runs_type_status_created", "run_type", "status", "created_at"),
+ Index("ix_agent_runs_session_created", "session_id", "created_at"),
+ Index("ix_agent_runs_agent_created", "agent_name", "created_at"),
)
+# Backwards-compatible Python aliases for legacy callers. The physical table
+# names are the new domain names.
+background_tasks = run_definitions
+background_runs = agent_runs
+
imported_state_tables = [
- background_runs,
- background_tasks,
+ agent_runs,
+ run_definitions,
scope_settings,
auth_codes,
agent_sessions,
diff --git a/storage/sessions_service.py b/storage/sessions_service.py
index 668a58abe..5a5570c4a 100644
--- a/storage/sessions_service.py
+++ b/storage/sessions_service.py
@@ -54,12 +54,97 @@ class SQLiteSessionsService:
.limit(1)
).scalar_one_or_none()
+ def get_agent_session_by_id(self, session_id: str) -> dict[str, Any] | None:
+ with self.engine.connect() as conn:
+ row = conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == str(session_id)).limit(1)
+ ).mappings().first()
+ return dict(row) if row else None
+
+ def reserve_agent_session(
+ self,
+ *,
+ scope_key: str,
+ agent_backend: str,
+ session_anchor: str,
+ agent_id: str | None = None,
+ agent_name: str | None = None,
+ model: str | None = None,
+ reasoning_effort: str | None = None,
+ ) -> str | None:
+ now = _utc_now_iso()
+ backend = str(agent_backend or "default")
+ with self.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(conn, str(scope_key), now=now)
+ if scope_id is None:
+ return None
+ return _insert_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ scope_key=str(scope_key),
+ agent_name=backend,
+ session_anchor=session_anchor,
+ native_session_id="",
+ vibe_agent_id=agent_id,
+ vibe_agent_name=agent_name,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ now=now,
+ )
+
+ def reserve_private_agent_session(
+ self,
+ *,
+ platform: str,
+ agent_backend: str,
+ session_anchor: str,
+ agent_id: str | None = None,
+ agent_name: str | None = None,
+ model: str | None = None,
+ reasoning_effort: str | None = None,
+ ) -> str:
+ now = _utc_now_iso()
+ platform_key = str(platform or "slack").strip() or "slack"
+ native_id = f"private-agent-run-{secrets.token_hex(8)}"
+ scope_key = f"{platform_key}::{native_id}"
+ backend = str(agent_backend or "default")
+ metadata_payload = {"private_agent_run": True, "no_delivery": True}
+ with self.engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn,
+ platform_key,
+ "user",
+ native_id,
+ display_name="Private Agent Run",
+ native_type="private_agent_run",
+ is_private=True,
+ supports_threads=False,
+ metadata=metadata_payload,
+ now=now,
+ )
+ return _insert_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ scope_key=scope_key,
+ agent_name=backend,
+ session_anchor=session_anchor,
+ native_session_id="",
+ vibe_agent_id=agent_id,
+ vibe_agent_name=agent_name,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ session_metadata=metadata_payload,
+ now=now,
+ )
+
def ensure_agent_session_id(
self,
*,
scope_key: str,
agent_name: str,
session_anchor: str,
+ vibe_agent_id: str | None = None,
+ vibe_agent_name: str | None = None,
) -> str | None:
"""Ensure a Vibe-owned agent-session row exists before native binding."""
now = _utc_now_iso()
@@ -82,6 +167,10 @@ class SQLiteSessionsService:
agent_name=agent_name,
session_anchor=session_anchor,
native_session_id="",
+ vibe_agent_id=vibe_agent_id,
+ vibe_agent_name=vibe_agent_name,
+ model=None,
+ reasoning_effort=None,
now=now,
)
@@ -92,6 +181,8 @@ class SQLiteSessionsService:
agent_name: str,
session_anchor: str,
native_session_id: Any,
+ vibe_agent_id: str | None = None,
+ vibe_agent_name: str | None = None,
) -> str | None:
"""Bind a backend-native session id to the stable Vibe session row."""
now = _utc_now_iso()
@@ -114,19 +205,24 @@ class SQLiteSessionsService:
agent_name=agent_name,
session_anchor=session_anchor,
native_session_id=encoded_session_id,
+ vibe_agent_id=vibe_agent_id,
+ vibe_agent_name=vibe_agent_name,
+ model=None,
+ reasoning_effort=None,
now=now,
)
- conn.execute(
- agent_sessions.update()
- .where(agent_sessions.c.id == row_id)
- .values(
- native_session_id=encoded_session_id,
- workdir=_workdir_from_anchor(str(session_anchor)),
- status="active",
- updated_at=now,
- last_active_at=now,
- )
- )
+ values = {
+ "native_session_id": encoded_session_id,
+ "workdir": _workdir_from_anchor(str(session_anchor)),
+ "status": "active",
+ "updated_at": now,
+ "last_active_at": now,
+ }
+ if vibe_agent_id is not None:
+ values["agent_id"] = vibe_agent_id
+ if vibe_agent_name is not None:
+ values["agent_name"] = vibe_agent_name
+ conn.execute(agent_sessions.update().where(agent_sessions.c.id == row_id).values(**values))
return row_id
def delete_agent_session(
@@ -758,6 +854,11 @@ def _insert_agent_session_row(
agent_name: str,
session_anchor: str,
native_session_id: Any,
+ vibe_agent_id: str | None = None,
+ vibe_agent_name: str | None = None,
+ model: str | None = None,
+ reasoning_effort: str | None = None,
+ session_metadata: dict[str, Any] | None = None,
now: str,
) -> str:
used_session_ids = {
@@ -767,20 +868,25 @@ def _insert_agent_session_row(
row_id = _new_session_id(used_session_ids)
agent_variant = str(agent_name) or "default"
anchor = str(session_anchor)
+ metadata_payload = {"legacy_scope_key": scope_key}
+ if session_metadata:
+ metadata_payload.update(session_metadata)
conn.execute(
agent_sessions.insert().values(
id=row_id,
scope_id=scope_id,
+ agent_id=vibe_agent_id,
+ agent_name=vibe_agent_name,
agent_backend=_agent_backend(agent_variant),
agent_variant=agent_variant,
- model=None,
- reasoning_effort=None,
+ model=model,
+ reasoning_effort=reasoning_effort,
session_anchor=anchor,
workdir=_workdir_from_anchor(anchor),
native_session_id=encode_session_value(native_session_id),
title=None,
status="active",
- metadata_json=_json_dumps({"legacy_scope_key": scope_key}),
+ metadata_json=_json_dumps(metadata_payload),
created_at=now,
updated_at=now,
last_active_at=now,
diff --git a/storage/settings_service.py b/storage/settings_service.py
index ec58abf90..93aa0fbdb 100644
--- a/storage/settings_service.py
+++ b/storage/settings_service.py
@@ -86,6 +86,7 @@ class SQLiteSettingsService:
enabled=_bool_int(state.guild_default_enabled.get(platform, False)),
role=None,
workdir=None,
+ agent_name=None,
agent_backend=None,
agent_variant=None,
model=None,
@@ -107,6 +108,7 @@ class SQLiteSettingsService:
enabled=_bool_int(item.enabled),
role=None,
workdir=None,
+ agent_name=None,
agent_backend=None,
agent_variant=None,
model=None,
@@ -332,6 +334,7 @@ def _routing_columns(routing: RoutingSettings) -> dict[str, str | None]:
or routing.opencode_reasoning_effort
)
return {
+ "agent_name": routing.agent_name,
"agent_backend": backend,
"agent_variant": variant,
"model": model,
@@ -342,6 +345,7 @@ def _routing_columns(routing: RoutingSettings) -> dict[str, str | None]:
def _routing_from_row(row: dict[str, Any], payload: dict[str, Any]) -> RoutingSettings:
routing_payload = payload.get("routing") or {}
routing = RoutingSettings(
+ agent_name=routing_payload.get("agent_name") or routing_payload.get("agent"),
agent_backend=routing_payload.get("agent_backend"),
opencode_agent=routing_payload.get("opencode_agent"),
opencode_model=routing_payload.get("opencode_model"),
@@ -354,6 +358,9 @@ def _routing_from_row(row: dict[str, Any], payload: dict[str, Any]) -> RoutingSe
codex_reasoning_effort=routing_payload.get("codex_reasoning_effort"),
)
backend = row.get("agent_backend")
+ stored_agent_name = row.get("agent_name")
+ if stored_agent_name:
+ routing.agent_name = routing.agent_name or str(stored_agent_name)
if backend:
routing.agent_backend = str(backend)
variant = row.get("agent_variant")
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index c07d9b2c0..ed121c7f5 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -41,6 +41,11 @@ def _parse_hook_send(argv: list[str]):
return parser.parse_args(["hook", "send", *argv])
+def _parse_agent_run(argv: list[str]):
+ parser = cli.build_parser()
+ return parser.parse_args(["agent", "run", *argv])
+
+
def _capture_stderr_json(func, *args):
stderr = io.StringIO()
with redirect_stderr(stderr):
@@ -55,7 +60,7 @@ def test_task_add_rejects_unsupported_platform() -> None:
"foo::channel::C123",
"--cron",
"0 * * * *",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -76,7 +81,7 @@ def test_task_add_rejects_disabled_platform_even_with_credentials_present() -> N
"discord::channel::C123",
"--cron",
"0 * * * *",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -100,7 +105,7 @@ def test_task_help_describes_session_id_guidance(capsys) -> None:
assert exc.value.code == 0
captured = capsys.readouterr()
- assert "Create, inspect, and control scheduled prompts for Vibe Remote." in captured.out
+ assert "Create, inspect, and control scheduled Agent messages for Vibe Remote." in captured.out
assert "vibe task add --session-id sesk8m4q2p7x" in captured.out
assert "{add,update,list,show,pause,resume,run,remove}" in captured.out
assert "rm (remove)" not in captured.out
@@ -132,7 +137,7 @@ def test_hook_send_help_describes_runtime_effects(capsys) -> None:
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 "`--post-to channel` changes where the message is posted, not which session is continued." in captured.out
- assert "`--prompt` and `--prompt-file` provide the one-shot async content that will be queued immediately." 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
@@ -211,7 +216,7 @@ def test_task_add_rejects_invalid_session_key_with_hint() -> None:
"slack::thread::123",
"--cron",
"0 * * * *",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -240,7 +245,7 @@ def test_task_add_rejects_conflicting_delivery_target_flags(capsys) -> None:
"slack::channel::C999",
"--cron",
"0 * * * *",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -261,7 +266,7 @@ def test_task_add_rejects_post_to_thread_without_thread_session_key() -> None:
"thread",
"--cron",
"0 * * * *",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -282,7 +287,7 @@ def test_task_add_rejects_cross_platform_deliver_key() -> None:
"discord::channel::C999",
"--cron",
"0 * * * *",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -305,7 +310,7 @@ def test_task_add_rejects_invalid_cron_with_example() -> None:
"slack::channel::C123",
"--cron",
"bad cron",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -325,7 +330,7 @@ def test_task_add_rejects_invalid_timezone() -> None:
"slack::channel::C123",
"--cron",
"0 * * * *",
- "--prompt",
+ "--message",
"hello",
"--timezone",
"Mars/Base",
@@ -483,7 +488,7 @@ def test_task_show_includes_derived_schedule_fields(tmp_path: Path, capsys) -> N
assert result == 0
payload = json.loads(capsys.readouterr().out)
assert payload["task"]["display_name"] == "Hourly summary"
- assert payload["task"]["prompt_preview"] == "recurring summary prompt"
+ assert payload["task"]["message_preview"] == "recurring summary prompt"
assert payload["task"]["next_run_at"] is not None
assert payload["task"]["state"] == "active"
assert payload["task"]["last_status"] == "never_run"
@@ -567,7 +572,7 @@ def test_task_update_modifies_existing_task_without_changing_id(tmp_path: Path,
)
parser = cli.build_parser()
args = parser.parse_args(
- ["task", "update", task.id, "--name", "Morning summary", "--cron", "*/30 * * * *", "--prompt", "updated"]
+ ["task", "update", task.id, "--name", "Morning summary", "--cron", "*/30 * * * *", "--message", "updated"]
)
with patch("vibe.cli._task_store", return_value=store):
@@ -634,7 +639,7 @@ def test_task_update_replaces_post_to_with_deliver_key(tmp_path: Path, capsys) -
def test_task_add_returns_reachability_warning_for_unbound_lark_dm(tmp_path: Path, capsys) -> None:
parser = cli.build_parser()
args = parser.parse_args(
- ["task", "add", "--session-key", "lark::user::ou_123", "--cron", "0 * * * *", "--prompt", "hello"]
+ ["task", "add", "--session-key", "lark::user::ou_123", "--cron", "0 * * * *", "--message", "hello"]
)
fake_store = SimpleNamespace(get_user=lambda *args, **kwargs: None)
@@ -651,7 +656,7 @@ def test_task_add_returns_reachability_warning_for_unbound_lark_dm(tmp_path: Pat
def test_hook_send_rejects_invalid_session_key_with_hint() -> None:
- args = _parse_hook_send(["--session-key", "slack::thread::123", "--prompt", "hello"])
+ args = _parse_hook_send(["--session-key", "slack::thread::123", "--message", "hello"])
with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):
result, payload = _capture_stderr_json(cli.cmd_hook_send, args)
@@ -675,7 +680,7 @@ def test_hook_send_rejects_conflicting_delivery_target_flags(capsys) -> None:
"channel",
"--deliver-key",
"slack::channel::C999",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -694,7 +699,7 @@ def test_hook_send_rejects_cross_platform_deliver_key() -> None:
"slack::channel::C123",
"--deliver-key",
"discord::channel::C999",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -717,7 +722,7 @@ def test_hook_send_enqueues_request(tmp_path: Path, capsys) -> None:
"slack::channel::C123::thread::171717.123",
"--post-to",
"channel",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -742,7 +747,7 @@ def test_hook_send_returns_reachability_warning_for_unbound_lark_dm(tmp_path: Pa
[
"--session-key",
"lark::user::ou_123",
- "--prompt",
+ "--message",
"hello",
]
)
@@ -761,6 +766,112 @@ def test_hook_send_returns_reachability_warning_for_unbound_lark_dm(tmp_path: Pa
assert payload["warnings"][0]["code"] == "lark_user_not_bound"
+def test_agent_run_private_async_reserves_session_and_queues_request(tmp_path: Path, capsys) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent = agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(["--agent", "worker", "--async", "--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),
+ patch("vibe.cli._primary_platform", return_value="slack"),
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["session_id"].startswith("ses")
+ assert payload["session_policy"] == "none"
+ assert payload["agent"] == agent.name
+ queued = json.loads((request_store.pending_dir / f"{payload['run_id']}.json").read_text())
+ assert queued["request_type"] == "agent_run"
+ assert queued["session_id"] == payload["session_id"]
+ assert queued["agent_name"] == "worker"
+
+
+def test_agent_run_rejects_deprecated_prompt_argument(tmp_path: Path) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ args = _parse_agent_run(["--agent", "worker", "--async", "--prompt", "hello"])
+
+ with patch("vibe.cli._agent_store", return_value=agent_store):
+ result, payload = _capture_stderr_json(cli.cmd_agent_run, args)
+
+ assert result == 1
+ assert payload["code"] == "deprecated_prompt_argument"
+
+
+def test_agent_run_rejects_per_run_for_direct_invocation() -> None:
+ args = _parse_agent_run(["--agent", "worker", "--create-session-per-run", "--message", "hello"])
+
+ result, payload = _capture_stderr_json(cli.cmd_agent_run, args)
+
+ assert result == 1
+ assert payload["code"] == "invalid_session_policy"
+
+
+def test_agent_run_rejects_backend_mismatch_for_existing_session(tmp_path: Path) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="codex-worker", backend="codex")
+ from storage.sessions_service import SQLiteSessionsService
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ session_id = service.reserve_private_agent_session(
+ platform="slack",
+ agent_backend="claude",
+ session_anchor="slack_private-agent-test",
+ )
+ finally:
+ service.close()
+ args = _parse_agent_run(["--agent", "codex-worker", "--session-id", session_id, "--message", "hello"])
+
+ with (
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result, payload = _capture_stderr_json(cli.cmd_agent_run, args)
+
+ assert result == 1
+ assert payload["code"] == "agent_session_backend_mismatch"
+
+
+def test_task_add_rejects_deprecated_prompt_argument() -> None:
+ args = _parse_task_add(
+ [
+ "--session-key",
+ "slack::channel::C123",
+ "--cron",
+ "0 * * * *",
+ "--prompt",
+ "hello",
+ ]
+ )
+
+ with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):
+ result, payload = _capture_stderr_json(cli.cmd_task_add, args)
+
+ assert result == 1
+ assert payload["code"] == "deprecated_prompt_argument"
+ assert "--message" in payload["hint"]
+
+
+def test_hook_send_rejects_deprecated_prompt_argument() -> None:
+ args = _parse_hook_send(["--session-key", "slack::channel::C123", "--prompt", "hello"])
+
+ with patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})):
+ result, payload = _capture_stderr_json(cli.cmd_hook_send, args)
+
+ assert result == 1
+ assert payload["code"] == "deprecated_prompt_argument"
+ assert "--message" in payload["hint"]
+
+
def test_task_remove_alias_parses_to_remove_command() -> None:
parser = cli.build_parser()
args = parser.parse_args(["task", "remove", "task-123"])
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index b4ff1814e..541f54a22 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -201,7 +201,7 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("## 3. Scheduled tasks, watches, and hooks", prompt)
self.assertIn("`vibe task add`", prompt)
- self.assertIn("`vibe hook send --session-id ... --prompt ...`", prompt)
+ self.assertIn("`vibe agent run --async --session-id ... --message ...`", prompt)
self.assertIn("`vibe watch add`", prompt)
self.assertIn("Use `vibe task add` for saved work that should run later on a schedule or at one exact time.", prompt)
self.assertIn(
@@ -226,11 +226,11 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
)
self.assertIn("If `--timezone` is omitted, the task uses the local system timezone at creation time.", prompt)
self.assertIn(
- "Use `--prompt \"...\"` or `--prompt-file <path>` for task and hook content. Use `--prefix \"...\"` on watches for the follow-up instruction that is prepended before waiter stdout; when both exist, Vibe Remote joins them with a blank line.",
+ "Use `--message \"...\"` or `--message-file <path>` for task and agent-run content. Use `--prefix \"...\"` on watches for the follow-up instruction that is prepended before waiter stdout; when both exist, Vibe Remote joins them with a blank line.",
prompt,
)
self.assertIn(
- "If this is your first time using these commands, read `vibe task add --help`, `vibe watch add --help`, or `vibe hook send --help` before creating anything.",
+ "If this is your first time using these commands, read `vibe task add --help`, `vibe watch add --help`, or `vibe agent run --help` before creating anything.",
prompt,
)
self.assertIn("A shared user context and preferences file is available at ", prompt)
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 0d07b9d47..20bdd7423 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -690,6 +690,42 @@ def test_drain_requests_executes_hook_send(tmp_path: Path) -> None:
assert payload["ok"] is True
+def test_drain_requests_agent_run_passes_agent_name(tmp_path: Path) -> None:
+ request_store = TaskExecutionStore(tmp_path / "task_requests")
+ request = request_store.enqueue_agent_run(
+ session_key="slack::channel::C123",
+ message="review build",
+ agent_name="release-reviewer",
+ )
+ settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None))
+ calls = []
+
+ async def _handle_scheduled_message(context, message, parsed_session_key=None):
+ calls.append((context, message, parsed_session_key))
+ return None
+
+ controller = SimpleNamespace(
+ platform_settings_managers={"slack": settings_manager},
+ message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),
+ )
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ asyncio.run(service._drain_requests())
+
+ assert len(calls) == 1
+ context, message, parsed = calls[0]
+ assert message == "review build"
+ assert parsed.to_key() == "slack::channel::C123"
+ assert context.message_id == f"agent_run:{request.id}"
+ assert context.platform_specific["vibe_agent_name"] == "release-reviewer"
+ payload = json.loads((request_store.completed_dir / f"{request.id}.json").read_text(encoding="utf-8"))
+ assert payload["ok"] is True
+
+
def test_run_task_request_does_not_disable_one_shot(tmp_path: Path) -> None:
path = tmp_path / "scheduled_tasks.json"
request_store = TaskExecutionStore(tmp_path / "task_requests")
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index b53432e3a..a51b43c29 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -31,17 +31,17 @@ def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:
assert "scope_settings" in tables
assert "agent_sessions" in tables
assert "runtime_records" in tables
- assert "background_tasks" in tables
- assert "background_runs" in tables
+ assert "run_definitions" in tables
+ assert "agent_runs" in tables
background_columns = {
row[1]
for row in conn.execute(
- "pragma table_info(background_tasks)",
+ "pragma table_info(run_definitions)",
)
}
assert "deleted_at" in background_columns
version = conn.execute("select version_num from alembic_version").fetchone()
- assert version == ("20260515_0002",)
+ assert version == ("20260522_0003",)
def test_initial_migration_is_schema_snapshot() -> None:
@@ -79,7 +79,7 @@ def test_run_migrations_stamps_existing_initial_schema(tmp_path: Path) -> None:
with sqlite3.connect(db_path) as conn:
version = conn.execute("select version_num from alembic_version").fetchone()
- assert version == ("20260515_0002",)
+ assert version == ("20260522_0003",)
def test_run_migrations_stamps_existing_initial_schema_with_empty_version_table(tmp_path: Path) -> None:
@@ -99,7 +99,7 @@ def test_run_migrations_stamps_existing_initial_schema_with_empty_version_table(
with sqlite3.connect(db_path) as conn:
version = conn.execute("select version_num from alembic_version").fetchone()
- assert version == ("20260515_0002",)
+ assert version == ("20260522_0003",)
def test_run_migrations_repairs_head_columns_before_stamping_head(tmp_path: Path) -> None:
@@ -113,7 +113,7 @@ def test_run_migrations_repairs_head_columns_before_stamping_head(tmp_path: Path
with sqlite3.connect(db_path) as conn:
columns = [
row
- for row in conn.execute("pragma table_info(background_tasks)").fetchall()
+ for row in conn.execute("pragma table_info(run_definitions)").fetchall()
if row[1] != "deleted_at"
]
column_defs = []
@@ -126,9 +126,9 @@ def test_run_migrations_repairs_head_columns_before_stamping_head(tmp_path: Path
if default_value is not None:
definition += f" DEFAULT {default_value}"
column_defs.append(definition)
- conn.execute('alter table "background_tasks" rename to "background_tasks_old"')
- conn.execute(f'create table "background_tasks" ({", ".join(column_defs)})')
- conn.execute('drop table "background_tasks_old"')
+ conn.execute('alter table "run_definitions" rename to "run_definitions_old"')
+ conn.execute(f'create table "run_definitions" ({", ".join(column_defs)})')
+ conn.execute('drop table "run_definitions_old"')
conn.execute("create table alembic_version (version_num varchar(32) not null)")
conn.commit()
@@ -138,8 +138,8 @@ def test_run_migrations_repairs_head_columns_before_stamping_head(tmp_path: Path
with sqlite3.connect(db_path) as conn:
version = conn.execute("select version_num from alembic_version").fetchone()
- background_columns = {row[1] for row in conn.execute("pragma table_info(background_tasks)")}
- assert version == ("20260515_0002",)
+ background_columns = {row[1] for row in conn.execute("pragma table_info(run_definitions)")}
+ assert version == ("20260522_0003",)
assert "deleted_at" in background_columns
assert background_tables_ready(db_path) is True
@@ -382,9 +382,9 @@ def test_ensure_sqlite_state_imports_background_json(tmp_path: Path) -> None:
assert report.counts["background_runs_imported"] == 1
with sqlite3.connect(db_path) as conn:
tasks = conn.execute(
- "select task_type, session_id, legacy_session_key from background_tasks order by id"
+ "select definition_type, session_id, legacy_session_key from run_definitions order by id"
).fetchall()
- runs = conn.execute("select run_type, status, session_id from background_runs").fetchall()
+ runs = conn.execute("select run_type, status, session_id from agent_runs").fetchall()
assert tasks == [
("scheduled", "sesk8m4q2p7x", "slack::channel::C123"),
("watch", "sesk8m4q2p7x", "slack::channel::C123"),
diff --git a/vibe/cli.py b/vibe/cli.py
index 442625023..fe4fe65ad 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -15,6 +15,7 @@ from datetime import datetime, timezone
from pathlib import Path
from textwrap import dedent
from typing import Optional
+from uuid import uuid4
from zoneinfo import ZoneInfo
from apscheduler.triggers.cron import CronTrigger
@@ -32,6 +33,7 @@ from config.v2_config import (
V2Config,
)
from core.scheduled_tasks import ScheduledTaskStore, TaskExecutionStore, parse_session_key, resolve_session_id_target
+from core.vibe_agents import VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
from core.watches import (
DEFAULT_RETRY_EXIT_CODE,
WATCH_RECONCILE_INTERVAL_SECONDS,
@@ -80,7 +82,9 @@ class VibeArgumentParser(argparse.ArgumentParser):
def error(self, message):
payload = {
+ "schema_version": 1,
"ok": False,
+ "kind": "error",
"code": "invalid_arguments",
"error": message,
"usage": self.format_usage().strip(),
@@ -114,7 +118,9 @@ class TaskCliError(ValueError):
def _print_task_error(exc: Exception, *, help_command: str | None = None) -> None:
if isinstance(exc, TaskCliError):
payload = {
+ "schema_version": 1,
"ok": False,
+ "kind": "error",
"code": exc.code,
"error": str(exc),
}
@@ -128,7 +134,9 @@ def _print_task_error(exc: Exception, *, help_command: str | None = None) -> Non
payload["details"] = exc.details
else:
payload = {
+ "schema_version": 1,
"ok": False,
+ "kind": "error",
"code": "task_command_failed",
"error": str(exc),
}
@@ -137,6 +145,14 @@ def _print_task_error(exc: Exception, *, help_command: str | None = None) -> Non
print(json.dumps(payload, indent=2), file=sys.stderr)
+def _cli_payload(kind: str, **fields) -> dict:
+ return {"schema_version": 1, "ok": True, "kind": kind, **fields}
+
+
+def _print_cli_payload(kind: str, **fields) -> None:
+ print(json.dumps(_cli_payload(kind, **fields), indent=2))
+
+
def _non_negative_float(value: str) -> float:
parsed = float(value)
if not math.isfinite(parsed):
@@ -150,11 +166,11 @@ def _task_examples_text() -> str:
return dedent(
"""\
Examples:
- vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --prompt 'Share the hourly summary.'
+ vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'
vibe task update 12ab34cd56ef --cron '*/30 * * * *' --name 'Half-hour summary'
vibe task run 12ab34cd56ef
- vibe task add --session-id sesk8m4q2p7x --post-to channel --cron '*/5 * * * *' --prompt 'Tell a new joke each time.'
- vibe task add --session-id sesk8m4q2p7x --at '2026-03-31T09:00:00+08:00' --prompt-file briefing.md
+ vibe task add --session-id sesk8m4q2p7x --post-to channel --cron '*/5 * * * *' --message 'Tell a new joke each time.'
+ vibe task add --session-id sesk8m4q2p7x --at '2026-03-31T09:00:00+08:00' --message-file briefing.md
"""
)
@@ -172,14 +188,14 @@ def _task_add_examples_text() -> str:
If no session id is available, trigger this from an active Vibe Remote conversation instead of guessing.
`--post-to channel` changes where the message is posted, not which session is continued.
Use --deliver-key only when delivery must go to a different explicit target.
- `--prompt` and `--prompt-file` provide the stored task content that will be injected each time the task runs.
+ `--message` and `--message-file` provide the stored user message that will be sent each time the task runs.
Use --cron for recurring jobs and --at for one-shot jobs.
--timezone controls how --cron and naive --at timestamps are interpreted.
Examples:
- vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --prompt 'Share the hourly summary.'
- vibe task add --session-id sesk8m4q2p7x --post-to channel --cron '*/5 * * * *' --prompt 'Tell a new joke each time.'
- vibe task add --session-id sesk8m4q2p7x --deliver-key 'slack::channel::C999' --cron '0 9 * * *' --prompt 'Post the daily summary in the announcements channel.'
+ vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'
+ vibe task add --session-id sesk8m4q2p7x --post-to channel --cron '*/5 * * * *' --message 'Tell a new joke each time.'
+ vibe task add --session-id sesk8m4q2p7x --deliver-key 'slack::channel::C999' --cron '0 9 * * *' --message 'Post the daily summary in the announcements channel.'
"""
)
@@ -192,7 +208,7 @@ def _task_update_examples_text() -> str:
Common updates:
vibe task update 12ab34cd56ef --name 'Morning summary'
vibe task update 12ab34cd56ef --cron '*/30 * * * *'
- vibe task update 12ab34cd56ef --prompt 'Send a shorter summary.'
+ vibe task update 12ab34cd56ef --message 'Send a shorter summary.'
vibe task update 12ab34cd56ef --session-id sesk8m4q2p7x --post-to channel
vibe task update 12ab34cd56ef --deliver-key 'slack::channel::C999'
vibe task update 12ab34cd56ef --reset-delivery
@@ -220,12 +236,12 @@ def _hook_send_examples_text() -> str:
If no session id is available, trigger this from an active Vibe Remote conversation instead of guessing.
`--post-to channel` changes where the message is posted, not which session is continued.
Use --deliver-key only when delivery must go to a different explicit target.
- `--prompt` and `--prompt-file` provide the one-shot async content that will be queued immediately.
+ `--message` and `--message-file` provide the one-shot async user message that will be queued immediately.
Examples:
- vibe hook send --session-id sesk8m4q2p7x --prompt 'The export finished. Share the summary.'
- vibe hook send --session-id sesk8m4q2p7x --post-to channel --prompt 'Share the benchmark result in the channel.'
- vibe hook send --session-id sesk8m4q2p7x --deliver-key 'slack::channel::C999' --prompt 'Post the deployment summary in announcements.'
+ 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.'
"""
)
@@ -543,6 +559,75 @@ def _default_timezone_name() -> str:
def _resolve_prompt_input(args, *, help_command: str, example_command: str) -> 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 'Share the hourly summary.'",
+ help_command=help_command,
+ )
+ return _resolve_message_input(args, help_command=help_command, example_command=example_command)
+
+
+def _resolve_message_input(args, *, help_command: str, example_command: str) -> 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 'Share the hourly summary.'",
+ help_command=help_command,
+ )
+ message = (getattr(args, "message", None) or "").strip()
+ message_file = getattr(args, "message_file", None)
+ if message and message_file:
+ raise TaskCliError(
+ "use either --message or --message-file",
+ code="conflicting_message_inputs",
+ hint="Pass inline text with --message or load it from disk with --message-file, but not both.",
+ help_command=help_command,
+ )
+ if message:
+ return message
+ if getattr(args, "message", None) is not None:
+ raise TaskCliError(
+ "message text cannot be empty",
+ code="empty_message",
+ hint="Provide non-empty text after --message, or use --message-file with a readable text file.",
+ help_command=help_command,
+ )
+ if message_file:
+ try:
+ content = Path(message_file).read_text(encoding="utf-8").strip()
+ except OSError as exc:
+ raise TaskCliError(
+ f"failed to read message file: {exc}",
+ code="message_file_read_failed",
+ hint="Use --message-file with a readable UTF-8 text file.",
+ example=f"{example_command} --message-file briefing.md",
+ help_command=help_command,
+ details={"message_file": message_file},
+ ) from exc
+ if not content:
+ raise TaskCliError(
+ "message file is empty",
+ code="empty_message",
+ hint="Put the message text in the file, or pass it directly with --message.",
+ example=f"{example_command} --message 'Share the hourly summary.'",
+ help_command=help_command,
+ details={"message_file": message_file},
+ )
+ return content
+ raise TaskCliError(
+ "one of --message or --message-file is required",
+ code="missing_message",
+ hint="Pass inline text with --message or load it from disk with --message-file.",
+ help_command=help_command,
+ )
+
+
+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)
if prompt and prompt_file:
@@ -681,18 +766,18 @@ def _validate_watch_timing(
code="invalid_watch_lifetime_timeout",
hint="Use --lifetime-timeout only on forever watches.",
help_command=help_command,
- )
+ )
-def _task_prompt_preview(prompt: str, *, max_chars: int = 72) -> str:
- compact = " ".join((prompt or "").split())
+def _task_message_preview(message: str, *, max_chars: int = 72) -> str:
+ compact = " ".join((message or "").split())
if len(compact) <= max_chars:
return compact
return compact[: max_chars - 1].rstrip() + "…"
def _task_display_name(task) -> str:
- return task.name or _task_prompt_preview(task.prompt)
+ return task.name or _task_message_preview(task.prompt)
def _task_state(task) -> str:
@@ -764,7 +849,7 @@ def _task_next_run_sort_key(task):
def _task_payload(task, *, brief: bool = False):
derived = {
"display_name": _task_display_name(task),
- "prompt_preview": _task_prompt_preview(task.prompt),
+ "message_preview": _task_message_preview(task.prompt),
"state": _task_state(task),
"last_status": _task_last_status(task),
"next_run_at": _task_next_run_at(task),
@@ -782,6 +867,7 @@ def _task_payload(task, *, brief: bool = False):
"schedule_summary": derived["schedule_summary"],
"session_id": task.session_id,
"session_key": task.session_key,
+ "agent_name": task.agent_name,
"post_to": task.post_to,
"deliver_key": task.deliver_key,
"timezone": task.timezone,
@@ -811,6 +897,25 @@ def _task_request_store() -> TaskExecutionStore:
return TaskExecutionStore()
+def _agent_store() -> VibeAgentStore:
+ return VibeAgentStore()
+
+
+def _session_service():
+ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
+ from storage.sessions_service import SQLiteSessionsService
+
+ ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
+ return SQLiteSessionsService(paths.get_sqlite_state_path())
+
+
+def _primary_platform() -> str:
+ try:
+ return _ensure_config().platform
+ except Exception:
+ return "slack"
+
+
def _watch_store() -> ManagedWatchStore:
return ManagedWatchStore()
@@ -924,7 +1029,7 @@ def _resolve_session_target_args(
"one of --session-id or --session-key is required",
code="missing_session_target",
hint="Use --session-id with the current Agent Session ID.",
- example="vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --prompt 'Share the hourly summary.'",
+ example="vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'",
help_command=help_command,
)
return session_id or None, session_key
@@ -1010,6 +1115,14 @@ def _collect_target_warnings(*targets) -> list[dict]:
return warnings
+def _validate_agent_name_arg(agent_name: Optional[str]) -> Optional[str]:
+ value = (agent_name or "").strip()
+ if not value:
+ return None
+ _agent_store().require(value)
+ return value
+
+
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 [])
@@ -1077,6 +1190,7 @@ def _watch_payload(watch, runtime_entry: Optional[dict[str, object]], *, brief:
"mode": watch.mode,
"session_id": watch.session_id,
"session_key": watch.session_key,
+ "agent_name": watch.agent_name,
"timeout_seconds": watch.timeout_seconds,
"lifetime_timeout_seconds": watch.lifetime_timeout_seconds,
"enabled": watch.enabled,
@@ -1088,6 +1202,38 @@ def _watch_payload(watch, runtime_entry: Optional[dict[str, object]], *, brief:
return payload
+def _agent_payload(agent, *, brief: bool = False) -> dict:
+ payload = agent.to_dict()
+ if brief:
+ return {
+ "id": payload["id"],
+ "name": payload["name"],
+ "backend": payload["backend"],
+ "model": payload["model"],
+ "reasoning_effort": payload["reasoning_effort"],
+ "source": payload["source"],
+ "updated_at": payload["updated_at"],
+ }
+ return payload
+
+
+def _run_payload(run: dict, *, brief: bool = False) -> dict:
+ 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"),
+ }
+ return run
+
+
def _seconds_since_iso(timestamp: object) -> float | None:
if not isinstance(timestamp, str) or not timestamp.strip():
return None
@@ -1171,23 +1317,37 @@ def _wait_for_watch_startup(
def cmd_task_add(args):
try:
+ schedule_type = "cron" if args.cron else "at"
+ session_policy = _validate_definition_session_policy(
+ args,
+ schedule_type=schedule_type,
+ help_command="vibe task add --help",
+ )
+ message = _resolve_prompt_input(
+ 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=True,
+ required=session_policy == "existing",
help_command="vibe task add --help",
)
+ if session_policy == "create_once":
+ session_id = _reserve_definition_session(
+ agent_name=agent_name,
+ deliver_key=args.deliver_key,
+ help_command="vibe task add --help",
+ )
+ validation_session_key = session_key or (args.deliver_key if session_policy == "create_per_run" else "")
session_target, delivery_target = _validate_delivery_args(
session_id=session_id,
- session_key=session_key,
+ session_key=validation_session_key,
post_to=getattr(args, "post_to", None),
deliver_key=getattr(args, "deliver_key", None),
help_command="vibe task add --help",
)
- prompt = _resolve_prompt_input(
- args,
- help_command="vibe task add --help",
- example_command="vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *'",
- )
timezone_name = args.timezone or _default_timezone_name()
try:
timezone = ZoneInfo(timezone_name)
@@ -1220,8 +1380,10 @@ def cmd_task_add(args):
session_id=session_id,
post_to=args.post_to,
deliver_key=args.deliver_key,
- prompt=prompt,
+ prompt=message,
schedule_type="cron",
+ agent_name=agent_name,
+ session_policy=session_policy,
cron=args.cron,
timezone_name=timezone_name,
)
@@ -1243,13 +1405,21 @@ def cmd_task_add(args):
session_id=session_id,
post_to=args.post_to,
deliver_key=args.deliver_key,
- prompt=prompt,
+ prompt=message,
schedule_type="at",
+ agent_name=agent_name,
+ session_policy=session_policy,
run_at=run_at,
timezone_name=timezone_name,
)
warnings = _collect_target_warnings(session_target, delivery_target)
- print(json.dumps({"ok": True, "task": _task_payload(task), "warnings": warnings}, indent=2))
+ task_payload = _task_payload(task)
+ _print_cli_payload(
+ "run_definition",
+ definition=task_payload,
+ task=task_payload,
+ warnings=warnings,
+ )
return 0
except Exception as exc:
_print_task_error(exc, help_command="vibe task add --help")
@@ -1262,7 +1432,11 @@ def cmd_task_list(*, include_all: bool = False, brief: bool = False):
if not include_all:
tasks = [task for task in tasks if not _is_completed_one_shot(task)]
tasks = _sort_tasks_for_display(tasks)
- print(json.dumps({"tasks": [_task_payload(task, brief=brief) for task in tasks]}, indent=2))
+ _print_cli_payload(
+ "run_definitions",
+ definitions=[_task_payload(task, brief=brief) for task in tasks],
+ tasks=[_task_payload(task, brief=brief) for task in tasks],
+ )
return 0
@@ -1280,7 +1454,8 @@ def cmd_task_show(task_id: str):
)
)
return 1
- print(json.dumps({"ok": True, "task": _task_payload(task)}, indent=2))
+ task_payload = _task_payload(task)
+ _print_cli_payload("run_definition", definition=task_payload, task=task_payload)
return 0
@@ -1300,7 +1475,8 @@ def cmd_task_set_enabled(task_id: str, enabled: bool):
)
return 1
updated = store.set_enabled(task_id, enabled)
- print(json.dumps({"ok": True, "task": _task_payload(updated)}, indent=2))
+ task_payload = _task_payload(updated)
+ _print_cli_payload("run_definition", definition=task_payload, task=task_payload)
return 0
@@ -1318,7 +1494,7 @@ def cmd_task_remove(task_id: str):
)
)
return 1
- print(json.dumps({"ok": True, "removed_id": task_id}, indent=2))
+ _print_cli_payload("run_definition", removed_id=task_id)
return 0
@@ -1374,14 +1550,6 @@ def cmd_task_update(args):
post_to = task.post_to
deliver_key = task.deliver_key
- session_target, delivery_target = _validate_delivery_args(
- session_id=session_id,
- session_key=session_key,
- post_to=post_to,
- deliver_key=deliver_key,
- help_command="vibe task update --help",
- )
-
if getattr(args, "name", None) is not None and getattr(args, "clear_name", False):
raise TaskCliError(
"use either --name or --clear-name, not both",
@@ -1396,14 +1564,24 @@ def cmd_task_update(args):
else:
name = task.name
- prompt_changed = getattr(args, "prompt", None) is not None or getattr(args, "prompt_file", None) is not None
- prompt = (
+ if getattr(args, "clear_agent", False):
+ agent_name = None
+ elif getattr(args, "agent", None) is not None:
+ agent_name = _validate_agent_name_arg(args.agent)
+ else:
+ agent_name = task.agent_name
+
+ message_changed = any(
+ getattr(args, name, None) is not None
+ for name in ("message", "message_file", "prompt", "prompt_file")
+ )
+ message = (
_resolve_prompt_input(
args,
help_command="vibe task update --help",
example_command=f"vibe task update {args.task_id}",
)
- if prompt_changed
+ if message_changed
else task.prompt
)
@@ -1462,11 +1640,45 @@ def cmd_task_update(args):
cron = task.cron
run_at = task.run_at
+ session_policy = _definition_session_policy_for_update(
+ args,
+ current_policy=task.session_policy,
+ current_schedule_type=task.schedule_type,
+ next_schedule_type=schedule_type,
+ help_command="vibe task update --help",
+ )
+ if session_policy in {"create_once", "create_per_run"} and not deliver_key:
+ raise TaskCliError(
+ "--deliver-key is required when a stored definition creates sessions",
+ code="missing_delivery_target",
+ hint="Pass the Scope ID that owns the new Session.",
+ help_command="vibe task update --help",
+ )
+ if session_policy == "create_once" and (
+ getattr(args, "create_session", False) or not session_id
+ ):
+ session_id = _reserve_definition_session(
+ agent_name=agent_name,
+ deliver_key=deliver_key or "",
+ help_command="vibe task update --help",
+ )
+ session_key = ""
+ session_target, delivery_target = _validate_definition_update_delivery_target(
+ session_policy=session_policy,
+ session_id=session_id,
+ session_key=session_key,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ help_command="vibe task update --help",
+ )
+
changes = {
"name": name,
"session_id": session_id,
"session_key": session_key,
- "prompt": prompt,
+ "prompt": message,
+ "agent_name": agent_name,
+ "session_policy": session_policy,
"schedule_type": schedule_type,
"post_to": post_to,
"deliver_key": deliver_key,
@@ -1479,6 +1691,8 @@ def cmd_task_update(args):
"session_id": task.session_id,
"session_key": task.session_key,
"prompt": task.prompt,
+ "agent_name": task.agent_name,
+ "session_policy": task.session_policy,
"schedule_type": task.schedule_type,
"post_to": task.post_to,
"deliver_key": task.deliver_key,
@@ -1490,7 +1704,7 @@ def cmd_task_update(args):
raise TaskCliError(
"no task fields were changed",
code="no_task_changes",
- hint="Pass at least one field to update, such as --name, --cron, --prompt, --session-id, or --deliver-key.",
+ hint="Pass at least one field to update, such as --name, --cron, --message, --session-id, or --deliver-key.",
help_command="vibe task update --help",
details={"task_id": args.task_id},
)
@@ -1500,8 +1714,10 @@ def cmd_task_update(args):
name=name,
session_key=session_key,
session_id=session_id,
- prompt=prompt,
+ prompt=message,
schedule_type=schedule_type,
+ agent_name=agent_name,
+ session_policy=session_policy,
post_to=post_to,
deliver_key=deliver_key,
cron=cron,
@@ -1509,7 +1725,13 @@ def cmd_task_update(args):
timezone_name=timezone_name,
)
warnings = _collect_target_warnings(session_target, delivery_target)
- print(json.dumps({"ok": True, "task": _task_payload(updated), "warnings": warnings}, indent=2))
+ task_payload = _task_payload(updated)
+ _print_cli_payload(
+ "run_definition",
+ definition=task_payload,
+ task=task_payload,
+ warnings=warnings,
+ )
return 0
except Exception as exc:
_print_task_error(exc, help_command="vibe task update --help")
@@ -1531,17 +1753,21 @@ def cmd_task_run(task_id: str):
)
return 1
request = _task_request_store().enqueue_task_run(task.id)
- print(
- json.dumps(
- {
- "ok": True,
- "accepted": True,
- "execution_id": request.id,
- "request_type": request.request_type,
- "task_id": task.id,
- },
- indent=2,
- )
+ _print_cli_payload(
+ "agent_run",
+ accepted=True,
+ execution_id=request.id,
+ run_id=request.id,
+ request_type=request.request_type,
+ task_id=task.id,
+ definition={"id": task.id, "definition_type": "scheduled"},
+ run={
+ "id": request.id,
+ "status": "queued",
+ "definition_id": task.id,
+ "agent_name": task.agent_name,
+ "session_id": task.session_id,
+ },
)
return 0
@@ -1560,7 +1786,7 @@ def cmd_hook_send(args):
deliver_key=getattr(args, "deliver_key", None),
help_command="vibe hook send --help",
)
- prompt = _resolve_prompt_input(
+ message = _resolve_prompt_input(
args,
help_command="vibe hook send --help",
example_command="vibe hook send --session-id sesk8m4q2p7x",
@@ -1570,24 +1796,27 @@ def cmd_hook_send(args):
session_id=session_id,
post_to=args.post_to,
deliver_key=args.deliver_key,
- prompt=prompt,
+ prompt=message,
+ agent_name=_validate_agent_name_arg(getattr(args, "agent", None)),
)
warnings = _collect_target_warnings(session_target, delivery_target)
- print(
- json.dumps(
- {
- "ok": True,
- "accepted": True,
- "execution_id": request.id,
- "request_type": request.request_type,
- "session_id": session_id,
- "session_key": session_key,
- "post_to": args.post_to,
- "deliver_key": args.deliver_key,
- "warnings": warnings,
- },
- indent=2,
- )
+ _print_cli_payload(
+ "agent_run",
+ accepted=True,
+ execution_id=request.id,
+ run_id=request.id,
+ request_type=request.request_type,
+ session_id=session_id,
+ session_key=session_key,
+ post_to=args.post_to,
+ deliver_key=args.deliver_key,
+ run={
+ "id": request.id,
+ "status": "queued",
+ "run_type": request.request_type,
+ "session_id": session_id,
+ },
+ warnings=warnings,
)
return 0
except Exception as exc:
@@ -1595,21 +1824,507 @@ def cmd_hook_send(args):
return 1
+def _read_optional_text(path: str | None, *, field_name: str) -> str | None:
+ if not path:
+ return None
+ try:
+ return Path(path).read_text(encoding="utf-8").strip() or None
+ except OSError as exc:
+ raise TaskCliError(
+ f"failed to read {field_name} file: {exc}",
+ code=f"{field_name}_file_read_failed",
+ details={f"{field_name}_file": path},
+ ) from exc
+
+
+def _parse_metadata_json(value: str | None) -> dict:
+ if not value:
+ return {}
+ try:
+ payload = json.loads(value)
+ except ValueError as exc:
+ raise TaskCliError("metadata must be valid JSON", code="invalid_metadata_json") from exc
+ if not isinstance(payload, dict):
+ raise TaskCliError("metadata JSON must be an object", code="invalid_metadata_json")
+ return payload
+
+
+def cmd_agent_list(args):
+ store = _agent_store()
+ agents = [_agent_payload(agent, brief=getattr(args, "brief", False)) for agent in store.list_agents()]
+ _print_cli_payload("agents", agents=agents)
+ return 0
+
+
+def cmd_agent_show(args):
+ try:
+ agent = _agent_store().require(args.name)
+ _print_cli_payload("agent", agent=_agent_payload(agent))
+ return 0
+ except Exception as exc:
+ _print_task_error(TaskCliError(str(exc), code="agent_not_found", details={"agent": args.name}))
+ return 1
+
+
+def cmd_agent_create(args):
+ try:
+ system_prompt = args.system_prompt
+ if args.system_prompt_file:
+ system_prompt = _read_optional_text(args.system_prompt_file, field_name="system_prompt")
+ agent = _agent_store().create(
+ name=args.name,
+ backend=validate_agent_backend(args.backend),
+ description=args.description,
+ model=args.model,
+ reasoning_effort=args.reasoning_effort,
+ system_prompt=system_prompt,
+ metadata=_parse_metadata_json(args.metadata),
+ )
+ _print_cli_payload("agent", agent=_agent_payload(agent))
+ return 0
+ except Exception as exc:
+ _print_task_error(exc)
+ return 1
+
+
+def cmd_agent_update(args):
+ try:
+ kwargs: dict[str, object] = {}
+ if args.description is not None:
+ kwargs["description"] = args.description
+ if args.clear_description:
+ kwargs["description"] = None
+ if args.model is not None:
+ kwargs["model"] = args.model
+ if args.clear_model:
+ kwargs["model"] = None
+ if args.reasoning_effort is not None:
+ kwargs["reasoning_effort"] = args.reasoning_effort
+ if args.clear_reasoning_effort:
+ kwargs["reasoning_effort"] = None
+ if args.system_prompt is not None:
+ kwargs["system_prompt"] = args.system_prompt
+ if args.system_prompt_file:
+ kwargs["system_prompt"] = _read_optional_text(args.system_prompt_file, field_name="system_prompt")
+ if args.clear_system_prompt:
+ kwargs["system_prompt"] = None
+ if args.metadata is not None:
+ kwargs["metadata"] = _parse_metadata_json(args.metadata)
+ if not kwargs:
+ raise TaskCliError(
+ "no agent fields were changed",
+ code="no_agent_changes",
+ hint="Pass at least one editable field. Agent name and backend are immutable.",
+ )
+ agent = _agent_store().update(args.name, **kwargs)
+ _print_cli_payload("agent", agent=_agent_payload(agent))
+ return 0
+ except Exception as exc:
+ _print_task_error(exc)
+ return 1
+
+
+def cmd_agent_remove(args):
+ try:
+ removed = _agent_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)
+ return 0
+ except Exception as exc:
+ _print_task_error(exc)
+ return 1
+
+
+def cmd_agent_import(args):
+ try:
+ candidates = []
+ if args.file:
+ if not args.backend:
+ raise TaskCliError(
+ "--backend is required when importing an arbitrary file",
+ code="missing_agent_backend",
+ hint="Pass --backend codex, --backend claude, or --backend opencode.",
+ )
+ candidates.append(parse_agent_file(Path(args.file), backend=args.backend))
+ else:
+ for path, backend in iter_global_agent_files(args.from_source):
+ candidates.append(parse_agent_file(path, backend=backend))
+ result = _agent_store().import_candidates(candidates)
+ _print_cli_payload(
+ "agents",
+ imported=[_agent_payload(agent, brief=True) for agent in result.imported],
+ skipped=result.skipped,
+ )
+ return 0
+ except Exception as exc:
+ _print_task_error(exc)
+ return 1
+
+
+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 session_id and (create_session or create_per_run):
+ raise TaskCliError(
+ "use either --session-id or --create-session, not both",
+ code="conflicting_session_policy",
+ help_command=help_command,
+ )
+ if create_session and create_per_run:
+ raise TaskCliError(
+ "use either --create-session or --create-session-per-run, not both",
+ code="conflicting_session_policy",
+ help_command=help_command,
+ )
+ if create_per_run:
+ raise TaskCliError(
+ "--create-session-per-run is only valid on stored recurring definitions",
+ code="invalid_session_policy",
+ hint="Use --create-session for a one-shot agent run.",
+ help_command=help_command,
+ )
+ if create_session:
+ return "create"
+ if session_id:
+ return "existing"
+ return "none"
+
+
+def _validate_definition_session_policy(args, *, schedule_type: str | None, help_command: str) -> str:
+ session_id = (getattr(args, "session_id", None) or "").strip()
+ session_key = (getattr(args, "session_key", None) or "").strip()
+ create_session = bool(getattr(args, "create_session", False))
+ create_per_run = bool(getattr(args, "create_session_per_run", False))
+ deliver_key = (getattr(args, "deliver_key", None) or "").strip()
+ specified = sum(1 for value in (bool(session_id or session_key), create_session, create_per_run) if value)
+ if specified > 1:
+ raise TaskCliError(
+ "use exactly one session policy",
+ code="conflicting_session_policy",
+ hint="Use --session-id, --create-session, or --create-session-per-run, but not more than one.",
+ help_command=help_command,
+ )
+ if create_per_run and schedule_type == "at":
+ raise TaskCliError(
+ "--create-session-per-run is invalid for one-shot tasks",
+ code="invalid_session_policy",
+ hint="Use --create-session for a one-shot task because it only runs once.",
+ help_command=help_command,
+ )
+ if (create_session or create_per_run) and not deliver_key:
+ raise TaskCliError(
+ "--deliver-key is required when a stored definition creates sessions",
+ code="missing_delivery_target",
+ hint="Pass the Scope ID that owns the new Session.",
+ help_command=help_command,
+ )
+ if create_session:
+ return "create_once"
+ if create_per_run:
+ return "create_per_run"
+ if session_id or session_key:
+ return "existing"
+ raise TaskCliError(
+ "one session policy is required",
+ code="missing_session_policy",
+ hint="Use --session-id to continue a Session, or --create-session with --deliver-key to create one.",
+ help_command=help_command,
+ )
+
+
+def _definition_session_policy_for_update(
+ args,
+ *,
+ current_policy: Optional[str],
+ current_schedule_type: str,
+ next_schedule_type: str,
+ help_command: str,
+) -> str:
+ create_session = bool(getattr(args, "create_session", False))
+ create_per_run = bool(getattr(args, "create_session_per_run", False))
+ session_id = (getattr(args, "session_id", None) or "").strip()
+ session_key = (getattr(args, "session_key", None) or "").strip()
+ if create_session and create_per_run:
+ raise TaskCliError(
+ "use either --create-session or --create-session-per-run, not both",
+ code="conflicting_session_policy",
+ help_command=help_command,
+ )
+ if (session_id or session_key) and (create_session or create_per_run):
+ raise TaskCliError(
+ "use either --session-id or session creation, not both",
+ code="conflicting_session_policy",
+ help_command=help_command,
+ )
+ if create_per_run and next_schedule_type == "at":
+ raise TaskCliError(
+ "--create-session-per-run is invalid for one-shot tasks",
+ code="invalid_session_policy",
+ hint="Use --create-session for a one-shot task because it only runs once.",
+ help_command=help_command,
+ )
+ if create_session:
+ return "create_once"
+ if create_per_run:
+ return "create_per_run"
+ if session_id or session_key:
+ return "existing"
+ if current_policy == "create_per_run" and current_schedule_type != next_schedule_type and next_schedule_type == "at":
+ raise TaskCliError(
+ "--create-session-per-run is invalid for one-shot tasks",
+ code="invalid_session_policy",
+ hint="Use --create-session when converting this definition to a one-shot task.",
+ help_command=help_command,
+ )
+ return current_policy or "existing"
+
+
+def _validate_definition_update_delivery_target(
+ *,
+ session_policy: str,
+ session_id: Optional[str],
+ session_key: str,
+ post_to: Optional[str],
+ deliver_key: Optional[str],
+ help_command: str,
+):
+ validation_session_key = session_key or (deliver_key if session_policy == "create_per_run" else "")
+ return _validate_delivery_args(
+ session_id=session_id,
+ session_key=validation_session_key,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ help_command=help_command,
+ )
+
+
+def _reserve_cli_session(*, agent, deliver_key: Optional[str]) -> str:
+ service = _session_service()
+ try:
+ if deliver_key:
+ target = _parse_validated_session_key(deliver_key, help_command="vibe agent run --help")
+ session_anchor = f"{target.platform}_agent-{uuid4().hex[:12]}"
+ session_id = service.reserve_agent_session(
+ scope_key=target.session_scope,
+ agent_backend=agent.backend,
+ session_anchor=session_anchor,
+ agent_id=agent.id,
+ agent_name=agent.name,
+ model=agent.model,
+ reasoning_effort=agent.reasoning_effort,
+ )
+ else:
+ platform = _primary_platform()
+ session_anchor = f"{platform}_private-agent-{uuid4().hex[:12]}"
+ session_id = service.reserve_private_agent_session(
+ platform=platform,
+ agent_backend=agent.backend,
+ session_anchor=session_anchor,
+ agent_id=agent.id,
+ agent_name=agent.name,
+ model=agent.model,
+ reasoning_effort=agent.reasoning_effort,
+ )
+ finally:
+ service.close()
+ if not session_id:
+ raise TaskCliError(
+ "failed to reserve a new Agent Session ID",
+ code="session_reservation_failed",
+ help_command="vibe agent run --help",
+ )
+ return session_id
+
+
+def _reserve_definition_session(*, agent_name: Optional[str], deliver_key: str, help_command: str) -> str:
+ target = _parse_validated_session_key(deliver_key, help_command=help_command)
+ agent = _agent_store().require(agent_name) if agent_name else None
+ agent_backend = agent.backend if agent else _ensure_config().agents.default_backend
+ session_anchor = f"{target.platform}_agent-{uuid4().hex[:12]}"
+ service = _session_service()
+ try:
+ session_id = service.reserve_agent_session(
+ scope_key=target.session_scope,
+ agent_backend=agent_backend,
+ session_anchor=session_anchor,
+ agent_id=agent.id if agent else None,
+ agent_name=agent.name if agent else None,
+ model=agent.model if agent else None,
+ reasoning_effort=agent.reasoning_effort if agent else None,
+ )
+ finally:
+ service.close()
+ if not session_id:
+ raise TaskCliError(
+ "failed to reserve a new Agent Session ID",
+ code="session_reservation_failed",
+ help_command=help_command,
+ )
+ return session_id
+
+
+def cmd_agent_run(args):
+ try:
+ message = _resolve_message_input(
+ args,
+ help_command="vibe agent run --help",
+ example_command="vibe agent run --agent default",
+ )
+ session_policy = _validate_run_session_policy(args, help_command="vibe agent run --help")
+ agent_name = (args.agent or "").strip()
+ if session_policy in {"create", "none"} and not agent_name:
+ raise TaskCliError(
+ "--agent is required when running without an existing --session-id",
+ code="missing_agent",
+ hint="Pass --agent with the Vibe Agent name to run.",
+ help_command="vibe agent run --help",
+ )
+ if session_policy == "none" and args.deliver_key:
+ raise TaskCliError(
+ "--deliver-key requires --session-id or --create-session",
+ code="delivery_target_without_session_policy",
+ 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 = ""
+ if session_policy == "create":
+ session_id = _reserve_cli_session(agent=agent, deliver_key=args.deliver_key)
+ elif session_policy == "none":
+ session_id = _reserve_cli_session(agent=agent, deliver_key=None)
+ 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",
+ )
+ if args.deliver_key:
+ _parse_validated_session_key(args.deliver_key, help_command="vibe agent run --help")
+ request_store = _task_request_store()
+ request = request_store.enqueue_agent_run(
+ agent_name=agent.name if agent else None,
+ agent_id=agent.id if agent else None,
+ agent_backend=agent.backend if agent else None,
+ model=agent.model if agent else None,
+ reasoning_effort=agent.reasoning_effort if agent else None,
+ session_policy=session_policy,
+ session_key=session_key,
+ session_id=session_id,
+ post_to=args.post_to,
+ deliver_key=args.deliver_key,
+ message=message,
+ )
+ payload = {
+ "accepted": True,
+ "request_type": request.request_type,
+ "run_id": request.id,
+ "execution_id": request.id,
+ "agent": agent.name if agent else None,
+ "session_policy": session_policy,
+ "session_id": session_id,
+ "deliver_key": args.deliver_key,
+ "async": bool(args.async_run),
+ "run": {
+ "id": request.id,
+ "status": "queued",
+ "run_type": request.request_type,
+ "agent_name": agent.name if agent else None,
+ "session_id": session_id,
+ },
+ }
+ if not args.async_run:
+ payload["run"] = _wait_for_run_result(request_store, request.id, wait_timeout=args.wait_timeout)
+ _print_cli_payload("agent_run", **payload)
+ return 0
+ except Exception as exc:
+ _print_task_error(exc, help_command="vibe agent run --help")
+ return 1
+
+
+def _wait_for_run_result(store: TaskExecutionStore, run_id: str, *, wait_timeout: Optional[float]) -> dict:
+ started = time.monotonic()
+ 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"}:
+ return _run_payload(run)
+ elapsed = time.monotonic() - started
+ if elapsed >= max_wait:
+ run = run or {"id": run_id}
+ run["wait_state"] = "detached"
+ run["wait_elapsed_seconds"] = round(elapsed, 3)
+ run["accepted"] = True
+ run["async"] = True
+ return _run_payload(run)
+ time.sleep(0.25)
+
+
+def cmd_runs_list(args):
+ runs = _task_request_store().list_runs(status=getattr(args, "status", None))
+ _print_cli_payload("agent_runs", runs=[_run_payload(run, brief=getattr(args, "brief", False)) for run in runs])
+ return 0
+
+
+def cmd_runs_show(args):
+ run = _task_request_store().get_run(args.run_id)
+ if run is None:
+ _print_task_error(TaskCliError(f"run '{args.run_id}' not found", code="run_not_found", details={"run_id": args.run_id}))
+ return 1
+ _print_cli_payload("agent_run", run=_run_payload(run))
+ return 0
+
+
+def cmd_runs_cancel(args):
+ canceled = _task_request_store().cancel_run(args.run_id)
+ if not canceled:
+ _print_task_error(TaskCliError(f"run '{args.run_id}' not found", code="run_not_found", details={"run_id": args.run_id}))
+ return 1
+ run = _task_request_store().get_run(args.run_id)
+ _print_cli_payload("agent_run", cancel_requested=True, run=_run_payload(run or {"id": args.run_id}))
+ return 0
+
+
def cmd_watch_add(args):
try:
+ session_policy = _validate_definition_session_policy(
+ args,
+ schedule_type="watch",
+ 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=True,
+ required=session_policy == "existing",
help_command="vibe watch add --help",
)
+ if session_policy == "create_once":
+ session_id = _reserve_definition_session(
+ agent_name=agent_name,
+ deliver_key=args.deliver_key,
+ help_command="vibe watch add --help",
+ )
+ validation_session_key = session_key or (args.deliver_key if session_policy == "create_per_run" else "")
session_target, delivery_target = _validate_delivery_args(
session_id=session_id,
- session_key=session_key,
+ session_key=validation_session_key,
post_to=getattr(args, "post_to", None),
deliver_key=getattr(args, "deliver_key", None),
help_command="vibe watch add --help",
)
- command, shell_command = _resolve_watch_command(args, help_command="vibe watch add --help")
mode = "forever" if args.forever else "once"
_validate_watch_timing(
@@ -1638,11 +2353,19 @@ def cmd_watch_add(args):
retry_delay_seconds=float(args.retry_delay),
post_to=args.post_to,
deliver_key=args.deliver_key,
+ agent_name=agent_name,
+ session_policy=session_policy,
)
runtime_store = _watch_runtime_store()
watch, runtime_entry = _wait_for_watch_startup(store, runtime_store, watch.id)
warnings = _collect_target_warnings(session_target, delivery_target)
- print(json.dumps({"ok": True, "watch": _watch_payload(watch, runtime_entry), "warnings": warnings}, indent=2))
+ watch_payload = _watch_payload(watch, runtime_entry)
+ _print_cli_payload(
+ "run_definition",
+ definition=watch_payload,
+ watch=watch_payload,
+ warnings=warnings,
+ )
return 0
except Exception as exc:
_print_task_error(exc, help_command="vibe watch add --help")
@@ -1654,12 +2377,8 @@ def cmd_watch_list(*, brief: bool = False):
runtime_state = _watch_runtime_store().load().get("watches", {})
watches = store.list_watches()
watches.sort(key=lambda item: (item.enabled is False, item.created_at, item.id))
- print(
- json.dumps(
- {"watches": [_watch_payload(watch, runtime_state.get(watch.id), brief=brief) for watch in watches]},
- indent=2,
- )
- )
+ watch_payloads = [_watch_payload(watch, runtime_state.get(watch.id), brief=brief) for watch in watches]
+ _print_cli_payload("run_definitions", definitions=watch_payloads, watches=watch_payloads)
return 0
@@ -1678,7 +2397,8 @@ def cmd_watch_show(watch_id: str):
)
return 1
runtime_entry = _watch_runtime_store().load().get("watches", {}).get(watch.id)
- print(json.dumps({"ok": True, "watch": _watch_payload(watch, runtime_entry)}, indent=2))
+ watch_payload = _watch_payload(watch, runtime_entry)
+ _print_cli_payload("run_definition", definition=watch_payload, watch=watch_payload)
return 0
@@ -1699,7 +2419,8 @@ def cmd_watch_set_enabled(watch_id: str, enabled: bool):
return 1
updated = store.set_enabled(watch_id, enabled)
runtime_entry = _watch_runtime_store().load().get("watches", {}).get(updated.id)
- print(json.dumps({"ok": True, "watch": _watch_payload(updated, runtime_entry)}, indent=2))
+ watch_payload = _watch_payload(updated, runtime_entry)
+ _print_cli_payload("run_definition", definition=watch_payload, watch=watch_payload)
return 0
@@ -1769,14 +2490,6 @@ def cmd_watch_update(args):
post_to = watch.post_to
deliver_key = watch.deliver_key
- session_target, delivery_target = _validate_delivery_args(
- session_id=session_id,
- session_key=session_key,
- post_to=post_to,
- deliver_key=deliver_key,
- help_command="vibe watch update --help",
- )
-
command = list(watch.command)
shell_command = watch.shell_command
waiter_command = getattr(args, "waiter_command", None)
@@ -1793,6 +2506,12 @@ def cmd_watch_update(args):
else watch.prefix
)
)
+ if getattr(args, "clear_agent", False):
+ agent_name = None
+ elif getattr(args, "agent", None) is not None:
+ agent_name = _validate_agent_name_arg(args.agent)
+ else:
+ agent_name = watch.agent_name
cwd = (
None
if getattr(args, "clear_cwd", False)
@@ -1824,11 +2543,44 @@ def cmd_watch_update(args):
mode=mode,
help_command="vibe watch update --help",
)
+ session_policy = _definition_session_policy_for_update(
+ args,
+ current_policy=watch.session_policy,
+ current_schedule_type="watch",
+ next_schedule_type="watch",
+ help_command="vibe watch update --help",
+ )
+ if session_policy in {"create_once", "create_per_run"} and not deliver_key:
+ raise TaskCliError(
+ "--deliver-key is required when a stored definition creates sessions",
+ code="missing_delivery_target",
+ hint="Pass the Scope ID that owns the new Session.",
+ help_command="vibe watch update --help",
+ )
+ if session_policy == "create_once" and (
+ getattr(args, "create_session", False) or not session_id
+ ):
+ session_id = _reserve_definition_session(
+ agent_name=agent_name,
+ deliver_key=deliver_key or "",
+ help_command="vibe watch update --help",
+ )
+ session_key = ""
+ session_target, delivery_target = _validate_definition_update_delivery_target(
+ session_policy=session_policy,
+ session_id=session_id,
+ session_key=session_key,
+ post_to=post_to,
+ deliver_key=deliver_key,
+ help_command="vibe watch update --help",
+ )
changes = {
"name": name,
"session_id": session_id,
"session_key": session_key,
+ "agent_name": agent_name,
+ "session_policy": session_policy,
"command": command,
"shell_command": shell_command,
"prefix": prefix,
@@ -1845,6 +2597,8 @@ def cmd_watch_update(args):
"name": watch.name,
"session_id": watch.session_id,
"session_key": watch.session_key,
+ "agent_name": watch.agent_name,
+ "session_policy": watch.session_policy,
"command": watch.command,
"shell_command": watch.shell_command,
"prefix": watch.prefix,
@@ -1869,7 +2623,13 @@ def cmd_watch_update(args):
updated = store.update_watch(args.watch_id, **changes)
runtime_entry = _watch_runtime_store().load().get("watches", {}).get(updated.id)
warnings = _collect_target_warnings(session_target, delivery_target)
- print(json.dumps({"ok": True, "watch": _watch_payload(updated, runtime_entry), "warnings": warnings}, indent=2))
+ watch_payload = _watch_payload(updated, runtime_entry)
+ _print_cli_payload(
+ "run_definition",
+ definition=watch_payload,
+ watch=watch_payload,
+ warnings=warnings,
+ )
return 0
except Exception as exc:
_print_task_error(exc, help_command="vibe watch update --help")
@@ -1890,7 +2650,7 @@ def cmd_watch_remove(watch_id: str):
)
)
return 1
- print(json.dumps({"ok": True, "removed_id": watch_id}, indent=2))
+ _print_cli_payload("run_definition", removed_id=watch_id)
return 0
@@ -2853,10 +3613,101 @@ def build_parser():
help="Print a machine-readable result with the output path and capture backend.",
)
+ agent_parser = subparsers.add_parser(
+ "agent",
+ help="Manage Vibe Agents",
+ description="Create, inspect, import, update, and run Vibe-owned Agent definitions.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe agent --help",
+ )
+ agent_subparsers = agent_parser.add_subparsers(
+ dest="agent_command",
+ metavar="{list,show,create,update,remove,import,run}",
+ )
+ agent_subparsers.required = True
+
+ 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_show_parser = agent_subparsers.add_parser("show", help="Show one Vibe Agent")
+ agent_show_parser.add_argument("name", help="Agent name")
+
+ agent_create_parser = agent_subparsers.add_parser("create", help="Create a Vibe Agent")
+ agent_create_parser.add_argument("name", help="Globally unique Agent name")
+ agent_create_parser.add_argument("--backend", required=True, choices=("codex", "claude", "opencode"))
+ agent_create_parser.add_argument("--description")
+ agent_create_parser.add_argument("--model")
+ agent_create_parser.add_argument("--reasoning-effort")
+ 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")
+
+ 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.")
+ agent_update_parser.add_argument("--description")
+ agent_update_parser.add_argument("--clear-description", action="store_true")
+ 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("--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")
+
+ agent_remove_parser = agent_subparsers.add_parser("remove", help="Remove a Vibe Agent")
+ agent_remove_parser.add_argument("name", help="Agent name")
+
+ 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_run_parser = agent_subparsers.add_parser(
+ "run",
+ help="Run a Vibe Agent",
+ description="Run a Vibe Agent turn. Use --async to queue it as a background run.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe agent run --help",
+ )
+ agent_run_parser.add_argument("--agent", help="Vibe Agent name")
+ agent_run_parser.add_argument("--session-id", help="Existing Agent Session ID to continue")
+ agent_run_parser.add_argument("--create-session", action="store_true", help="Create a new Vibe Session ID before running")
+ agent_run_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Vibe Session ID for each definition run")
+ agent_run_parser.add_argument("--deliver-key", help="Scope ID used as delivery target when creating or sending to a target")
+ agent_run_parser.add_argument("--post-to", choices=("thread", "channel"))
+ agent_run_parser.add_argument("--async", dest="async_run", action="store_true", help="Queue the run and return immediately")
+ agent_run_parser.add_argument("--wait-timeout", type=float, help="Maximum seconds the CLI waits for a synchronous run result")
+ agent_message_group = agent_run_parser.add_mutually_exclusive_group(required=True)
+ agent_message_group.add_argument("--message")
+ 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)
+
+ runs_parser = subparsers.add_parser(
+ "runs",
+ help="Inspect and manage Agent run records",
+ description="List, inspect, and request cancellation for Agent run records.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe runs --help",
+ )
+ runs_subparsers = runs_parser.add_subparsers(dest="runs_command", metavar="{list,show,cancel}")
+ runs_subparsers.required = True
+ 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")
+ runs_show_parser = runs_subparsers.add_parser("show", help="Show one Agent run")
+ runs_show_parser.add_argument("run_id")
+ runs_cancel_parser = runs_subparsers.add_parser("cancel", help="Request best-effort cancellation for one run")
+ runs_cancel_parser.add_argument("run_id")
+
task_parser = subparsers.add_parser(
"task",
help="Manage scheduled tasks",
- description="Create, inspect, and control scheduled prompts for Vibe Remote.",
+ description="Create, inspect, and control scheduled Agent messages for Vibe Remote.",
epilog=_task_examples_text(),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe task --help",
@@ -2871,11 +3722,11 @@ def build_parser():
task_add_parser = task_subparsers.add_parser(
"add",
help="Create a scheduled task",
- description="Create a recurring or one-shot scheduled prompt.",
+ description="Create a recurring or one-shot scheduled Agent message.",
epilog=_task_add_examples_text(),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe task add --help",
- error_hint="Use --session-id together with exactly one schedule flag and one prompt input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",
+ error_hint="Use --session-id together with exactly one schedule flag and one message input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",
)
task_add_parser.add_argument(
"--name",
@@ -2889,6 +3740,9 @@ def build_parser():
"--session-key",
help="Legacy compatibility target; prefer --session-id.",
)
+ task_add_parser.add_argument("--create-session", action="store_true", help="Create one reusable Vibe Session ID for this task")
+ task_add_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Vibe Session ID each time this task runs")
+ task_add_parser.add_argument("--agent", help="Vibe Agent name to use when the task runs")
delivery_group = task_add_parser.add_mutually_exclusive_group()
delivery_group.add_argument(
"--post-to",
@@ -2903,8 +3757,10 @@ def build_parser():
schedule_group.add_argument("--cron", help="Recurring schedule in 5-field crontab format")
schedule_group.add_argument("--at", help="One-shot timestamp in ISO 8601 format")
prompt_group = task_add_parser.add_mutually_exclusive_group(required=True)
- prompt_group.add_argument("--prompt", help="Stored task content to inject each time the task runs")
- prompt_group.add_argument("--prompt-file", help="Read stored task content from a UTF-8 text file")
+ prompt_group.add_argument("--message", help="Stored user message to send each time the task runs")
+ prompt_group.add_argument("--message-file", help="Read stored user message from a UTF-8 text file")
+ 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")
task_update_parser = task_subparsers.add_parser(
@@ -2925,6 +3781,10 @@ def build_parser():
)
task_update_parser.add_argument("--session-id", help="Replace the stored Agent Session ID")
task_update_parser.add_argument("--session-key", help="Legacy compatibility target; prefer --session-id")
+ task_update_parser.add_argument("--create-session", action="store_true", help="Replace the task with one reusable newly-created Vibe Session ID")
+ task_update_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Vibe Session ID each time this task runs")
+ task_update_parser.add_argument("--agent", help="Replace the Vibe Agent used by this task")
+ task_update_parser.add_argument("--clear-agent", action="store_true", help="Clear the stored Vibe Agent override")
update_delivery_group = task_update_parser.add_mutually_exclusive_group()
update_delivery_group.add_argument(
"--post-to",
@@ -2942,8 +3802,10 @@ def build_parser():
)
task_update_parser.add_argument("--cron", help="Replace the schedule with a recurring 5-field crontab")
task_update_parser.add_argument("--at", help="Replace the schedule with a one-shot ISO 8601 timestamp")
- task_update_parser.add_argument("--prompt", help="Replace the stored prompt text")
- task_update_parser.add_argument("--prompt-file", help="Replace the stored prompt from a UTF-8 text file")
+ task_update_parser.add_argument("--message", help="Replace the stored user message text")
+ task_update_parser.add_argument("--message-file", help="Replace the stored user message from a UTF-8 text file")
+ 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")
task_subparsers.add_parser(
@@ -3035,7 +3897,7 @@ def build_parser():
epilog=_hook_send_examples_text(),
formatter_class=argparse.RawDescriptionHelpFormatter,
error_help_command="vibe hook send --help",
- error_hint="Use --session-id together with exactly one prompt input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",
+ error_hint="Use --session-id together with exactly one message input flag. Add --post-to or --deliver-key only when delivery must differ from the session target.",
)
hook_send_parser.add_argument(
"--session-id",
@@ -3045,6 +3907,7 @@ def build_parser():
"--session-key",
help="Legacy compatibility target; prefer --session-id.",
)
+ hook_send_parser.add_argument("--agent", help="Vibe Agent name to use for this one-shot async turn")
hook_delivery_group = hook_send_parser.add_mutually_exclusive_group()
hook_delivery_group.add_argument(
"--post-to",
@@ -3056,8 +3919,10 @@ def build_parser():
help="Explicit delivery target key. Use this only when delivery must go to a different target than the continued session.",
)
hook_prompt_group = hook_send_parser.add_mutually_exclusive_group(required=True)
- hook_prompt_group.add_argument("--prompt", help="One-shot async content to queue immediately")
- hook_prompt_group.add_argument("--prompt-file", help="Read one-shot async content from a UTF-8 text file")
+ hook_prompt_group.add_argument("--message", help="One-shot async user message to queue immediately")
+ 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)
watch_parser = subparsers.add_parser(
"watch",
@@ -3092,6 +3957,9 @@ def build_parser():
"--session-key",
help="Legacy compatibility target; prefer --session-id.",
)
+ watch_add_parser.add_argument("--create-session", action="store_true", help="Create one reusable Vibe Session ID for this watch")
+ watch_add_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Vibe Session ID each time this watch triggers")
+ watch_add_parser.add_argument("--agent", help="Vibe Agent name to use for follow-up messages")
watch_delivery_group = watch_add_parser.add_mutually_exclusive_group()
watch_delivery_group.add_argument(
"--post-to",
@@ -3168,6 +4036,10 @@ def build_parser():
"--session-key",
help="Legacy compatibility target; prefer --session-id.",
)
+ watch_update_parser.add_argument("--create-session", action="store_true", help="Replace the watch with one reusable newly-created Vibe Session ID")
+ watch_update_parser.add_argument("--create-session-per-run", action="store_true", help="Create a new Vibe Session ID each time this watch triggers")
+ watch_update_parser.add_argument("--agent", help="Replace the Vibe Agent used for follow-up messages")
+ watch_update_parser.add_argument("--clear-agent", action="store_true", help="Clear the stored Vibe Agent override")
watch_update_delivery_group = watch_update_parser.add_mutually_exclusive_group()
watch_update_delivery_group.add_argument(
"--post-to",
@@ -3304,6 +4176,30 @@ def main():
if args.remote_command == "stop":
sys.exit(cmd_remote_stop(args))
parser.error("remote command is invalid")
+ if args.command == "agent":
+ if args.agent_command == "list":
+ sys.exit(cmd_agent_list(args))
+ if args.agent_command == "show":
+ sys.exit(cmd_agent_show(args))
+ if args.agent_command == "create":
+ sys.exit(cmd_agent_create(args))
+ if args.agent_command == "update":
+ sys.exit(cmd_agent_update(args))
+ if args.agent_command == "remove":
+ sys.exit(cmd_agent_remove(args))
+ if args.agent_command == "import":
+ sys.exit(cmd_agent_import(args))
+ if args.agent_command == "run":
+ sys.exit(cmd_agent_run(args))
+ parser.error("agent command is required")
+ if args.command == "runs":
+ if args.runs_command in {"list", "ls"}:
+ sys.exit(cmd_runs_list(args))
+ if args.runs_command == "show":
+ sys.exit(cmd_runs_show(args))
+ if args.runs_command == "cancel":
+ sys.exit(cmd_runs_cancel(args))
+ parser.error("runs command is required")
if args.command == "task":
if args.task_command == "add":
sys.exit(cmd_task_add(args))