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(bots): Bot data, main Bot, Bot directories, CLI, and Web API (#3115)

Call Whiteaefe71d37b25
diff --git a/config/paths.py b/config/paths.py
index a635f6796..38f43886b 100644
--- a/config/paths.py
+++ b/config/paths.py
@@ -160,6 +160,16 @@ def get_show_git_dir(session_id: str) -> Path:
return get_vibe_remote_dir() / "show-git" / f"{session_id}.git"
+def get_bots_dir() -> Path:
+ """The parent of every Bot's working directory (``docs/plans/bots.md`` D7)."""
+
+ return get_vibe_remote_dir() / "bots"
+
+
+def get_bot_dir(handle: str) -> Path:
+ return get_bots_dir() / handle
+
+
def get_show_git_runtime_status_path() -> Path:
return get_runtime_dir() / "show-git-checkpoints.json"
diff --git a/core/bot_git.py b/core/bot_git.py
new file mode 100644
index 000000000..1b4a2800f
--- /dev/null
+++ b/core/bot_git.py
@@ -0,0 +1,164 @@
+"""Automatic Git history for Bot directories (``docs/plans/bots.md`` D7).
+
+A Bot's directory is an ordinary repository with ``.git`` in place. Avibe commits before each Turn of the Bot's
+Session (what others changed since, attributed to them) and after it (the Bot's own changes, with the input's summary
+as the subject). The Bot is not taught to commit; it reads the history to trace or undo. History is never squashed
+or pruned: only ``git gc --auto`` runs, when Git's own thresholds say the repository has grown.
+
+The commits run on the Show Page checkpoint worker (``core.show_git.ShowGitCheckpointService``), off the controller
+loop, and the Turn's dispatch waits for its PRE_TURN commit before the prompt reaches the backend.
+"""
+
+from __future__ import annotations
+
+import logging
+import shutil
+import subprocess
+import time
+from pathlib import Path
+from typing import Optional
+
+from core.git_binary import ResolvedGit
+
+logger = logging.getLogger(__name__)
+
+PRE_TURN = "pre-turn"
+POST_TURN = "post-turn"
+GIT_COMMAND_TIMEOUT_SECONDS = 60
+GIT_MAINTENANCE_TIMEOUT_SECONDS = 5 * 60
+STALE_INDEX_LOCK_SECONDS = 5 * 60
+OTHERS_SUBJECT = "Changes by others"
+TURN_SUBJECT_FALLBACK = "Turn"
+_OTHERS_AUTHOR = ("Others", "[email protected]")
+_COMMITTER = ("Avibe", "[email protected]")
+_HOOKS_DIRNAME = "avibe-empty-hooks"
+
+
+class BotGitError(RuntimeError):
+ """A Git operation on a Bot directory failed."""
+
+
+def bot_git_environment() -> dict[str, str]:
+ """The service's environment without Git overrides or the user's Git configuration (no hooks, no signing)."""
+ from core.show_git import _git_environment
+
+ return _git_environment()
+
+
+class BotGitRepository:
+ def __init__(self, handle: str, directory: Path, git: ResolvedGit) -> None:
+ self.handle = handle
+ self.directory = directory
+ self.git = git
+
+ @property
+ def gitdir(self) -> Path:
+ return self.directory / ".git"
+
+ def checkpoint(
+ self,
+ checkpoint: str,
+ *,
+ session_id: str,
+ message: str = "",
+ run_id: Optional[str] = None,
+ ) -> bool:
+ """Commit everything the directory holds now, if anything changed. Returns whether a commit was made."""
+ from core.show_git import _checkpoint_message, sanitize_checkpoint_subject
+
+ if checkpoint not in {PRE_TURN, POST_TURN}:
+ raise ValueError(f"unsupported checkpoint kind: {checkpoint}")
+ if not self.directory.is_dir():
+ return False
+ if not self.gitdir.exists():
+ self._run_checked(["-c", "init.defaultBranch=main", "init", "--quiet", str(self.directory)], bare=True)
+ if not self.gitdir.is_dir():
+ # A ``.git`` file points elsewhere: the user moved the history on purpose, and it is theirs to keep.
+ return False
+ self._remove_stale_index_lock()
+ self._ensure_empty_hooks_dir()
+ status = self._run_checked(["status", "--porcelain=v1", "--untracked-files=all"])
+ if not status.stdout.strip():
+ return False
+ if checkpoint == PRE_TURN:
+ subject, author = OTHERS_SUBJECT, _OTHERS_AUTHOR
+ else:
+ subject = sanitize_checkpoint_subject(message) if str(message or "").strip() else TURN_SUBJECT_FALLBACK
+ author = (f"@{self.handle}", f"{self.handle}@bots.avibe.local")
+ self._run_checked(["add", "-A"])
+ result = self._run(
+ [
+ "commit",
+ "--quiet",
+ f"--author={author[0]} <{author[1]}>",
+ "-m",
+ _checkpoint_message(subject, session_id=session_id, run_id=run_id, checkpoint=checkpoint),
+ ]
+ )
+ if result.returncode != 0:
+ if "nothing to commit" in (result.stdout + result.stderr).lower():
+ return False
+ raise BotGitError(result.stderr.strip() or result.stdout.strip() or "failed to commit the Bot directory")
+ if checkpoint == POST_TURN:
+ self._maintain()
+ return True
+
+ def _maintain(self) -> None:
+ """``git gc --auto``: packs when Git's thresholds say so. Never squashes, never drops a commit."""
+ result = self._run(["-c", "gc.autoDetach=false", "gc", "--auto", "--quiet"], timeout=GIT_MAINTENANCE_TIMEOUT_SECONDS)
+ if result.returncode != 0:
+ logger.warning("git gc --auto failed for the Bot directory %s: %s", self.directory, result.stderr.strip())
+
+ def _remove_stale_index_lock(self) -> None:
+ lock = self.gitdir / "index.lock"
+ try:
+ age = time.time() - lock.stat().st_mtime
+ except OSError:
+ return
+ if age > STALE_INDEX_LOCK_SECONDS:
+ try:
+ lock.unlink()
+ except OSError:
+ logger.warning("failed to remove a stale Bot directory index lock: %s", lock, exc_info=True)
+
+ def _ensure_empty_hooks_dir(self) -> None:
+ hooks = self.gitdir / _HOOKS_DIRNAME
+ if hooks.is_symlink() or (hooks.exists() and not hooks.is_dir()):
+ hooks.unlink()
+ hooks.mkdir(exist_ok=True)
+ for child in hooks.iterdir():
+ if child.is_dir() and not child.is_symlink():
+ shutil.rmtree(child)
+ else:
+ child.unlink()
+
+ def _base_command(self) -> list[str]:
+ return [
+ str(self.git.path),
+ "-c", f"user.name={_COMMITTER[0]}",
+ "-c", f"user.email={_COMMITTER[1]}",
+ "-c", "commit.gpgsign=false",
+ "-c", f"core.hooksPath={self.gitdir / _HOOKS_DIRNAME}",
+ # Commits never start background maintenance; ``_maintain`` runs it in the foreground instead.
+ "-c", "maintenance.auto=false",
+ ]
+
+ def _run(self, args: list[str], *, timeout: int = GIT_COMMAND_TIMEOUT_SECONDS, bare: bool = False):
+ location = [] if bare else ["-C", str(self.directory)]
+ try:
+ return subprocess.run(
+ [*self._base_command(), *location, *args],
+ check=False,
+ capture_output=True,
+ text=True,
+ env=bot_git_environment(),
+ timeout=timeout,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ raise BotGitError(f"failed to execute a Bot directory Git command: {exc}") from exc
+
+ def _run_checked(self, args: list[str], *, bare: bool = False):
+ result = self._run(args, bare=bare)
+ if result.returncode != 0:
+ raise BotGitError(result.stderr.strip() or result.stdout.strip() or f"git {' '.join(args)} failed")
+ return result
diff --git a/core/bot_handles.py b/core/bot_handles.py
new file mode 100644
index 000000000..db32357b0
--- /dev/null
+++ b/core/bot_handles.py
@@ -0,0 +1,133 @@
+"""Handle suggestions for new Bots (``docs/plans/bots.md`` D2).
+
+1. An ASCII display name is normalized (``Researcher`` to ``researcher``).
+2. Otherwise the main Bot's model, at its lowest reasoning effort, proposes an English codename from the display
+ name and role through Model Hub, accepted only if it is a valid handle. The request waits at most 5 seconds.
+3. Without a usable model answer, the display name is transliterated with ``anyascii`` (``小爱`` to ``xiaoai``).
+4. A collision adds ``-2`` (and so on), skipping reserved handles.
+
+The model call runs in the controller process, which owns the Model Hub gateway (``propose_handle_with_model``,
+reached over the internal socket); the Web server falls back to transliteration whenever it cannot get an answer.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import uuid
+from typing import Any, Optional
+
+from core.bots import (
+ HANDLE_SOURCE_MODEL,
+ HANDLE_SOURCE_TRANSLITERATION,
+ ascii_name_handle,
+ fallback_handle_base,
+ free_handle,
+ model_handle,
+)
+
+logger = logging.getLogger(__name__)
+
+MODEL_BUDGET_SECONDS = 5.0
+#: Reasoning efforts from lowest to highest; a model's lowest is the first of these it supports.
+_EFFORT_ORDER = ("none", "minimal", "low", "medium", "high", "xhigh", "max")
+_MAX_OUTPUT_TOKENS = 2048
+_SYSTEM = (
+ "You choose a handle for a new member of the user's team of AI assistants. "
+ "Reply with one short English codename and nothing else: 2 to 24 characters, lowercase letters, digits, and "
+ "hyphens, starting with a letter. Prefer a familiar abbreviation or a short English word for the role, for "
+ "example cso for a chief security officer, or researcher."
+)
+
+
+def lowest_effort(efforts: Any) -> Optional[str]:
+ """The lowest reasoning effort a model supports, or None when it takes none."""
+ offered = [str(effort) for effort in efforts or () if str(effort).strip()]
+ for effort in _EFFORT_ORDER:
+ if effort in offered:
+ return effort
+ return offered[0] if offered else None
+
+
+def needs_model(display_name: str) -> bool:
+ """Whether D2 step 2 applies: the display name does not normalize to a handle by itself."""
+ return ascii_name_handle(display_name) is None
+
+
+async def propose_handle_with_model(
+ controller: Any, *, display_name: str, role: str = "", budget_seconds: float = MODEL_BUDGET_SECONDS
+) -> Optional[str]:
+ """The main Bot's model's codename for a new Bot, or None: no route, no answer in time, or no valid handle."""
+ store = getattr(controller, "vibe_agent_store", None)
+ runtime = getattr(controller, "model_hub_runtime", None)
+ if store is None or runtime is None:
+ return None
+ main = await asyncio.to_thread(store.get_main_bot_agent)
+ model = str(getattr(main, "model", None) or "").strip()
+ if not model:
+ return None
+ scope = f"vibey:bot-handle:{uuid.uuid4().hex[:12]}"
+ try:
+ return await asyncio.wait_for(
+ _propose(runtime, model, scope, display_name=display_name, role=role), timeout=budget_seconds
+ )
+ except asyncio.TimeoutError:
+ logger.info("The Bot handle model did not answer within %.0f seconds", budget_seconds)
+ return None
+ except Exception:
+ logger.info("The Bot handle model had no usable route", exc_info=True)
+ return None
+ finally:
+ retire = getattr(runtime, "retire_process_scope", None)
+ if callable(retire):
+ try:
+ retire("vibey", scope)
+ except Exception:
+ logger.debug("Could not retire the Bot handle model scope", exc_info=True)
+
+
+async def _propose(runtime: Any, model: str, scope: str, *, display_name: str, role: str) -> Optional[str]:
+ from core.agent_core.ai.provider import ModelRequest, ProviderError, TextDelta
+ from core.agent_core.cancel import CancelToken
+ from core.agent_core.harness.context import output_tokens
+ from core.agent_core.messages import TextBlock, UserMessage
+ from modules.agents.vibey.models import registry_providers, selection_from_hop
+
+ launch = await runtime.resolve("vibey", model, process_scope=scope)
+ selection = selection_from_hop(launch.to_hop_resolution())
+ capabilities = selection.capabilities
+ effort = lowest_effort(capabilities.reasoning_efforts) if capabilities.supports_reasoning is not False else None
+ prompt = f"Display name: {display_name}\nRole: {role.strip() or '(none)'}"
+ request = ModelRequest(
+ endpoint=selection.endpoint,
+ system=_SYSTEM,
+ messages=(UserMessage(content=(TextBlock(text=prompt),)),),
+ tools=(),
+ max_tokens=output_tokens(capabilities, _MAX_OUTPUT_TOKENS),
+ reasoning_effort=effort,
+ cache="none",
+ )
+ adapter = registry_providers(media_loader=None)(selection.endpoint.protocol)
+ text: list[str] = []
+ try:
+ async for event in adapter.stream(request, CancelToken()):
+ if isinstance(event, TextDelta):
+ text.append(event.delta)
+ elif isinstance(event, ProviderError):
+ return None
+ finally:
+ close = getattr(adapter, "aclose", None)
+ if close is not None:
+ await close()
+ return model_handle("".join(text))
+
+
+def suggest_handle(conn: Any, *, display_name: str, proposal: Optional[str]) -> tuple[str, str]:
+ """A free handle and its source (``model`` or ``transliteration``) for a new Bot."""
+ ascii_handle = ascii_name_handle(display_name)
+ if ascii_handle is not None:
+ return free_handle(conn, ascii_handle), HANDLE_SOURCE_TRANSLITERATION
+ accepted = model_handle(proposal) if proposal else None
+ if accepted is not None:
+ return free_handle(conn, accepted), HANDLE_SOURCE_MODEL
+ return free_handle(conn, fallback_handle_base(display_name)), HANDLE_SOURCE_TRANSLITERATION
diff --git a/core/bots.py b/core/bots.py
new file mode 100644
index 000000000..5ffaca854
--- /dev/null
+++ b/core/bots.py
@@ -0,0 +1,718 @@
+"""Bots: an enabled Vibey Agent plus one permanent Session and a working directory (``docs/plans/bots.md``).
+
+A Bot is no new table. Its fields live in its Agent's metadata under ``bot`` (D1), a key ordinary Agent create and
+update can neither set nor clear (``core.vibe_agents.STORE_OWNED_METADATA_KEYS``); this module is its one writer.
+
+- **Handle** (D2): lowercase ASCII, frozen once the Bot exists. It names the Session (``ses_<handle>``), the working
+ directory (``~/.avibe/bots/<handle>/``), and every ``@<bot:handle>`` marker and ``--bot`` invocation.
+- **Removing** the Bot role keeps the Agent, the Session, and the directory, hidden; the record keeps its handle with
+ ``removed_at``, so setting the Agent as a Bot again reconnects them.
+- **The main Bot** (D9) is the store-made ``main`` Agent (``VibeAgentStore.ensure_main_bot_agent``); it is always a
+ Bot, and its Session is the released ``ses_main``.
+- Bots are the instance Owner's (D1): every operation here requires the Owner.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import logging
+import re
+import subprocess
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Iterable, Mapping, Optional
+
+from sqlalchemy import func, select, update
+from sqlalchemy.engine import Connection
+
+from config import paths
+from core.vibe_agents import (
+ BOT_METADATA_KEY,
+ MAIN_BOT_HANDLE,
+ VibeAgent,
+ VibeAgentStore,
+ agent_bot_record,
+ is_main_bot_agent,
+ normalize_agent_name,
+)
+from storage.agent_session_rows import BOT_SESSION_ID_PREFIX, is_bot_session_id, reserve_write_lock
+from storage.agent_session_rows import hidden_bot_session_ids as stored_hidden_bot_session_ids
+from storage.models import agent_sessions, agents
+from vibe.authorization import AuthorizationContext, require_instance_role
+
+logger = logging.getLogger(__name__)
+
+BOT_BACKEND = "vibey"
+BOT_HANDLE_PATTERN = re.compile(r"^[a-z][a-z0-9-]{1,23}$")
+BOT_HANDLE_MAX_LENGTH = 24
+#: Handles kept for the built-in Bots: the main Bot, and later the memory and operations Bots (D2).
+RESERVED_BOT_HANDLES = frozenset({MAIN_BOT_HANDLE, "memory", "ops"})
+DISPLAY_NAME_MAX_LENGTH = 64
+AVATAR_FILENAME = "avatar.png"
+AVATAR_SIZE = 256
+AVATAR_MAX_UPLOAD_BYTES = 10 * 1024 * 1024
+EMOJI_MAX_LENGTH = 16
+HANDLE_SOURCE_MODEL = "model"
+HANDLE_SOURCE_TRANSLITERATION = "transliteration"
+GIT_INIT_TIMEOUT_SECONDS = 30
+
+
+class BotError(ValueError):
+ """A refused Bot operation: a stable ``code`` for every surface, the HTTP status it maps to, and details."""
+
+ def __init__(self, code: str, message: str, *, status: int = 400, **details: Any) -> None:
+ super().__init__(message)
+ self.code = code
+ self.status = status
+ self.details = details
+
+
+def _not_found(handle: str) -> BotError:
+ return BotError("bot_not_found", f"Bot '{handle}' not found", status=404, handle=handle)
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+# --- identity ---------------------------------------------------------------------------------------------------
+
+
+def bot_session_id(handle: str) -> str:
+ return f"{BOT_SESSION_ID_PREFIX}{handle}"
+
+
+def bot_handle_for_session_id(session_id: Any) -> Optional[str]:
+ """The handle a Bot-namespace Session id names, or None for any other Session."""
+ text = str(session_id or "")
+ if not is_bot_session_id(text):
+ return None
+ handle = text[len(BOT_SESSION_ID_PREFIX):]
+ return handle if BOT_HANDLE_PATTERN.fullmatch(handle) else None
+
+
+def bot_directory(handle: str) -> Path:
+ return paths.get_bot_dir(handle)
+
+
+def is_valid_handle(handle: Any) -> bool:
+ """D2's pattern, and no trailing hyphen: a new Bot's Agent is named after its handle, and an Agent name never
+ ends in one, so such a handle could never be created."""
+ return isinstance(handle, str) and BOT_HANDLE_PATTERN.fullmatch(handle) is not None and not handle.endswith("-")
+
+
+def normalize_handle(text: Any) -> Optional[str]:
+ """``text`` as a handle: lowercase ASCII letters, digits, and single hyphens, starting with a letter."""
+ lowered = str(text or "").lower()
+ candidate = re.sub(r"[^a-z0-9]+", "-", lowered).strip("-")
+ candidate = re.sub(r"^[^a-z]+", "", candidate)
+ candidate = candidate[:BOT_HANDLE_MAX_LENGTH].rstrip("-")
+ return candidate if is_valid_handle(candidate) else None
+
+
+def ascii_name_handle(display_name: str) -> Optional[str]:
+ """D2 step 1: an ASCII display name, normalized (``Researcher`` to ``researcher``)."""
+ name = str(display_name or "").strip()
+ return normalize_handle(name) if name.isascii() else None
+
+
+def transliterated_handle(display_name: str) -> Optional[str]:
+ """D2 step 3: the display name transliterated with ``anyascii`` (``小爱`` to ``xiaoai``)."""
+ from anyascii import anyascii
+
+ return normalize_handle(anyascii(str(display_name or "")))
+
+
+def model_handle(text: Any) -> Optional[str]:
+ """A model's proposal, accepted only if it is a handle once trimmed of quoting (``CSO`` reads as ``cso``)."""
+ candidate = str(text or "").strip().strip("`'\"").strip().removeprefix("@").lower()
+ return candidate if is_valid_handle(candidate) else None
+
+
+def _with_suffix(base: str, number: int) -> str:
+ suffix = f"-{number}"
+ return base[: BOT_HANDLE_MAX_LENGTH - len(suffix)].rstrip("-") + suffix
+
+
+def handle_taken(conn: Connection, handle: str, *, agent_id: Optional[str] = None) -> bool:
+ """Whether ``handle`` already names something other than ``agent_id``'s Bot.
+
+ A handle is a Session id, a directory, and an Agent name at once, so any of them in use takes it: another Agent
+ named so, another Agent's Bot record (removed ones too, since setting them again reconnects), a ``ses_<handle>``
+ Session not run by ``agent_id``, or an existing directory, which is someone's memory. A Bot reconnecting to its
+ own record's handle never asks.
+ """
+ owner_rows = conn.execute(
+ select(agents.c.id).where(
+ (agents.c.normalized_name == handle)
+ | (func.json_extract(agents.c.metadata_json, f"$.{BOT_METADATA_KEY}.handle") == handle)
+ )
+ ).scalars().all()
+ if any(owner != agent_id for owner in owner_rows):
+ return True
+ session_agent = conn.execute(
+ select(agent_sessions.c.agent_id).where(agent_sessions.c.id == bot_session_id(handle)).limit(1)
+ ).first()
+ if session_agent is not None and (agent_id is None or session_agent[0] != agent_id):
+ return True
+ return bot_directory(handle).exists()
+
+
+def free_handle(conn: Connection, base: str, *, agent_id: Optional[str] = None) -> str:
+ """``base``, or ``base-2``, ``base-3``... skipping reserved handles and taken ones (D2 step 4)."""
+ if not is_valid_handle(base):
+ raise BotError("bot_handle_invalid", f"'{base}' is not a valid Bot handle", handle=base)
+ candidate, number = base, 1
+ while candidate in RESERVED_BOT_HANDLES or handle_taken(conn, candidate, agent_id=agent_id):
+ number += 1
+ candidate = _with_suffix(base, number)
+ return candidate
+
+
+def require_new_handle(conn: Connection, handle: str, *, agent_id: Optional[str] = None) -> str:
+ """A handle a caller chose: valid, not reserved, and free. Never suffixed: the caller asked for this one."""
+ if not is_valid_handle(handle):
+ raise BotError(
+ "bot_handle_invalid",
+ f"'{handle}' is not a valid Bot handle: 2 to 24 lowercase letters, digits, or hyphens, starting with a "
+ "letter and not ending with a hyphen",
+ handle=handle,
+ )
+ if handle in RESERVED_BOT_HANDLES:
+ raise BotError("bot_handle_reserved", f"Bot handle '{handle}' is reserved", handle=handle)
+ if handle_taken(conn, handle, agent_id=agent_id):
+ raise BotError("bot_handle_taken", f"Bot handle '{handle}' is already taken", status=409, handle=handle)
+ return handle
+
+
+def fallback_handle_base(display_name: str) -> str:
+ """The handle base without a model: the normalized ASCII name, else the transliteration, else ``bot``."""
+ return ascii_name_handle(display_name) or transliterated_handle(display_name) or "bot"
+
+
+# --- the Bot ----------------------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Bot:
+ handle: str
+ display_name: str
+ avatar: Optional[dict[str, Any]]
+ position: int
+ agent: VibeAgent
+
+ @property
+ def builtin(self) -> bool:
+ return is_main_bot_agent(self.agent)
+
+ @property
+ def session_id(self) -> str:
+ return bot_session_id(self.handle)
+
+ @property
+ def directory(self) -> Path:
+ return bot_directory(self.handle)
+
+ @property
+ def role(self) -> str:
+ return str(self.agent.description or "")
+
+ def avatar_payload(self) -> Optional[dict[str, Any]]:
+ avatar = self.avatar or {}
+ if avatar.get("kind") == "emoji":
+ return {"kind": "emoji", "emoji": avatar.get("emoji"), "hue": avatar.get("hue")}
+ if avatar.get("kind") == "image":
+ image = self.directory / AVATAR_FILENAME
+ try:
+ version = int(image.stat().st_mtime_ns)
+ except OSError:
+ version = None
+ if version is not None:
+ return {"kind": "image", "url": f"/api/bots/{self.handle}/avatar?v={version}"}
+ return {"kind": "mascot"} if self.builtin else None
+
+ def to_payload(self) -> dict[str, Any]:
+ return {
+ "handle": self.handle,
+ # Empty means the main Bot's localized default name (D5).
+ "display_name": self.display_name,
+ "avatar": self.avatar_payload(),
+ "role": self.role,
+ "agent_name": self.agent.name,
+ "session_id": self.session_id,
+ "position": self.position,
+ "builtin": self.builtin,
+ }
+
+
+def bot_from_agent(agent: VibeAgent) -> Optional[Bot]:
+ """The Bot an Agent is, or None: archived, a removed role, or no Bot record."""
+ if agent.archived_at is not None:
+ return None
+ record = agent_bot_record(agent)
+ if record is None:
+ return None
+ try:
+ position = int(record.get("position") or 0)
+ except (TypeError, ValueError):
+ position = 0
+ avatar = record.get("avatar")
+ return Bot(
+ handle=str(record["handle"]),
+ display_name=str(record.get("display_name") or ""),
+ avatar=dict(avatar) if isinstance(avatar, dict) else None,
+ position=0 if is_main_bot_agent(agent) else position,
+ agent=agent,
+ )
+
+
+def _display_order(bot: Bot) -> tuple[int, int, str]:
+ return (0 if bot.builtin else 1, bot.position, bot.handle)
+
+
+def _agent_rows(conn: Connection) -> list[VibeAgent]:
+ rows = conn.execute(
+ select(agents).where(agents.c.archived_at.is_(None)).where(
+ func.json_extract(agents.c.metadata_json, f"$.{BOT_METADATA_KEY}.handle").is_not(None)
+ )
+ ).mappings().all()
+ return [VibeAgentStore._from_row(row) for row in rows]
+
+
+def list_bots_in(conn: Connection) -> list[Bot]:
+ """Every Bot in display order: the main Bot first, then by position."""
+ bots = [bot for bot in map(bot_from_agent, _agent_rows(conn)) if bot is not None]
+ return sorted(bots, key=_display_order)
+
+
+def hidden_bot_session_ids(conn: Connection, context: AuthorizationContext | None) -> list[str]:
+ """Bots' Sessions a reader may not see: every one for a non-Owner (D1), else those of removed Bots."""
+ owner = context is None or context.is_instance_owner
+ return sorted(stored_hidden_bot_session_ids(conn, owner=owner))
+
+
+# --- directories ------------------------------------------------------------------------------------------------
+
+
+def ensure_bot_directory(handle: str) -> Path:
+ """The Bot's working directory: created with ``git init`` and nothing else (D7). Idempotent."""
+ directory = bot_directory(handle)
+ directory.mkdir(parents=True, exist_ok=True)
+ if not (directory / ".git").exists():
+ init_bot_repository(directory)
+ return directory
+
+
+def init_bot_repository(directory: Path) -> bool:
+ from core.bot_git import bot_git_environment
+ from core.git_binary import resolve_git
+
+ git = resolve_git()
+ if git is None:
+ logger.warning("Git is unavailable; the Bot directory %s starts without history", directory)
+ return False
+ try:
+ result = subprocess.run(
+ [str(git.path), "-c", "init.defaultBranch=main", "init", "--quiet", str(directory)],
+ check=False,
+ capture_output=True,
+ text=True,
+ env=bot_git_environment(),
+ timeout=GIT_INIT_TIMEOUT_SECONDS,
+ )
+ except (OSError, subprocess.SubprocessError):
+ logger.warning("git init failed for the Bot directory %s", directory, exc_info=True)
+ return False
+ if result.returncode != 0:
+ logger.warning("git init failed for the Bot directory %s: %s", directory, result.stderr.strip())
+ return False
+ return True
+
+
+# --- validation -------------------------------------------------------------------------------------------------
+
+
+def _clean_display_name(value: Any, *, required: bool) -> str:
+ name = " ".join(str(value or "").split())
+ if not name and required:
+ raise BotError("bot_display_name_required", "A Bot needs a display name")
+ if len(name) > DISPLAY_NAME_MAX_LENGTH:
+ raise BotError(
+ "bot_display_name_too_long", f"A Bot's display name has at most {DISPLAY_NAME_MAX_LENGTH} characters"
+ )
+ return name
+
+
+def clean_emoji_avatar(value: Any) -> Optional[dict[str, Any]]:
+ """An emoji avatar (``{"emoji": ..., "hue": 0-359}``), or None to clear it."""
+ if value is None:
+ return None
+ if not isinstance(value, Mapping):
+ raise BotError("bot_avatar_invalid", "An avatar is an object with an emoji and a hue")
+ emoji = str(value.get("emoji") or "").strip()
+ hue = value.get("hue")
+ if (
+ not emoji
+ or len(emoji) > EMOJI_MAX_LENGTH
+ or any(char.isspace() or ord(char) < 32 for char in emoji)
+ or isinstance(hue, bool)
+ or not isinstance(hue, int)
+ or not 0 <= hue < 360
+ ):
+ raise BotError("bot_avatar_invalid", "An emoji avatar needs one emoji and a hue from 0 to 359")
+ return {"kind": "emoji", "emoji": emoji, "hue": hue}
+
+
+def scaled_avatar_png(data: bytes) -> bytes:
+ """An uploaded image as a ``AVATAR_SIZE`` square PNG, center-cropped (D5)."""
+ from PIL import Image, ImageOps, UnidentifiedImageError
+
+ if not data:
+ raise BotError("bot_avatar_invalid", "The avatar upload is empty")
+ if len(data) > AVATAR_MAX_UPLOAD_BYTES:
+ raise BotError("bot_avatar_too_large", "The avatar upload is larger than 10 MB", status=413)
+ try:
+ with Image.open(io.BytesIO(data)) as image:
+ image = ImageOps.exif_transpose(image)
+ image = image.convert("RGBA")
+ image = ImageOps.fit(image, (AVATAR_SIZE, AVATAR_SIZE), Image.Resampling.LANCZOS)
+ output = io.BytesIO()
+ image.save(output, format="PNG", optimize=True)
+ return output.getvalue()
+ except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError) as exc:
+ raise BotError("bot_avatar_invalid", "The avatar upload is not a readable image") from exc
+
+
+# --- the service ------------------------------------------------------------------------------------------------
+
+
+class BotService:
+ """Bot operations over the Agent catalog, Sessions, and directories. Owner only (D1)."""
+
+ def __init__(self, store: Optional[VibeAgentStore] = None) -> None:
+ self._own_store = store is None
+ self.store = store or VibeAgentStore()
+ self.engine = self.store.engine
+
+ def close(self) -> None:
+ if self._own_store:
+ self.store.close()
+
+ def __enter__(self) -> "BotService":
+ return self
+
+ def __exit__(self, *_exc: Any) -> None:
+ self.close()
+
+ # reads
+
+ def list_bots(self, *, authorization_context: Any = None) -> list[Bot]:
+ require_instance_role(authorization_context, "owner")
+ with self.engine.connect() as conn:
+ return list_bots_in(conn)
+
+ def get_bot(self, handle: str, *, authorization_context: Any = None) -> Bot:
+ require_instance_role(authorization_context, "owner")
+ with self.engine.connect() as conn:
+ return self._require_bot(conn, handle)
+
+ @staticmethod
+ def _require_bot(conn: Connection, handle: str) -> Bot:
+ handle = str(handle or "").strip()
+ for bot in list_bots_in(conn):
+ if bot.handle == handle:
+ return bot
+ raise _not_found(handle)
+
+ # the Bot's Session and directory
+
+ def ensure_home(self, bot: Bot, *, authorization_context: Any = None) -> dict[str, Any]:
+ """Prepare the Bot's directory and Session, creating what is missing; returns the Session payload."""
+ from storage import workbench_sessions_service
+
+ context = require_instance_role(authorization_context, "owner")
+ directory = ensure_bot_directory(bot.handle)
+ with self.engine.begin() as conn:
+ return workbench_sessions_service.ensure_bot_session(
+ conn,
+ session_id=bot.session_id,
+ agent={"id": bot.agent.id, "name": bot.agent.name},
+ workdir=str(directory),
+ title=bot.display_name or None,
+ authorization_context=context,
+ )
+
+ def ensure_main_bot(self, *, authorization_context: Any = None) -> Bot:
+ """The main Bot with its Agent, directory, and ``ses_main``, created or repaired on use."""
+ require_instance_role(authorization_context, "owner")
+ bot = bot_from_agent(self.store.ensure_main_bot_agent())
+ if bot is None:
+ raise BotError("bot_main_unavailable", "The main Bot's Agent is unavailable", status=409)
+ self.ensure_home(bot, authorization_context=authorization_context)
+ return bot
+
+ # writes
+
+ def create_bot(
+ self,
+ *,
+ display_name: Any,
+ handle: Optional[str] = None,
+ role: Any = None,
+ avatar: Any = None,
+ model: Optional[str] = None,
+ reasoning_effort: Optional[str] = None,
+ authorization_context: Any = None,
+ ) -> Bot:
+ """A new Vibey Agent and its Bot (D4 ``create``): its directory and Session are created with it.
+
+ The Agent is named after the handle. Its role is its description (D1). Without a model it follows the
+ main Bot's model and effort (D5).
+ """
+ context = require_instance_role(authorization_context, "owner")
+ name = _clean_display_name(display_name, required=True)
+ avatar_record = clean_emoji_avatar(avatar)
+ if not str(model or "").strip():
+ # The main Bot's model, or Vibey's while the main Bot has none yet.
+ for follows in (self.store.get_main_bot_agent(), self.store.get_builtin_default_agent_for_backend("vibey")):
+ if follows is not None and str(follows.model or "").strip():
+ model, reasoning_effort = follows.model, reasoning_effort or follows.reasoning_effort
+ break
+ requested = str(handle or "").strip() or None
+ chosen: dict[str, str] = {}
+
+ def claim(conn: Connection, agent: VibeAgent) -> None:
+ # Decided under the writer lock, in the inserting transaction, so two creates cannot take one handle.
+ if requested is not None:
+ resolved = require_new_handle(conn, requested)
+ else:
+ resolved = free_handle(conn, fallback_handle_base(name))
+ if resolved != agent.normalized_name:
+ raise _HandleMoved(resolved)
+ chosen["handle"] = resolved
+
+ base = requested or fallback_handle_base(name)
+ for _attempt in range(5):
+ with self.engine.connect() as conn:
+ candidate = require_new_handle(conn, base) if requested else free_handle(conn, base)
+ try:
+ agent = self.store._create(
+ name=candidate,
+ backend=BOT_BACKEND,
+ description=str(role or "").strip() or None,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ store_metadata={
+ BOT_METADATA_KEY: {
+ "handle": candidate,
+ "display_name": name,
+ "avatar": avatar_record,
+ "position": self._next_position(),
+ }
+ },
+ user_context=context,
+ before_insert=claim,
+ )
+ except _HandleMoved:
+ continue
+ break
+ else:
+ raise BotError("bot_handle_taken", "Could not reserve a Bot handle; try again", status=409)
+ bot = bot_from_agent(agent)
+ assert bot is not None
+ self.ensure_home(bot, authorization_context=context)
+ return bot
+
+ def set_bot(
+ self,
+ agent_name: str,
+ *,
+ display_name: Any,
+ avatar: Any = None,
+ authorization_context: Any = None,
+ ) -> Bot:
+ """Make an existing enabled Vibey Agent a Bot (D4 ``set``).
+
+ Its handle is its Agent name, or the handle it had if it was a Bot before, which reconnects its Session and
+ directory (D1).
+ """
+ context = require_instance_role(authorization_context, "owner")
+ name = _clean_display_name(display_name, required=True)
+ avatar_record = clean_emoji_avatar(avatar)
+ try:
+ normalized = normalize_agent_name(agent_name)
+ except ValueError as exc:
+ raise BotError("bot_agent_not_found", f"Agent '{agent_name}' not found", status=404) from exc
+ with self.engine.begin() as conn:
+ reserve_write_lock(conn)
+ row = conn.execute(select(agents).where(agents.c.normalized_name == normalized).limit(1)).mappings().first()
+ if row is None or row["archived_at"] is not None:
+ raise BotError("bot_agent_not_found", f"Agent '{agent_name}' not found", status=404)
+ agent = VibeAgentStore._from_row(row)
+ VibeAgentStore._require_manageable_agent(conn, agent, user_context=context)
+ if agent.backend != BOT_BACKEND:
+ raise BotError(
+ "bot_agent_backend", f"Only Vibey Agents can be Bots; '{agent.name}' runs on {agent.backend}"
+ )
+ if not agent.enabled:
+ raise BotError("bot_agent_disabled", f"Agent '{agent.name}' is disabled", status=409)
+ if agent_bot_record(agent) is not None:
+ raise BotError("bot_agent_is_bot", f"Agent '{agent.name}' is already a Bot", status=409)
+ previous = agent.metadata.get(BOT_METADATA_KEY)
+ previous = dict(previous) if isinstance(previous, dict) else {}
+ handle = str(previous.get("handle") or "")
+ if not is_valid_handle(handle):
+ handle = free_handle(conn, normalize_handle(agent.normalized_name) or fallback_handle_base(name),
+ agent_id=agent.id)
+ record = {
+ "handle": handle,
+ "display_name": name,
+ "avatar": avatar_record if avatar is not None else previous.get("avatar"),
+ "position": self._next_position(conn),
+ }
+ self._write_record(conn, agent, record)
+ agent = self._reload(conn, agent.id)
+ self._sync_session_title(conn, bot_session_id(handle), name)
+ bot = bot_from_agent(agent)
+ assert bot is not None
+ self.ensure_home(bot, authorization_context=context)
+ return bot
+
+ def update_bot(
+ self,
+ handle: str,
+ *,
+ display_name: Any = ...,
+ avatar: Any = ...,
+ position: Any = ...,
+ authorization_context: Any = None,
+ ) -> Bot:
+ """Change a Bot's display name, emoji avatar, or position among the other Bots (D5 ``PATCH``)."""
+ context = require_instance_role(authorization_context, "owner")
+ with self.engine.begin() as conn:
+ reserve_write_lock(conn)
+ bot = self._require_bot(conn, handle)
+ VibeAgentStore._require_manageable_agent(conn, bot.agent, user_context=context)
+ record = dict(agent_bot_record(bot.agent) or {})
+ if display_name is not ...:
+ record["display_name"] = _clean_display_name(display_name, required=not bot.builtin)
+ if avatar is not ...:
+ record["avatar"] = clean_emoji_avatar(avatar)
+ self._write_record(conn, bot.agent, record)
+ if position is not ...:
+ if bot.builtin:
+ raise BotError("bot_main_position", "The main Bot is always first")
+ if isinstance(position, bool) or not isinstance(position, int) or position < 1:
+ raise BotError("bot_position_invalid", "A Bot's position is a whole number from 1")
+ self._move(conn, bot.agent.id, position)
+ if display_name is not ...:
+ self._sync_session_title(conn, bot.session_id, record["display_name"])
+ return self._require_bot(conn, handle)
+
+ def remove_bot(self, handle: str, *, authorization_context: Any = None) -> Bot:
+ """Drop the Bot role, keeping the Agent, the Session, and the directory (D4 ``remove``)."""
+ context = require_instance_role(authorization_context, "owner")
+ with self.engine.begin() as conn:
+ reserve_write_lock(conn)
+ bot = self._require_bot(conn, handle)
+ if bot.builtin:
+ raise BotError("bot_main_not_removable", "The main Bot cannot be removed", status=409)
+ VibeAgentStore._require_manageable_agent(conn, bot.agent, user_context=context)
+ record = dict(agent_bot_record(bot.agent) or {})
+ record["removed_at"] = _now()
+ self._write_record(conn, bot.agent, record)
+ self._compact_positions(conn)
+ return bot
+
+ def set_avatar_image(self, handle: str, data: bytes, *, authorization_context: Any = None) -> Bot:
+ """Store an uploaded avatar as ``avatar.png`` in the Bot's directory, scaled to 256px (D5)."""
+ require_instance_role(authorization_context, "owner")
+ png = scaled_avatar_png(data)
+ bot = self.get_bot(handle, authorization_context=authorization_context)
+ directory = ensure_bot_directory(bot.handle)
+ target = directory / AVATAR_FILENAME
+ temporary = directory / f".{AVATAR_FILENAME}.tmp"
+ temporary.write_bytes(png)
+ temporary.replace(target)
+ with self.engine.begin() as conn:
+ reserve_write_lock(conn)
+ bot = self._require_bot(conn, handle)
+ record = dict(agent_bot_record(bot.agent) or {})
+ record["avatar"] = {"kind": "image"}
+ self._write_record(conn, bot.agent, record)
+ return self._require_bot(conn, handle)
+
+ def avatar_path(self, handle: str, *, authorization_context: Any = None) -> Path:
+ bot = self.get_bot(handle, authorization_context=authorization_context)
+ path = bot.directory / AVATAR_FILENAME
+ if (bot.avatar or {}).get("kind") != "image" or not path.is_file():
+ raise BotError("bot_avatar_missing", f"Bot '{handle}' has no uploaded avatar", status=404)
+ return path
+
+ # internals
+
+ @staticmethod
+ def _reload(conn: Connection, agent_id: str) -> VibeAgent:
+ return VibeAgentStore._from_row(conn.execute(select(agents).where(agents.c.id == agent_id)).mappings().one())
+
+ @staticmethod
+ def _write_record(conn: Connection, agent: VibeAgent, record: dict[str, Any]) -> None:
+ current = conn.execute(select(agents.c.metadata_json).where(agents.c.id == agent.id)).scalar_one()
+ try:
+ metadata = json.loads(current or "{}")
+ except (TypeError, ValueError):
+ metadata = {}
+ if not isinstance(metadata, dict):
+ metadata = {}
+ metadata[BOT_METADATA_KEY] = record
+ conn.execute(
+ update(agents)
+ .where(agents.c.id == agent.id)
+ .values(metadata_json=json.dumps(metadata, ensure_ascii=False, separators=(",", ":")), updated_at=_now())
+ )
+
+ def _next_position(self, conn: Optional[Connection] = None) -> int:
+ if conn is None:
+ with self.engine.connect() as fresh:
+ return self._next_position(fresh)
+ others = [bot.position for bot in list_bots_in(conn) if not bot.builtin]
+ return max(others, default=0) + 1
+
+ def _move(self, conn: Connection, agent_id: str, position: int) -> None:
+ ordered = [bot for bot in list_bots_in(conn) if not bot.builtin]
+ moving = next(bot for bot in ordered if bot.agent.id == agent_id)
+ ordered.remove(moving)
+ ordered.insert(min(position, len(ordered) + 1) - 1, moving)
+ self._renumber(conn, ordered)
+
+ def _compact_positions(self, conn: Connection) -> None:
+ self._renumber(conn, [bot for bot in list_bots_in(conn) if not bot.builtin])
+
+ def _renumber(self, conn: Connection, ordered: Iterable[Bot]) -> None:
+ for index, bot in enumerate(ordered, start=1):
+ if bot.position != index:
+ record = dict(agent_bot_record(self._reload(conn, bot.agent.id)) or {})
+ record["position"] = index
+ self._write_record(conn, bot.agent, record)
+
+ @staticmethod
+ def _sync_session_title(conn: Connection, session_id: str, display_name: str) -> None:
+ """A Bot's Session is titled by its display name; the main Bot's empty name clears it (the UI's default)."""
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .values(
+ title=display_name or None,
+ updated_at=datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ )
+ )
+
+
+class _HandleMoved(Exception):
+ """The handle checked before the insert was taken by the time the insert held the lock."""
+
+ def __init__(self, handle: str) -> None:
+ super().__init__(handle)
+ self.handle = handle
diff --git a/core/controller.py b/core/controller.py
index 43f3bf0a1..7cebc9188 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -417,11 +417,23 @@ class Controller:
return
store = self.vibe_agent_store
vibey = store.get_builtin_default_agent_for_backend("vibey", enabled_only=False)
- if vibey is None or str(vibey.model or "").strip():
+ if vibey is not None and not str(vibey.model or "").strip():
+ vibey = store.update(
+ vibey.name,
+ model=models[0].id,
+ only_if_model_unset=True,
+ user_context=instance_owner_context(),
+ )
+ # The main Bot's Agent follows Vibey's model (docs/plans/bots.md D9). On a new install it is created
+ # before any model exists, so it takes Vibey's here, under the same never-replace-a-choice rule.
+ main = store.get_main_bot_agent()
+ if main is None or str(main.model or "").strip():
return
+ follows = vibey is not None and str(vibey.model or "").strip()
store.update(
- vibey.name,
- model=models[0].id,
+ main.name,
+ model=vibey.model if follows else models[0].id,
+ reasoning_effort=vibey.reasoning_effort if follows else None,
only_if_model_unset=True,
user_context=instance_owner_context(),
)
@@ -1709,9 +1721,8 @@ class Controller:
"""Archive one Workbench session through its serialized lifecycle."""
from core.services import sessions as workbench_sessions_service
- from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID, is_bot_session, is_bot_session_id
from storage.db import create_sqlite_engine
- from storage.workbench_sessions_service import MAIN_SESSION_ID
if (
not isinstance(raw_session_id, str)
@@ -1719,11 +1730,20 @@ class Controller:
or raw_session_id != raw_session_id.strip()
):
raise ValueError("invalid Workbench session ID")
- if raw_session_id in {
- WORKSPACE_NOTICE_SESSION_ID,
- MAIN_SESSION_ID,
- }:
+ if raw_session_id == WORKSPACE_NOTICE_SESSION_ID:
raise workbench_sessions_service.ReservedSessionError(raw_session_id)
+ if is_bot_session_id(raw_session_id):
+
+ def owned_by_bot() -> bool:
+ engine = create_sqlite_engine()
+ try:
+ with engine.connect() as conn:
+ return is_bot_session(conn, raw_session_id)
+ finally:
+ engine.dispose()
+
+ if await asyncio.to_thread(owned_by_bot):
+ raise workbench_sessions_service.ReservedSessionError(raw_session_id)
async def retire_computer_use_session() -> None:
js_kernels = getattr(self, "computer_js_kernels", None)
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index f54bbb11c..4eb4aeecc 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -540,10 +540,14 @@ class SettingsHandler(BaseHandler):
current_routing=current_routing,
agent_option_limit=getattr(im_client, "route_option_limit", None),
)
- if data.agent(data.current_agent) is None and agents:
+ from core.vibe_agents import is_bot_agent
+
+ bot_ids = {row.id for row in listed if is_bot_agent(row)}
+ workers = [agent for agent in agents if agent.id not in bot_ids]
+ if data.agent(data.current_agent) is None and workers:
# The scope's Agent cannot run here. As for a default Agent, the built-in backend's is the
- # replacement only when no other Agent is listed.
- data.current_agent = min(agents, key=lambda agent: implicit_default_rank(agent.backend)).id
+ # replacement only when no other Agent is listed, and a Bot is never the replacement.
+ data.current_agent = min(workers, key=lambda agent: implicit_default_rank(agent.backend)).id
current_agent = data.agent(data.current_agent)
shown = data.agent(data.shown_agent(selected_agent))
# A form refreshed per change loads only the shown Agent's backend; the others load every listed one.
diff --git a/core/internal_server.py b/core/internal_server.py
index 2f16717c9..f445d9174 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -1679,6 +1679,19 @@ def create_app(
except Exception as exc:
logger.exception("internal backend auth test failed")
return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})
+ @app.post("/internal/bots/handle-suggestion")
+ async def _bot_handle_suggestion(request: Request) -> Any:
+ """The main Bot's model's proposal for a new Bot's handle (``docs/plans/bots.md`` D2), or null."""
+ from core.bot_handles import propose_handle_with_model
+
+ body = await _safe_json(request)
+ display_name = body.get("display_name") if isinstance(body, dict) else None
+ role = body.get("role", "") if isinstance(body, dict) else None
+ if not isinstance(display_name, str) or not display_name.strip() or not isinstance(role, str):
+ return JSONResponse(status_code=400, content={"ok": False, "error": "invalid_bot_handle_request"})
+ handle = await propose_handle_with_model(controller, display_name=display_name.strip(), role=role)
+ return {"ok": True, "handle": handle}
+
@app.post("/internal/sessions/archive")
async def _archive_session(request: Request) -> Any:
body = await _safe_json(request)
diff --git a/core/show_git.py b/core/show_git.py
index 304238327..30d43fbf8 100644
--- a/core/show_git.py
+++ b/core/show_git.py
@@ -717,9 +717,23 @@ class ShowGitRepository:
_UNSET = object()
+def _bot_directory_for_session(session_id: str) -> Path | None:
+ """A Bot Session's directory (``ses_<handle>`` and ``~/.avibe/bots/<handle>/``), when it exists."""
+ from core.bots import bot_directory, bot_handle_for_session_id
+
+ handle = bot_handle_for_session_id(session_id)
+ if handle is None:
+ return None
+ directory = bot_directory(handle)
+ return directory if directory.is_dir() else None
+
+
class ShowGitCheckpointService:
"""Turn-boundary subscriber owned by the Controller process.
+ The same boundaries give a Bot's directory its automatic history (``core.bot_git``): a Bot Session's Turn is
+ committed before it starts and after it ends, in the same ordered worker.
+
The bus delivers turn events on the controller loop. The subscriber records
them there and runs the checkpoint work, storage reads and ``git``, on one
ordered worker thread (#2734), so a slow or hung ``git`` stalls no Session.
@@ -902,7 +916,7 @@ class ShowGitCheckpointService:
self._open_bus_turns.add(session_id)
else:
self._open_bus_turns.discard(session_id)
- if not paths.get_show_page_dir(session_id).is_dir():
+ if not paths.get_show_page_dir(session_id).is_dir() and _bot_directory_for_session(session_id) is None:
if event_type == "turn.end":
self._worker.submit(self._active_turns.pop, session_id, None)
return
@@ -927,7 +941,9 @@ class ShowGitCheckpointService:
started_at=started_at,
turn_id=turn_id or context.turn_id,
)
- self._repository(session_id).checkpoint(PRE_TURN, run_id=context.run_id)
+ self._checkpoint_bot_directory(session_id, PRE_TURN, run_id=context.run_id)
+ if paths.get_show_page_dir(session_id).is_dir():
+ self._repository(session_id).checkpoint(PRE_TURN, run_id=context.run_id)
except Exception:
logger.exception("Show Page checkpoint failed at turn.start for session=%s", session_id)
@@ -957,14 +973,31 @@ class ShowGitCheckpointService:
)
)
run_id = start_context.run_id or context.run_id
- self._repository(session_id).checkpoint(
- POST_TURN,
- message=start_context.message if start_context.message_id is not None else context.message,
- run_id=run_id,
- )
+ message = start_context.message if start_context.message_id is not None else context.message
+ self._checkpoint_bot_directory(session_id, POST_TURN, message=message, run_id=run_id)
+ if paths.get_show_page_dir(session_id).is_dir():
+ self._repository(session_id).checkpoint(POST_TURN, message=message, run_id=run_id)
except Exception:
logger.exception("Show Page checkpoint failed at turn.end for session=%s", session_id)
+ def _checkpoint_bot_directory(
+ self, session_id: str, checkpoint: str, *, message: str = "", run_id: str | None = None
+ ) -> None:
+ """Commit a Bot Session's directory; a failure here never blocks the Show Page checkpoint."""
+ from core.bot_git import BotGitRepository
+ from core.bots import bot_handle_for_session_id
+
+ directory = _bot_directory_for_session(session_id)
+ handle = bot_handle_for_session_id(session_id)
+ if directory is None or handle is None or not isinstance(self.git, ResolvedGit):
+ return
+ try:
+ BotGitRepository(handle, directory, self.git).checkpoint(
+ checkpoint, session_id=session_id, message=message, run_id=run_id
+ )
+ except Exception:
+ logger.exception("Bot directory checkpoint failed at %s for session=%s", checkpoint, session_id)
+
def _repository(self, session_id: str) -> ShowGitRepository:
if not isinstance(self.git, ResolvedGit):
raise ShowGitError("Git is unavailable")
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index 98ff5242e..c4c682459 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -55,6 +55,17 @@ BUILTIN_DEFAULT_AGENT_METADATA = {"builtin": True, "builtin_default": True, "loc
BUILTIN_BACKEND_ENABLED_META_KEY = "backend_enabled"
# Catalog-owned: only the store writes them, and only on rows it created (``source == "builtin"``).
BUILTIN_AGENT_MARKER_KEYS = frozenset((*BUILTIN_DEFAULT_AGENT_METADATA, BUILTIN_BACKEND_ENABLED_META_KEY))
+#: An Agent's Bot fields (``docs/plans/bots.md`` D1): handle, display name, avatar, position, and ``removed_at``
+#: once the Bot role is removed. Written only by the Bot operations (``core/bots.py``), never by ordinary create/update.
+BOT_METADATA_KEY = "bot"
+#: Marks the store-made Agent of a built-in Bot (its handle, ``"main"``); written only by the store.
+BUILTIN_BOT_METADATA_KEY = "builtin_bot"
+MAIN_BOT_HANDLE = "main"
+#: The main Bot's Agent: its name (taking the next free one when a user Agent holds it) and its role.
+MAIN_BOT_AGENT_NAME = "main"
+MAIN_BOT_DESCRIPTION = "The user's main Bot and first point of contact."
+#: Metadata no public create or update can set, change, or clear.
+STORE_OWNED_METADATA_KEYS = frozenset((*BUILTIN_AGENT_MARKER_KEYS, BOT_METADATA_KEY, BUILTIN_BOT_METADATA_KEY))
# The description a built-in Agent is created with. The built-in backend's Agent is Vibey, as its system prompt
# says (``modules/agents/vibey/prompt.py``); the prompt's Agents roster (``core/prompts/harness-agents.md``)
# lists this description beside that identity.
@@ -130,6 +141,16 @@ class AgentAlwaysEnabledError(ValueError):
self.agent_name = str(agent_name)
+class AgentBotLockedError(ValueError):
+ """While an Agent is a Bot it stays enabled and keeps its name, backend, and row (``bots.md`` D1)."""
+
+ code = "agent_is_bot"
+
+ def __init__(self, *, agent_name: str) -> None:
+ super().__init__(self.code)
+ self.agent_name = str(agent_name)
+
+
class AgentReferenceRewriteError(ValueError):
"""A durable Agent reference cannot be rewritten without losing data."""
@@ -485,6 +506,7 @@ class VibeAgent:
payload = asdict(self)
payload["archived"] = self.archived_at is not None
payload["display_name"] = archived_agent_original_name(self) or self.name
+ payload["bot"] = agent_bot_summary(self)
return payload
@@ -497,6 +519,18 @@ class AgentArchiveResult:
default_agent_name: Optional[str] = None
+def agent_bot_summary(agent: VibeAgent) -> Optional[dict[str, Any]]:
+ """The Bot an Agent is, as Agent lists show it: handle and display name, or None."""
+ record = agent_bot_record(agent) if agent.archived_at is None else None
+ if record is None:
+ return None
+ return {
+ "handle": str(record["handle"]),
+ "display_name": str(record.get("display_name") or ""),
+ "builtin": is_main_bot_agent(agent),
+ }
+
+
def archived_agent_original_name(agent: VibeAgent) -> Optional[str]:
if agent.archived_at is None:
return None
@@ -616,7 +650,8 @@ def resolve_usable_default_agent(
.mappings()
.all()
)
- candidates = [VibeAgentStore._from_row(row) for row in rows]
+ # A Bot is a standing colleague, never a substitute default.
+ candidates = [agent for agent in map(VibeAgentStore._from_row, rows) if not is_bot_agent(agent)]
# Builtins first: they are the shape every install has and the one a caller
# is most likely to be entitled to. A built-in backend's Agents still come last.
candidates.sort(key=lambda item: (implicit_default_rank(item.backend), 0 if item.source == "builtin" else 1))
@@ -1007,6 +1042,39 @@ class VibeAgentStore:
enabled: bool = True,
user_context: Any = None,
) -> VibeAgent:
+ return self._create(
+ name=name,
+ backend=backend,
+ description=description,
+ model=model,
+ reasoning_effort=reasoning_effort,
+ system_prompt=system_prompt,
+ source=source,
+ source_ref=source_ref,
+ metadata=metadata,
+ enabled=enabled,
+ user_context=user_context,
+ )
+
+ 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,
+ enabled: bool = True,
+ user_context: Any = None,
+ store_metadata: Optional[dict[str, Any]] = None,
+ before_insert: Any = None,
+ ) -> VibeAgent:
+ """``create``, plus the catalog's own writes: ``store_metadata`` (store-owned keys, such as a Bot's fields)
+ and ``before_insert(conn, agent)``, a check run under the write lock in the inserting transaction."""
from storage import resource_access_service
raw_name, normalized = _validated_public_agent_name(name)
@@ -1027,12 +1095,18 @@ class VibeAgentStore:
enabled=bool(enabled),
source=str(source or "user"),
source_ref=_clean_optional(source_ref),
- metadata=dict(metadata or {}) if source == "builtin" else _without_builtin_markers(metadata),
+ metadata={
+ **(dict(metadata or {}) if source == "builtin" else _without_builtin_markers(metadata)),
+ **dict(store_metadata or {}),
+ },
created_at=now,
updated_at=now,
)
try:
with self.engine.begin() as conn:
+ if before_insert is not None:
+ reserve_write_lock(conn)
+ before_insert(conn, agent)
conn.execute(agents.insert().values(**self._values(agent)))
# Register a private ACL for any creating subject, including a
# Personal/email member. Organization *use* still follows the
@@ -1099,15 +1173,17 @@ class VibeAgentStore:
if system_prompt is not _UNSET:
values["system_prompt"] = _clean_optional(system_prompt)
if metadata is not _UNSET:
- # The built-in markers belong to the catalog: a caller neither sets nor clears them.
+ # The built-in markers and Bot fields belong to the catalog: a caller neither sets nor clears them.
metadata = _without_builtin_markers(metadata)
metadata.update(
- (key, existing.metadata[key]) for key in BUILTIN_AGENT_MARKER_KEYS if key in existing.metadata
+ (key, existing.metadata[key]) for key in STORE_OWNED_METADATA_KEYS if key in existing.metadata
)
values["metadata_json"] = _json_dumps(metadata)
if enabled is not _UNSET:
- if not enabled and is_always_enabled_agent(existing):
+ if not enabled and (is_always_enabled_agent(existing) or is_main_bot_agent(existing)):
raise AgentAlwaysEnabledError(agent_name=existing.name)
+ if not enabled and is_bot_agent(existing):
+ raise AgentBotLockedError(agent_name=existing.name)
values["enabled"] = 1 if bool(enabled) else 0
result = conn.execute(
agents.update()
@@ -1155,6 +1231,8 @@ class VibeAgentStore:
raise AgentArchivedEditError(agent_name=name)
if is_builtin_default_agent(agent):
raise ValueError(f"agent '{agent.name}' is built in and cannot be renamed")
+ if is_bot_agent(agent):
+ raise AgentBotLockedError(agent_name=agent.name)
if new_normalized == agent.normalized_name:
if raw_new_name == agent.name:
return agent
@@ -1230,6 +1308,8 @@ class VibeAgentStore:
code="agent_builtin",
agent_name=agent.name,
)
+ if is_bot_agent(agent):
+ raise AgentArchiveError(code=AgentBotLockedError.code, agent_name=agent.name)
if agent.archived_at is not None:
if agent.name.startswith(LEGACY_ARCHIVED_AGENT_NAME_PREFIX):
return self._compact_legacy_archive(conn, agent, now=now)
@@ -1410,6 +1490,8 @@ class VibeAgentStore:
)
if is_builtin_default_agent(agent):
raise ValueError(f"agent '{agent.name}' is built in and cannot be deleted")
+ if is_bot_agent(agent):
+ raise AgentBotLockedError(agent_name=agent.name)
result = conn.execute(agents.delete().where(agents.c.id == agent.id))
if result.rowcount:
resource_access_service.delete_resource_policy(conn, "agent", agent.id)
@@ -1593,7 +1675,7 @@ class VibeAgentStore:
.where(agents.c.archived_at.is_(None))
.order_by(agents.c.name)
).mappings()
- candidates = [VibeAgentStore._from_row(row) for row in rows]
+ candidates = [agent for agent in map(VibeAgentStore._from_row, rows) if not is_bot_agent(agent)]
for candidate in candidates:
if candidate.backend == archived.backend and is_builtin_default_agent(candidate):
return candidate
@@ -1780,6 +1862,10 @@ class VibeAgentStore:
and agent.backend not in enabled_backend_set
):
self.sync_builtin_default_agent(backend=agent.backend, backend_enabled=False, name=agent.name)
+ try:
+ self.ensure_main_bot_agent()
+ except ValueError as exc:
+ logger.warning("Skipping the main Bot's Agent: %s", exc)
default_name = self.get_default_agent_name()
default_agent = self.get(default_name) if default_name else None
enabled_ensured = [agent for agent in ensured if agent.enabled]
@@ -1795,6 +1881,64 @@ class VibeAgentStore:
self.set_default_agent_name(chosen.name, user_context=instance_owner_context())
return ensured
+ def get_main_bot_agent(self) -> Optional[VibeAgent]:
+ """The main Bot's Agent: the oldest row the store created and marked for it, under any name."""
+ with self.engine.connect() as conn:
+ rows = conn.execute(
+ select(agents)
+ .where(agents.c.source == "builtin", agents.c.archived_at.is_(None))
+ .order_by(agents.c.created_at, agents.c.id)
+ ).mappings().all()
+ return next((agent for agent in map(self._from_row, rows) if is_main_bot_agent(agent)), None)
+
+ def ensure_main_bot_agent(self) -> VibeAgent:
+ """The dedicated built-in Agent behind the main Bot (``bots.md`` D9).
+
+ Created once on the Vibey backend, named ``main`` (or the next free name when a user Agent holds it), with
+ the built-in Vibey Agent's model and effort at creation. It is always enabled and always the main Bot: a
+ missing or removed Bot record is restored, keeping the display name and avatar the user chose.
+ """
+ current = self.get_main_bot_agent()
+ if current is not None:
+ record = current.metadata.get(BOT_METADATA_KEY)
+ record = dict(record) if isinstance(record, dict) else {}
+ restored = {**_main_bot_record(), **{key: record[key] for key in ("display_name", "avatar") if key in record}}
+ return self._write_builtin_state(
+ current, metadata={**current.metadata, BOT_METADATA_KEY: restored}, enabled=True
+ )
+ vibey = self.get_builtin_default_agent_for_backend("vibey", enabled_only=False)
+
+ def only_one(conn: Connection, _agent: VibeAgent) -> None:
+ # Decided under the writer lock in the inserting transaction: two processes starting together create
+ # one main Bot, whatever names they computed before the lock.
+ rows = conn.execute(
+ select(agents)
+ .where(agents.c.source == "builtin", agents.c.archived_at.is_(None))
+ .where(func.json_extract(agents.c.metadata_json, f"$.{BUILTIN_BOT_METADATA_KEY}") == MAIN_BOT_HANDLE)
+ .limit(1)
+ ).first()
+ if rows is not None:
+ raise _MainBotExists()
+
+ try:
+ return self._create(
+ name=self._free_agent_name(MAIN_BOT_AGENT_NAME),
+ backend="vibey",
+ description=MAIN_BOT_DESCRIPTION,
+ model=vibey.model if vibey is not None else None,
+ reasoning_effort=vibey.reasoning_effort if vibey is not None else None,
+ source="builtin",
+ metadata={BUILTIN_BOT_METADATA_KEY: MAIN_BOT_HANDLE, BOT_METADATA_KEY: _main_bot_record()},
+ enabled=True,
+ before_insert=only_one,
+ )
+ except (_MainBotExists, ValueError):
+ # Another process created it first (or took the name it computed).
+ current = self.get_main_bot_agent()
+ if current is None:
+ raise
+ return current
+
def get_builtin_default_agent_for_backend(self, backend: str, *, enabled_only: bool = True) -> Optional[VibeAgent]:
"""The backend's built-in Agent: the one owner of built-in identity.
@@ -1937,7 +2081,39 @@ def _has_builtin_markers(agent: VibeAgent) -> bool:
def _without_builtin_markers(metadata: Any) -> dict[str, Any]:
- return {key: value for key, value in dict(metadata or {}).items() if key not in BUILTIN_AGENT_MARKER_KEYS}
+ return {key: value for key, value in dict(metadata or {}).items() if key not in STORE_OWNED_METADATA_KEYS}
+
+
+class _MainBotExists(Exception):
+ """The main Bot's Agent was created by someone else while this one waited for the writer lock."""
+
+
+def _main_bot_record() -> dict[str, Any]:
+ return {"handle": MAIN_BOT_HANDLE, "display_name": "", "avatar": None, "position": 0}
+
+
+def _agent_metadata(agent: Any) -> Mapping[str, Any]:
+ metadata = getattr(agent, "metadata", None)
+ return metadata if isinstance(metadata, Mapping) else {}
+
+
+def agent_bot_record(agent: VibeAgent) -> Optional[dict[str, Any]]:
+ """The Agent's Bot fields while it is a Bot: a record with a handle and no ``removed_at``."""
+ record = _agent_metadata(agent).get(BOT_METADATA_KEY)
+ if not isinstance(record, dict) or not str(record.get("handle") or "").strip() or record.get("removed_at"):
+ return None
+ return record
+
+
+def is_bot_agent(agent: VibeAgent) -> bool:
+ return getattr(agent, "archived_at", None) is None and agent_bot_record(agent) is not None
+
+
+def is_main_bot_agent(agent: VibeAgent) -> bool:
+ """The main Bot's Agent: store-made (``source == "builtin"``) and marked by the store."""
+ return getattr(agent, "source", None) == "builtin" and _agent_metadata(agent).get(BUILTIN_BOT_METADATA_KEY) == (
+ MAIN_BOT_HANDLE
+ )
def is_builtin_default_agent(agent: VibeAgent) -> bool:
@@ -1951,8 +2127,15 @@ def is_always_enabled_agent(agent: VibeAgent) -> bool:
def _implicit_default(candidates: Iterable[VibeAgent]) -> Optional[VibeAgent]:
- """The first candidate by ``implicit_default_rank``, keeping the given order among equals."""
- return min(candidates, key=lambda agent: implicit_default_rank(agent.backend), default=None)
+ """The first candidate by ``implicit_default_rank``, keeping the given order among equals.
+
+ A Bot is a standing colleague, not a worker new chats start on, so it is never chosen implicitly.
+ """
+ return min(
+ (agent for agent in candidates if not is_bot_agent(agent)),
+ key=lambda agent: implicit_default_rank(agent.backend),
+ default=None,
+ )
def _first_default(candidates: list[VibeAgent]) -> Optional[VibeAgent]:
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index 5be985642..3d3b82c5c 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -953,14 +953,22 @@ def _badge_count_for_user_key(
"""Return the unread count visible to one Push subscription owner."""
if user_key == "local":
- return messages_service.total_unread(conn, platform="avibe")
+ from core.bots import hidden_bot_session_ids
+
+ return messages_service.total_unread(
+ conn, platform="avibe", hidden_session_ids=hidden_bot_session_ids(conn, None)
+ )
context = contexts.get(user_key)
if context is None:
# Legacy remote messages predate persisted authorization claims. Keep
# delivering eligible content, but never attach a machine-global count.
return 0
if context.can_manage_instance:
- return messages_service.total_unread(conn, platform="avibe")
+ from core.bots import hidden_bot_session_ids
+
+ return messages_service.total_unread(
+ conn, platform="avibe", hidden_session_ids=hidden_bot_session_ids(conn, context)
+ )
from storage import project_access_service
diff --git a/docs/CLI.md b/docs/CLI.md
index 3c18ef18e..be8363e55 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -687,6 +687,7 @@ vibe agent run --no-callback --agent release-reviewer --message 'Review the late
vibe agent run --sync --agent release-reviewer --message 'Review the latest deployment result and print it here.'
vibe agent run --no-callback --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
vibe agent run --session-id sesk8m4q2p7x --queue --message 'Do this after the current turn.'
+vibe agent run --no-callback --bot cso --message 'Review the new login flow for security risks.'
vibe agent run --no-callback --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'
vibe agent run --session-id sesworker123 --callback-session-id sescaller456 --message 'Run the delegated investigation.'
vibe agent run --no-callback --scope-id slack::channel::C999 --visible --agent release-reviewer --message 'Post the deployment summary.'
@@ -707,6 +708,14 @@ promotes the exact existing FIFO head without adding a message. A stale head is
refused rather than replaced by the next queued item, and neither command calls
Stop.
+`--bot <handle>` messages a Bot's permanent Session (see `vibe bot`). The run is
+queued behind the Bot's earlier messages, as with `--queue`, so a Bot handles
+one message at a time. A Bot keeps one conversation on its own model:
+`--agent`, `--session-id`, the fork flags, `--model`, `--reasoning-effort`,
+the placement flags, `--cwd`, and `--close-after` are refused with `--bot`.
+`--agent` keeps its meaning for an Agent that is also a Bot: it starts a new
+Session of that Agent, never a message to the Bot.
+
Use `--fork-session <session-id>` when a new Agent Session should branch from
an existing Session's native backend context instead of starting blank. The new
Session keeps the source backend. `--agent`, `--model`, and
@@ -745,6 +754,50 @@ released after the Run settles while the Session, transcript, and Run record sta
available. It is rejected for `--session-id`, which targets an existing Session
with its own runtime lifecycle.
+### `vibe bot`
+
+Manage Bots: standing members with one permanent Session and a directory of
+their own. A Bot is an enabled Vibey Agent; its role is the Agent's
+description. Bots belong to the instance Owner.
+
+```bash
+vibe bot list
+vibe bot show main
+vibe bot create --name 'Chief Security Officer' --handle cso --role 'Reviews security risks.'
+vibe bot set reviewer --name 'Reviewer'
+vibe bot update cso --name 'Security' --emoji '🛡️' --hue 210
+vibe bot update cso --position 1
+vibe bot remove cso
+```
+
+- `list` prints every Bot, the main Bot first. `show` prints one by handle.
+- `create` makes a Vibey Agent named after the handle and makes it a Bot.
+ `--handle` is lowercase ASCII, 2 to 24 letters, digits, or hyphens, starting
+ with a letter and not ending with a hyphen; `main`, `memory`, and `ops` are
+ reserved. Without `--handle`
+ the handle comes from the name: an ASCII name is normalized, any other name
+ is transliterated, and a taken handle gets `-2`. Without `--model` the Bot
+ follows the main Bot's model and effort.
+- `set` makes an existing enabled Vibey Agent a Bot. Its handle is its Agent
+ name; an Agent that was a Bot before gets its old handle, Session, and
+ directory back.
+- `update` changes the display name, the emoji avatar (`--emoji` with `--hue`,
+ or `--clear-avatar`), or the position among the other Bots. Change the role,
+ model, or instructions with `vibe agent update`.
+- `remove` drops the Bot role and keeps the Agent, the Session, and the
+ directory. The main Bot cannot be removed.
+
+The handle never changes once the Bot exists: the Bot's Session is
+`ses_<handle>` and its directory is `~/.avibe/bots/<handle>/`. The main Bot's
+Session is `ses_main`. While an Agent is a Bot it stays enabled and cannot be
+renamed or deleted. The directory starts as an empty Git repository; Avibe
+commits it before each Turn of the Bot's Session (changes by others) and after
+it (the Bot's own changes), and never squashes its history.
+
+Each command prints a `bot` object with `handle`, `display_name`, `avatar`,
+`role`, `agent_name`, `session_id`, `position`, `builtin`, and `directory`
+(`list` prints `bots`; `remove` prints `bot_removed`).
+
### `vibe watch`
Create, update, inspect, pause, resume, or remove a managed background watch. A watch
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 2a5ca6d22..216542ad0 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -556,6 +556,7 @@ vibe agent run --no-callback --agent release-reviewer --message 'Review the late
vibe agent run --sync --agent release-reviewer --message 'Review the latest deployment result and print it here.'
vibe agent run --no-callback --session-id sesk8m4q2p7x --message 'The export finished. Share the summary.'
vibe agent run --session-id sesk8m4q2p7x --queue --message 'Do this after the current turn.'
+vibe agent run --no-callback --bot cso --message 'Review the new login flow for security risks.'
vibe agent run --no-callback --fork-session sesk8m4q2p7x --message 'Explore this alternate fix from the current context.'
vibe agent run --session-id sesworker123 --callback-session-id sescaller456 --message 'Run the delegated investigation.'
vibe agent run --no-callback --scope-id slack::channel::C999 --visible --agent release-reviewer --message 'Post the deployment summary.'
@@ -571,6 +572,12 @@ Session 空闲时立即启动;只有明确拒绝后才回退到 P3。它不会
`vibe session send-now` 是无内容 P1 操作,只提升现有的精确 FIFO 队头,不新增消息。
过期队头会被拒绝,而不会改为提升下一条;两个命令都不会调用 Stop。
+`--bot <handle>` 给伙伴(Bot)的永久 Session 发消息(见 `vibe bot`)。这次运行会像
+`--queue` 一样排在伙伴之前的消息之后,所以伙伴一次只处理一条消息。伙伴只有一个对话,
+用自己的模型:`--agent`、`--session-id`、fork 参数、`--model`、`--reasoning-effort`、
+位置参数、`--cwd` 和 `--close-after` 都不能与 `--bot` 一起使用。对同时是伙伴的
+Agent,`--agent` 的含义不变:它新建该 Agent 的一个 Session,而不是给伙伴发消息。
+
当一个新 Agent Session 需要从现有 Session 的 native backend 上下文分叉,而不是空白开始时,
使用 `--fork-session <session-id>`。新 Session 会保持源 Session 的 backend。
只有 backend 不变时,才可以通过 `--agent`、`--model`、`--reasoning-effort`
@@ -602,6 +609,41 @@ Session 或 fork)设置模型,该 Session 之后的轮次会沿用它。
Session、transcript 和 Run 记录,可以使用 `--close-after`。它不能和
`--session-id` 一起使用,因为现有 Session 自己管理 runtime 生命周期。
+### `vibe bot`
+
+管理伙伴(Bot):有一个永久 Session 和自己目录的固定成员。伙伴是一个已启用的 Vibey
+Agent,它的角色就是这个 Agent 的描述。伙伴属于实例 Owner。
+
+```bash
+vibe bot list
+vibe bot show main
+vibe bot create --name 'Chief Security Officer' --handle cso --role 'Reviews security risks.'
+vibe bot set reviewer --name 'Reviewer'
+vibe bot update cso --name 'Security' --emoji '🛡️' --hue 210
+vibe bot update cso --position 1
+vibe bot remove cso
+```
+
+- `list` 列出所有伙伴,主伙伴在最前;`show` 按 handle 显示一个伙伴。
+- `create` 新建一个以 handle 命名的 Vibey Agent,并把它设为伙伴。`--handle` 是小写
+ ASCII,2 到 24 个字母、数字或连字符,以字母开头、不以连字符结尾;`main`、`memory`、`ops` 已保留。
+ 不传 `--handle` 时,handle 由名字生成:ASCII 名字会被规范化,其他名字会被转写,
+ 被占用时加 `-2`。不传 `--model` 时,伙伴沿用主伙伴的模型和推理强度。
+- `set` 把一个已启用的现有 Vibey Agent 设为伙伴。它的 handle 就是 Agent 名称;
+ 以前当过伙伴的 Agent 会拿回原来的 handle、Session 和目录。
+- `update` 修改显示名称、emoji 头像(`--emoji` 配合 `--hue`,或 `--clear-avatar`),
+ 或在其他伙伴中的位置。角色、模型或指令用 `vibe agent update` 修改。
+- `remove` 移出伙伴,保留 Agent、Session 和目录。主伙伴不能移出。
+
+伙伴创建后 handle 不再改变:它的 Session 是 `ses_<handle>`,目录是
+`~/.avibe/bots/<handle>/`。主伙伴的 Session 是 `ses_main`。Agent 作为伙伴期间保持
+启用,不能改名或删除。目录一开始是一个空的 Git 仓库;Avibe 在伙伴 Session 的每个
+Turn 之前(他人的修改)和之后(伙伴自己的修改)自动提交,从不压缩历史。
+
+每个命令输出一个 `bot` 对象,包含 `handle`、`display_name`、`avatar`、`role`、
+`agent_name`、`session_id`、`position`、`builtin` 和 `directory`(`list` 输出
+`bots`,`remove` 输出 `bot_removed`)。
+
### `vibe watch`
创建、查看、更新、暂停、恢复或删除一个被管理的后台 watch。watch 会运行一个
diff --git a/docs/plans/bots.md b/docs/plans/bots.md
index 99a46cf2c..c41ba7b35 100644
--- a/docs/plans/bots.md
+++ b/docs/plans/bots.md
@@ -58,8 +58,9 @@ own. A Session has none of these; a Bot has all three.
1. an ASCII name is normalized (`Researcher` to `researcher`);
2. otherwise the main Bot's model, at its lowest reasoning effort, proposes
an English codename from the display name and role, accepted only if it
- matches `^[a-z][a-z0-9-]{1,23}$` (首席安全官 to `cso`); the request waits
- at most 5 seconds;
+ matches `^[a-z][a-z0-9-]{1,23}$` and does not end with a hyphen (an
+ Agent name never does) (首席安全官 to `cso`); the request waits at most
+ 5 seconds;
3. if no model answers in time or the output is invalid, transliterate with
`anyascii` (ISC license; 小爱 to `xiaoai`);
4. on a collision add `-2`, and skip reserved names.
@@ -152,9 +153,9 @@ Owner decisions 2026-11-01, from the mockups in this Session's Show Page
- *New*: name (any language), avatar, and role. The handle is generated in
the background after the name is entered (D2) and shown as a muted
`@handle` with an edit pencil; until an avatar is chosen, the avatar is the
- name's first character on a color derived from the name. The role seeds the
- Agent's system prompt and stays editable on the Agents page. The model
- follows the main Bot by default, under "Advanced".
+ name's first character on a color derived from the name. The role is
+ written to the Agent's description (D1) and stays editable on the Agents
+ page. The model follows the main Bot by default, under "Advanced".
- *From an existing Agent*: lists Vibey-backend Agents that are not Bots; the
handle is the Agent name, locked.
- Avatars come from an emoji with a background color, or an uploaded image
diff --git a/pyproject.toml b/pyproject.toml
index 7c68c6cc7..816751599 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -91,6 +91,8 @@ dependencies = [
# Vibey fits context images to the providers' per-image size limit
# (core/agent_core/ai/image_limits.py).
"Pillow>=11.0",
+ # Bot handles from display names in any script (docs/plans/bots.md D2); ISC license.
+ "anyascii>=0.3.2",
"pywebpush>=2.0.3",
# The Intel Mac Runtime is binary-only, and 48.0.1 is the newest release with
# an x86_64 macOS wheel (universal2); 49+ ships none. Elsewhere, 50.0.2
diff --git a/storage/agent_session_rows.py b/storage/agent_session_rows.py
index f38602f93..9d644f7d8 100644
--- a/storage/agent_session_rows.py
+++ b/storage/agent_session_rows.py
@@ -254,6 +254,78 @@ WORKSPACE_NOTICE_SESSION_METADATA_KEY = "workspace_notice_session"
#: than either of the two that existed.
WORKSPACE_NOTICE_SESSION_VISIBILITY = "system"
+#: A Bot's permanent Session is ``ses_<handle>`` (``docs/plans/bots.md`` D2). Generated ids are ``ses`` plus
+#: characters from ``SESSION_ID_ALPHABET``, which has no ``_``, so this prefix is the Bots' namespace alone.
+BOT_SESSION_ID_PREFIX = "ses_"
+
+
+MAIN_BOT_SESSION_ID = "ses_main"
+
+
+def is_bot_session_id(session_id: Any) -> bool:
+ """Whether ``session_id`` is in the Bots' namespace. Only ``is_bot_session`` says whether a Bot owns it."""
+
+ return str(session_id or "").startswith(BOT_SESSION_ID_PREFIX)
+
+
+def _bot_handle_column():
+ from storage.models import agents
+
+ return func.json_extract(agents.c.metadata_json, "$.bot.handle")
+
+
+def bot_session_ids(conn: Connection) -> set[str]:
+ """Every Bot's Session id, removed Bots' included: ``ses_main`` and ``ses_<handle>`` of each Bot record."""
+
+ from storage.models import agents
+
+ handles = conn.execute(select(_bot_handle_column()).select_from(agents).where(_bot_handle_column().is_not(None)))
+ return {MAIN_BOT_SESSION_ID} | {
+ f"{BOT_SESSION_ID_PREFIX}{handle}" for handle in handles.scalars() if isinstance(handle, str) and handle
+ }
+
+
+def hidden_bot_session_ids(conn: Connection, *, owner: bool) -> set[str]:
+ """Bots' Sessions a reader may not see: every one for a non-Owner, those of removed Bots for the Owner.
+
+ Bots are the Owner's (``docs/plans/bots.md`` D1), and removing the Bot role keeps its Session, hidden.
+ """
+
+ from storage.models import agents
+
+ every = bot_session_ids(conn)
+ if not owner:
+ return every
+ removed = func.json_extract(agents.c.metadata_json, "$.bot.removed_at")
+ active = {MAIN_BOT_SESSION_ID} | {
+ f"{BOT_SESSION_ID_PREFIX}{handle}"
+ for handle in conn.execute(
+ select(_bot_handle_column())
+ .select_from(agents)
+ .where(_bot_handle_column().is_not(None), removed.is_(None), agents.c.archived_at.is_(None))
+ ).scalars()
+ if isinstance(handle, str) and handle
+ }
+ return every - active
+
+
+def is_bot_session(conn: Connection, session_id: Any) -> bool:
+ """Whether a Bot owns this Session (``docs/plans/bots.md`` D2): ``ses_main``, or ``ses_<handle>`` of a Bot record.
+
+ A removed Bot's Session still counts: it is kept, hidden, for the Bot to reconnect to. Only ids in the Bots'
+ namespace reach the catalog, so every other Session pays nothing for the check.
+ """
+
+ from storage.models import agents
+
+ text = str(session_id or "")
+ if not is_bot_session_id(text):
+ return False
+ if text == MAIN_BOT_SESSION_ID:
+ return True
+ handle = text[len(BOT_SESSION_ID_PREFIX):]
+ return conn.execute(select(agents.c.id).where(_bot_handle_column() == handle).limit(1)).first() is not None
+
def session_is_runtime_owned(*, session_id: Any, visibility: Any = None) -> bool:
"""Whether the RUNTIME owns this session, i.e. it accepts no user turn.
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 475cfe93a..6c35b4568 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -433,6 +433,7 @@ def search_messages(
limit: int = 50,
include_archived: bool = False,
scope_ids: Optional[Iterable[str]] = None,
+ hidden_session_ids: Optional[Iterable[str]] = None,
) -> dict[str, Any]:
"""Global message-content search, grouped by session.
@@ -525,6 +526,9 @@ def search_messages(
)
if allowed_scope_ids is not None:
stmt = stmt.where(agent_sessions.c.scope_id.in_(allowed_scope_ids))
+ hidden = _hidden_ids(hidden_session_ids)
+ if hidden:
+ stmt = stmt.where(messages.c.session_id.not_in(hidden))
rows = conn.execute(stmt).mappings().all()
@@ -1149,11 +1153,16 @@ _DETACHED_COMPLETION_TYPES = types_with("detachedCompletion")
_UNREAD_TYPES = types_with("unread")
+def _hidden_ids(session_ids: Optional[Iterable[str]]) -> list[str]:
+ return sorted({str(session_id) for session_id in session_ids or () if session_id})
+
+
def unread_counts(
conn: Connection,
*,
platform: Optional[str] = None,
scope_ids: Optional[Iterable[str]] = None,
+ hidden_session_ids: Optional[Iterable[str]] = None,
) -> dict[str, int]:
"""Return ``{scope_id: count}`` for unread agent ``result`` messages.
@@ -1202,6 +1211,9 @@ def unread_counts(
query = query.where(messages.c.platform == platform)
if allowed_scope_ids is not None:
query = query.where(messages.c.scope_id.in_(allowed_scope_ids))
+ hidden = _hidden_ids(hidden_session_ids)
+ if hidden:
+ query = query.where(or_(messages.c.session_id.is_(None), messages.c.session_id.not_in(hidden)))
return {scope: int(count) for scope, count in conn.execute(query).all()}
@@ -1210,9 +1222,12 @@ def unread_counts_by_session(
*,
platform: Optional[str] = None,
scope_ids: Optional[Iterable[str]] = None,
+ hidden_session_ids: Optional[Iterable[str]] = None,
) -> dict[str, int]:
"""Return ``{session_id: count}`` for unread agent ``result`` messages.
+ ``hidden_session_ids`` are Sessions this reader may not see (another member's Bots, a removed Bot's Session).
+
Per-session granularity for the sidebar: a project can hold several
sessions, so a scope-level count (see ``unread_counts``) would stamp the
same badge on every session row. Rows with a null ``session_id`` are
@@ -1257,6 +1272,9 @@ def unread_counts_by_session(
)
)
)
+ hidden = _hidden_ids(hidden_session_ids)
+ if hidden:
+ query = query.where(messages.c.session_id.not_in(hidden))
return {session_id: int(count) for session_id, count in conn.execute(query).all()}
@@ -1265,6 +1283,7 @@ def total_unread(
*,
platform: Optional[str] = None,
scope_ids: Optional[Iterable[str]] = None,
+ hidden_session_ids: Optional[Iterable[str]] = None,
) -> int:
"""Global unread agent-``result`` count across all non-archived sessions.
@@ -1280,6 +1299,7 @@ def total_unread(
conn,
platform=platform,
scope_ids=scope_ids,
+ hidden_session_ids=hidden_session_ids,
).values()
)
@@ -1293,9 +1313,13 @@ def list_inbox_sessions(
before: Optional[str] = None,
only_session: Optional[str] = None,
scope_ids: Optional[Iterable[str]] = None,
+ hidden_session_ids: Optional[Iterable[str]] = None,
) -> dict[str, Any]:
"""Per-session ("Slack-like") inbox feed.
+ Bot Sessions have no scope and belong in the feed like any other conversation; ``hidden_session_ids`` names
+ the ones this reader may not see (``core.bots.hidden_bot_session_ids``).
+
One row per session that has at least one agent reply. Sorted by the
session's most recent message of *any* author (the activity clock),
descending. The preview text is the session's latest *agent* reply
@@ -1489,6 +1513,9 @@ def list_inbox_sessions(
session_rows = session_rows.where(agent_sessions.c.id == only_session)
if allowed_scope_ids is not None:
session_rows = session_rows.where(agent_sessions.c.scope_id.in_(allowed_scope_ids))
+ hidden = _hidden_ids(hidden_session_ids)
+ if hidden:
+ session_rows = session_rows.where(agent_sessions.c.id.not_in(hidden))
session_rows_sub = session_rows.subquery()
query = select(session_rows_sub).where(session_rows_sub.c.preview_id.is_not(None))
diff --git a/storage/project_access_service.py b/storage/project_access_service.py
index f23c416dc..fe49b1086 100644
--- a/storage/project_access_service.py
+++ b/storage/project_access_service.py
@@ -11,6 +11,7 @@ from sqlalchemy import delete, insert, select
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from sqlalchemy.engine import Connection
+from storage.agent_session_rows import is_bot_session
from storage.models import (
agent_sessions,
project_access_bindings,
@@ -373,6 +374,9 @@ def get_effective_session_role(
if project_id is None:
if context.is_instance_owner:
return "owner"
+ if is_bot_session(conn, session_id):
+ # Bots are the Owner's (``docs/plans/bots.md`` D1): no other member reaches a Bot's Session.
+ return None
if context.can_manage_instance and session_exists(conn, session_id):
return context.instance_role
return None
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index d574129ae..fd8ad2489 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -40,7 +40,10 @@ from storage.agent_session_rows import (
SESSION_SPEED_FAST,
SESSION_SPEED_METADATA_KEY,
WORKSPACE_NOTICE_SESSION_ID,
+ bot_session_ids,
create_agent_session_row,
+ hidden_bot_session_ids,
+ is_bot_session,
new_session_id,
session_speed,
normalize_workdir,
@@ -173,6 +176,10 @@ def _apply_session_speed(metadata: dict[str, Any], speed: Any) -> None:
raise ValueError(f"invalid session speed: {speed!r}")
+def _not_bot_session(conn: Connection):
+ return agent_sessions.c.id.not_in(sorted(bot_session_ids(conn)))
+
+
def _has_runtime_management_access(context: AuthorizationContext) -> bool:
return context.can_manage_instance
@@ -209,7 +216,11 @@ def list_sessions(
"""
context = require_instance_role(authorization_context, "viewer")
- query = select(agent_sessions).where(agent_sessions.c.visibility == "foreground")
+ query = select(agent_sessions).where(
+ agent_sessions.c.visibility == "foreground",
+ # A Bot's Session is reached through its Bot, never a session list or the ``#`` search (``bots.md`` D3).
+ _not_bot_session(conn),
+ )
if not _has_runtime_management_access(context):
accessible_scope_ids = {
project_access_service.project_scope_id(project_id)
@@ -304,6 +315,9 @@ def get_session(
).mappings().first()
if row is None:
raise LookupError(f"Session not found: {session_id}")
+ if not context.is_instance_owner and is_bot_session(conn, session_id):
+ # Bots are the Owner's (``bots.md`` D1): no other member reaches a Bot's Session.
+ raise LookupError(f"Session not found: {session_id}")
if not _has_runtime_management_access(context):
project_id = project_access_service.project_id_from_scope_id(row["scope_id"])
if project_id is None or not project_access_service.can_read_project(
@@ -434,6 +448,10 @@ def list_sessions_page(
agent_sessions.c.status == "active",
agent_sessions.c.visibility == "foreground",
)
+ # A Bot's Session is the Owner's, and a removed Bot's stays hidden until the Bot is set again (bots.md D1).
+ hidden = hidden_bot_session_ids(conn, owner=context.is_instance_owner)
+ if hidden:
+ query = query.where(agent_sessions.c.id.not_in(sorted(hidden)))
if not _has_runtime_management_access(context):
accessible_scope_ids = {
project_access_service.project_scope_id(project_id)
@@ -672,13 +690,17 @@ def create_session(
MAIN_SESSION_ID = "ses_main"
MAIN_SESSION_METADATA_KEY = "kind"
MAIN_SESSION_METADATA_VALUE = "main"
-MAIN_SESSION_WORKDIR_DIRNAME = "main"
-MAIN_SESSION_WORKDIR_COMPONENT = "owner"
-MAIN_SESSION_UPDATABLE_FIELDS = frozenset({"model", "reasoning_effort", "speed", "title", "pinned"})
+BOT_SESSION_METADATA_VALUE = "bot"
+#: The released main Session's workdir, before the main Bot moved it to its Bot directory (``bots.md`` D9).
+LEGACY_MAIN_SESSION_WORKDIR_PARTS = ("main", "owner")
+#: What a caller may change on a Bot's Session, ``ses_main`` included. Its title follows the Bot's display name
+#: and is written only by the Bot operations (``core/bots.py``).
+BOT_SESSION_UPDATABLE_FIELDS = frozenset({"model", "reasoning_effort", "speed", "pinned"})
+MAIN_SESSION_UPDATABLE_FIELDS = BOT_SESSION_UPDATABLE_FIELDS
class MainSessionArchivedError(PermissionError):
- """Raised when the fixed main-session row is already archived."""
+ """Raised when a Bot's fixed Session row is already archived."""
code = "main_session_archived"
@@ -687,7 +709,7 @@ class MainSessionArchivedError(PermissionError):
class MainSessionInvariantError(RuntimeError):
- """Raised when the fixed main-session row no longer has its built-in shape."""
+ """Raised when a Bot's fixed Session row no longer has its Bot shape."""
code = "main_session_invalid"
@@ -697,106 +719,151 @@ class MainSessionInvariantError(RuntimeError):
def main_session_workdir() -> str:
- """Return the fixed singleton main-session workdir."""
+ """The main Bot's working directory, where ``ses_main`` runs."""
- return str(paths.get_vibe_remote_dir() / MAIN_SESSION_WORKDIR_DIRNAME / MAIN_SESSION_WORKDIR_COMPONENT)
+ return bot_session_workdir("main")
-def _main_builtin_agent(conn: Connection, agent_name: str) -> dict[str, Any]:
- from core.vibe_agents import VibeAgentStore, is_builtin_default_agent
+def bot_session_workdir(handle: str) -> str:
+ return str(paths.get_bot_dir(handle))
- row = conn.execute(
- select(agents)
- .where(
- agents.c.name == str(agent_name or "").strip(),
- agents.c.backend == "vibey",
- agents.c.enabled == 1,
- agents.c.archived_at.is_(None),
- agents.c.source == "builtin",
- )
- .limit(1)
- ).mappings().first()
- if row is None or not is_builtin_default_agent(VibeAgentStore._from_row(row)):
- raise MainSessionInvariantError("built-in Vibey Agent is unavailable")
- return dict(row)
+
+def _legacy_main_session_workdir() -> str:
+ return str(paths.get_vibe_remote_dir().joinpath(*LEGACY_MAIN_SESSION_WORKDIR_PARTS))
+
+
+def _session_kind(session_id: str) -> str:
+ return MAIN_SESSION_METADATA_VALUE if session_id == MAIN_SESSION_ID else BOT_SESSION_METADATA_VALUE
-def _validate_main_session_row(
+def _bot_session_repairs(
+ conn: Connection,
row: Mapping[str, Any],
*,
+ session_id: str,
agent: Mapping[str, Any],
workdir: str,
-) -> None:
+) -> dict[str, Any]:
+ """The in-place rewrites a Bot's existing Session row needs, or ``MainSessionInvariantError``.
+
+ Two rewrites keep data where it is: the released ``ses_main`` shape (the built-in Vibey Agent in the old
+ ``~/.avibe/main/owner`` workdir) moves to the main Bot's Agent and directory, and a Bot set again after its Agent
+ was renamed follows the Agent's current name. Any other difference is corruption, refused as before.
+ """
if row.get("status") == "archived":
raise MainSessionArchivedError()
+ repairs: dict[str, Any] = {}
+ agent_id, agent_name = row.get("agent_id"), row.get("agent_name")
+ row_workdir = row.get("workdir")
+ if session_id == MAIN_SESSION_ID and agent_id != agent["id"] and row_workdir == _legacy_main_session_workdir():
+ legacy_agent = conn.execute(select(agents).where(agents.c.id == agent_id).limit(1)).mappings().first()
+ from core.vibe_agents import VibeAgentStore, is_builtin_default_agent
+
+ if legacy_agent is not None and legacy_agent["backend"] == "vibey" and is_builtin_default_agent(
+ VibeAgentStore._from_row(legacy_agent)
+ ):
+ repairs.update(agent_id=agent["id"], agent_name=agent["name"], workdir=workdir)
+ agent_id, agent_name, row_workdir = agent["id"], agent["name"], workdir
+ if agent_id == agent["id"] and agent_name != agent["name"]:
+ repairs["agent_name"] = agent["name"]
+ agent_name = agent["name"]
metadata = _load_metadata(row.get("metadata_json"))
+ actual = {**dict(row), "agent_id": agent_id, "agent_name": agent_name, "workdir": row_workdir}
expected = {
- "id": MAIN_SESSION_ID,
+ "id": session_id,
"scope_id": None,
"agent_id": agent["id"],
"agent_name": agent["name"],
"agent_backend": "vibey",
"agent_variant": "vibey",
- "session_anchor": MAIN_SESSION_ID,
+ "session_anchor": session_id,
"workdir": workdir,
"status": "active",
"visibility": "foreground",
}
for field, value in expected.items():
- if row.get(field) != value:
- raise MainSessionInvariantError(f"{field} does not match the built-in main session")
- if metadata.get(MAIN_SESSION_METADATA_KEY) != MAIN_SESSION_METADATA_VALUE:
- raise MainSessionInvariantError("metadata.kind does not identify the main session")
+ if actual.get(field) != value:
+ raise MainSessionInvariantError(f"{field} does not match the Bot's session")
+ if metadata.get(MAIN_SESSION_METADATA_KEY) != _session_kind(session_id):
+ raise MainSessionInvariantError("metadata.kind does not identify the Bot's session")
+ return repairs
-def ensure_main_session(
+def ensure_bot_session(
conn: Connection,
*,
- agent_name: str,
+ session_id: str,
+ agent: Mapping[str, Any],
+ workdir: str,
title: Optional[str] = None,
authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
) -> dict[str, Any]:
- """Resolve the stable built-in main session, creating it on first use."""
+ """Resolve a Bot's permanent Session, creating it on first use (``bots.md`` D1, D2).
+
+ The Session is ``ses_<handle>``: no scope, the Bot's Agent, its directory as the workdir. Only the instance Owner
+ reaches it. The caller prepares ``workdir`` before this reserves the writer lock.
+ """
context = require_instance_role(authorization_context, "owner")
if desktop_mini_owner_key(context) is None:
raise ProjectAccessDeniedError
- workdir = main_session_workdir()
- row = conn.execute(
- select(agent_sessions).where(agent_sessions.c.id == MAIN_SESSION_ID)
- ).mappings().first()
- if row is not None and row.get("status") == "archived":
- raise MainSessionArchivedError()
- builtin_agent = _main_builtin_agent(conn, agent_name)
- if row is not None:
- _validate_main_session_row(row, agent=builtin_agent, workdir=workdir)
- return get_session(conn, MAIN_SESSION_ID, authorization_context=context)
-
- Path(workdir).mkdir(parents=True, exist_ok=True)
- # The fixed primary key makes deletion idempotent, while the write lock closes
- # the read/insert race when two first turns arrive together.
- reserve_write_lock(conn)
- row = conn.execute(
- select(agent_sessions).where(agent_sessions.c.id == MAIN_SESSION_ID)
- ).mappings().first()
- if row is not None:
- _validate_main_session_row(row, agent=builtin_agent, workdir=workdir)
- return get_session(conn, MAIN_SESSION_ID, authorization_context=context)
-
+ for attempt in range(2):
+ row = conn.execute(select(agent_sessions).where(agent_sessions.c.id == session_id)).mappings().first()
+ if row is not None:
+ repairs = _bot_session_repairs(conn, row, session_id=session_id, agent=agent, workdir=workdir)
+ if repairs:
+ # Identity and placement only: the Session keeps its model, effort, and route settings.
+ reserve_write_lock(conn)
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .values(
+ agent_id=agent["id"],
+ agent_name=agent["name"],
+ workdir=workdir,
+ updated_at=_utc_now_iso(),
+ )
+ )
+ return get_session(conn, session_id, authorization_context=context)
+ if attempt:
+ break
+ # The fixed primary key makes creation idempotent, and the write lock closes the
+ # read/insert race when two first uses arrive together.
+ reserve_write_lock(conn)
return create_session(
conn,
scope_id=None,
- session_id=MAIN_SESSION_ID,
+ session_id=session_id,
agent_backend="",
- agent_name=agent_name,
+ agent_name=agent["name"],
+ agent_id=agent["id"],
title=title,
workdir=workdir,
- metadata={MAIN_SESSION_METADATA_KEY: MAIN_SESSION_METADATA_VALUE},
+ metadata={MAIN_SESSION_METADATA_KEY: _session_kind(session_id)},
authorization_context=context,
workdir_prepared=True,
)
+def ensure_main_session(
+ conn: Connection,
+ *,
+ agent: Mapping[str, Any],
+ title: Optional[str] = None,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Resolve the main Bot's ``ses_main``, creating it on first use."""
+
+ return ensure_bot_session(
+ conn,
+ session_id=MAIN_SESSION_ID,
+ agent=agent,
+ workdir=main_session_workdir(),
+ title=title,
+ authorization_context=authorization_context,
+ )
+
+
# Legacy desktop mini conversation support. The association lives in server-owned
# ``state_meta``, one key per principal, never in client-writable session metadata:
# a marker any editor can set on their own session (or inherit by forking) would let
@@ -1043,10 +1110,10 @@ def update_session(
``system`` itself is not assignable in the other direction either: see the
``visibility`` branch below.
"""
- is_main_session = str(session_id) == MAIN_SESSION_ID
+ is_bot_session_row = is_bot_session(conn, session_id)
authorization = require_instance_role(
authorization_context,
- "owner" if is_main_session else "editor",
+ "owner" if is_bot_session_row else "editor",
)
requested_fields = {
name
@@ -1066,7 +1133,7 @@ def update_session(
if value is not _UNSET
}
if str(session_id) == WORKSPACE_NOTICE_SESSION_ID or (
- is_main_session and not requested_fields.issubset(MAIN_SESSION_UPDATABLE_FIELDS)
+ is_bot_session_row and not requested_fields.issubset(BOT_SESSION_UPDATABLE_FIELDS)
):
raise ReservedSessionError(str(session_id))
reserve_write_lock(conn)
@@ -1544,7 +1611,8 @@ def backfill_session_title(
"""
cleaned = str(title or "").strip()
- if not cleaned:
+ if not cleaned or is_bot_session(conn, session_id):
+ # A Bot's Session is titled by the Bot's display name, never from its conversation.
return None
row = conn.execute(
@@ -2013,7 +2081,7 @@ def archive_session(
Checked BEFORE the existence lookup so the answer is the same on every install,
whether or not the lazily-created row exists yet.
"""
- if str(session_id) in {WORKSPACE_NOTICE_SESSION_ID, MAIN_SESSION_ID}:
+ if str(session_id) == WORKSPACE_NOTICE_SESSION_ID or is_bot_session(conn, session_id):
raise ReservedSessionError(str(session_id))
context = require_instance_role(authorization_context, "editor")
existing = conn.execute(
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 2f2fb624c..4c1ea0156 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -4811,7 +4811,8 @@ def test_a_new_install_starts_on_vibey_and_setup_completes_without_choosing_a_de
headers = csrf_headers(client)
try:
listed = client.get("/api/agents").get_json()
- vibey = next(row for row in listed["agents"] if row["backend"] == "vibey")
+ # The built-in Vibey Agent, not the main Bot's Agent beside it (docs/plans/bots.md D9).
+ vibey = next(row for row in listed["agents"] if row["backend"] == "vibey" and row["bot"] is None)
assert listed["default_agent_name"] == vibey["name"]
candidate = next(
@@ -4887,7 +4888,8 @@ def test_builtin_vibey_model_pick_completes_setup_without_a_cli(monkeypatch, tmp
headers = csrf_headers(client)
try:
listed = client.get("/api/agents").get_json()
- vibey = next(row for row in listed["agents"] if row["backend"] == "vibey")
+ # The built-in Vibey Agent, not the main Bot's Agent beside it (docs/plans/bots.md D9).
+ vibey = next(row for row in listed["agents"] if row["backend"] == "vibey" and row["bot"] is None)
assert vibey["model"] is None
candidates = client.get("/api/models/agents/vibey/models/candidates").get_json()["candidates"]
@@ -4988,7 +4990,9 @@ def test_vibey_starts_on_a_sources_tool_capable_model_and_setup_completes_withou
client = app.test_client()
headers = csrf_headers(client)
try:
- vibey = next(row for row in client.get("/api/agents").get_json()["agents"] if row["backend"] == "vibey")
+ vibey = next(
+ row for row in client.get("/api/agents").get_json()["agents"] if row["backend"] == "vibey" and row["bot"] is None
+ )
assert vibey["model"] is None
# A new install records the built-in Agent as its default.
recorded = client.post("/api/agents/default", json={"name": vibey["name"]}, headers=headers)
diff --git a/tests/test_agent_organization_onboarding.py b/tests/test_agent_organization_onboarding.py
index 228c4c462..0de610de3 100644
--- a/tests/test_agent_organization_onboarding.py
+++ b/tests/test_agent_organization_onboarding.py
@@ -79,30 +79,30 @@ def test_upgrade_onboarding_inventories_custom_and_system_agents_as_private(monk
backend="codex",
system_prompt="legacy prompt",
)
- # Every install also has the built-in Avibe Agent.
+ # Every install also has the built-in Avibe Agent and the main Bot's Agent.
builtins = store.ensure_builtin_default_agents(["codex", "claude"])
before = store.organization_onboarding_inventory(user_context=_organization_context())
assert before["counts"] == {
- "total": 4,
- "system": 3,
+ "total": 5,
+ "system": 4,
"custom": 1,
- "not_onboarded": 4,
+ "not_onboarded": 5,
"private": 0,
"published": 0,
"conflicts": 0,
}
result = store.onboard_organization_agents(user_context=_organization_context())
- assert result["created"] == 4
- assert result["counts"]["private"] == 4
+ assert result["created"] == 5
+ assert result["counts"]["private"] == 5
with store.engine.connect() as connection:
policies = resource_access_service.list_resource_policies(
resource_kind="agent",
organization_id="org-1",
connection=connection,
)
- assert len(policies) == 4
+ assert len(policies) == 5
assert all(policy["access_level"] == "private" for policy in policies)
assert all(policy["group_ids"] == [] for policy in policies)
diff --git a/tests/test_bot_cli.py b/tests/test_bot_cli.py
new file mode 100644
index 000000000..814191084
--- /dev/null
+++ b/tests/test_bot_cli.py
@@ -0,0 +1,120 @@
+"""``vibe bot`` and ``vibe agent run --bot`` (``docs/plans/bots.md`` D4)."""
+
+from __future__ import annotations
+
+import json
+import re
+import shlex
+import sys
+from unittest.mock import patch
+
+import pytest
+
+import vibe.cli as cli
+from storage.importer import ensure_sqlite_state
+
+
+def home(monkeypatch, tmp_path):
+ for key in ("AVIBE_SESSION_ID", "AVIBE_RUN_ID", "AVIBE_CALLER_SOURCE", "AVIBE_CALLER_BACKEND"):
+ monkeypatch.delenv(key, raising=False)
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ store = cli.VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agents([])
+ finally:
+ store.close()
+ return tmp_path
+
+
+def _run(monkeypatch, capsys, *argv: str) -> tuple[int, dict]:
+ monkeypatch.setattr(sys, "argv", ["vibe", *argv])
+ with pytest.raises(SystemExit) as exc:
+ cli.main()
+ captured = capsys.readouterr()
+ return exc.value.code, json.loads(captured.out or captured.err)
+
+
+def test_bot_commands_print_json_envelopes(home, monkeypatch, capsys):
+ code, created = _run(
+ monkeypatch, capsys, "bot", "create", "--name", "首席安全官", "--handle", "cso", "--role", "Reviews security."
+ )
+ assert code == 0, created
+ assert (created["kind"], created["bot"]["handle"], created["bot"]["directory"]) == (
+ "bot", "cso", str(home / "bots" / "cso"),
+ )
+ code, listed = _run(monkeypatch, capsys, "bot", "list")
+ assert [bot["handle"] for bot in listed["bots"]] == ["main", "cso"]
+ code, updated = _run(monkeypatch, capsys, "bot", "update", "cso", "--emoji", "🛡️", "--hue", "210")
+ assert updated["bot"]["avatar"] == {"kind": "emoji", "emoji": "🛡️", "hue": 210}
+ code, shown = _run(monkeypatch, capsys, "bot", "show", "main")
+ assert (code, shown["bot"]["session_id"]) == (0, "ses_main")
+ code, removed = _run(monkeypatch, capsys, "bot", "remove", "cso")
+ assert (code, removed["kind"], removed["session_id"]) == (0, "bot_removed", "ses_cso")
+ code, refused = _run(monkeypatch, capsys, "bot", "remove", "main")
+ assert (code, refused["code"]) == (1, "bot_main_not_removable")
+ code, again = _run(monkeypatch, capsys, "bot", "set", "cso", "--name", "CSO")
+ assert (code, again["bot"]["session_id"]) == (0, "ses_cso")
+
+
+def test_bot_commands_are_the_owners():
+ for leaf in ("list", "show", "create", "set", "update", "remove"):
+ assert cli._CLI_COMMAND_FLOORS[("bot", leaf)] == "owner"
+
+
+def _agent_run(home, capsys, argv):
+ request_store = cli.TaskExecutionStore(home / "task_requests")
+ args = cli.build_parser().parse_args(["agent", "run", *argv])
+ with patch("vibe.cli._task_request_store", return_value=request_store):
+ result = cli.cmd_agent_run(args)
+ captured = capsys.readouterr()
+ return result, json.loads(captured.out or captured.err), request_store
+
+
+def test_agent_run_bot_queues_on_the_bots_permanent_session(home, capsys):
+ result, payload, store = _agent_run(home, capsys, ["--bot", "main", "--no-callback", "--message", "hello"])
+ assert result == 0, payload
+ assert payload["run"]["session_id"] == "ses_main"
+ stored = store.get_run(payload["run"]["id"])
+ assert stored["session_id"] == "ses_main"
+ assert stored["metadata"]["delivery_intent"] == "queue"
+ assert (home / "bots" / "main" / ".git").is_dir()
+
+ result, payload, _store = _agent_run(home, capsys, ["--bot", "ghost", "--no-callback", "--message", "hi"])
+ assert (result, payload["code"]) == (1, "bot_not_found")
+
+
+ "extra",
+ [["--model", "m"], ["--reasoning-effort", "low"], ["--agent", "vibey"], ["--session-id", "ses_main"], ["--fork-self"]],
+)
+def test_agent_run_bot_refuses_flags_that_pick_or_shape_a_session(home, capsys, extra):
+ result, payload, _store = _agent_run(home, capsys, ["--bot", "main", *extra, "--no-callback", "--message", "hi"])
+ assert (result, payload["code"]) == (1, "bot_run_conflict")
+
+
+def test_agent_run_bot_without_a_caller_needs_a_callback_choice(home, capsys):
+ result, payload, _store = _agent_run(home, capsys, ["--bot", "main", "--message", "hi"])
+ assert (result, payload["code"]) == (1, "missing_async_callback")
+
+
+def test_help_examples_parse_against_the_real_cli():
+ """The examples in ``vibe bot --help`` and ``vibe agent run --help`` are live callers."""
+ examples = re.findall(r"^\s+(vibe (?:bot|agent run) .+)$", cli._bot_examples_text() + cli._agent_run_examples_text(), re.M)
+ assert sum(example.startswith("vibe bot ") for example in examples) >= 5
+ parser = cli.build_parser()
+ for example in examples:
+ parser.parse_args(shlex.split(example)[1:])
+
+
[email protected]("doc", ["docs/CLI.md", "docs/CLI_ZH.md"])
+def test_cli_reference_bot_examples_parse(doc):
+ from pathlib import Path
+
+ text = (Path(__file__).resolve().parents[1] / doc).read_text(encoding="utf-8")
+ examples = [line for line in text.splitlines() if line.startswith("vibe bot ") or line.startswith("vibe agent run") and "--bot" in line]
+ assert len(examples) >= 8
+ parser = cli.build_parser()
+ for example in examples:
+ parser.parse_args(shlex.split(example)[1:])
diff --git a/tests/test_bot_git.py b/tests/test_bot_git.py
new file mode 100644
index 000000000..f66cf087b
--- /dev/null
+++ b/tests/test_bot_git.py
@@ -0,0 +1,85 @@
+"""A Bot directory's automatic Git history (``docs/plans/bots.md`` D7)."""
+
+from __future__ import annotations
+
+import asyncio
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from config import paths
+from core import show_git
+from core.bot_git import POST_TURN, PRE_TURN, BotGitRepository
+from core.bots import ensure_bot_directory
+from core.git_binary import ResolvedGit
+from core.inbox_events import InboxEventBus
+from core.show_git import ShowGitCheckpointService, TurnCheckpointContext
+
+
+def git(monkeypatch, tmp_path) -> ResolvedGit:
+ candidate = shutil.which("git")
+ if candidate is None:
+ pytest.skip("system Git is required for Bot directory history")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ return ResolvedGit(path=Path(candidate), source="system")
+
+
+def _log(directory: Path, fmt: str = "%an|%s") -> list[str]:
+ return subprocess.run(
+ ["git", "-C", str(directory), "log", f"--format={fmt}"], check=True, capture_output=True, text=True
+ ).stdout.splitlines()
+
+
+def test_turn_checkpoints_attribute_others_before_and_the_bot_after(git):
+ directory = ensure_bot_directory("cso")
+ repo = BotGitRepository("cso", directory, git)
+ assert not repo.checkpoint(PRE_TURN, session_id="ses_cso") # git init and nothing else: nothing to record
+
+ (directory / "AGENTS.md").write_text("# Notes from the user\n")
+ assert repo.checkpoint(PRE_TURN, session_id="ses_cso", run_id="run-1")
+ (directory / "AGENTS.md").write_text("# Notes\n- Prefer short reports.\n")
+ assert repo.checkpoint(POST_TURN, session_id="ses_cso", message="Remember: short reports\nplease", run_id="run-1")
+ assert not repo.checkpoint(POST_TURN, session_id="ses_cso", message="nothing changed")
+
+ assert _log(directory) == ["@cso|Remember: short reports please", "Others|Changes by others"]
+ body = _log(directory, "%B")
+ assert "Avibe-Session: ses_cso" in body and "Avibe-Checkpoint: post-turn" in body
+
+
+def test_history_is_never_squashed(git, monkeypatch):
+ # The Show Page history squashes past its limits; a Bot's memory history keeps every commit.
+ monkeypatch.setattr(show_git, "MAX_COMMITS", 1)
+ directory = ensure_bot_directory("main")
+ repo = BotGitRepository("main", directory, git)
+ for index in range(4):
+ (directory / "notes.md").write_text(f"{index}\n")
+ repo.checkpoint(POST_TURN, session_id="ses_main", message=f"turn {index}")
+ assert len(_log(directory)) == 4
+
+
+def test_a_bot_sessions_turn_boundaries_commit_its_directory(git, monkeypatch):
+ directory = ensure_bot_directory("cso")
+ (directory / "draft.md").write_text("edited by the user between turns\n")
+ monkeypatch.setattr(
+ show_git,
+ "load_turn_checkpoint_context",
+ lambda _session_id, **_kwargs: TurnCheckpointContext(message="Review the login flow", message_id="m1"),
+ )
+ service = ShowGitCheckpointService(git)
+ bus = InboxEventBus()
+ service.start(bus)
+ try:
+ bus.publish("turn.start", {"session_id": "ses_cso", "turn_id": "t1"})
+ # The dispatch waits for the PRE_TURN commit, so it precedes the Bot's first edit.
+ asyncio.run(service.wait_for_turn_start("ses_cso"))
+ assert _log(directory) == ["Others|Changes by others"]
+ (directory / "AGENTS.md").write_text("# Security notes\n")
+ bus.publish("turn.end", {"session_id": "ses_cso", "turn_id": "t1"})
+ finally:
+ service.stop()
+ assert _log(directory) == ["@cso|Review the login flow", "Others|Changes by others"]
+ # A Bot Session is not a Show Page: no shadow repository appears for it.
+ assert not paths.get_show_git_dir("ses_cso").exists()
diff --git a/tests/test_bot_handles.py b/tests/test_bot_handles.py
new file mode 100644
index 000000000..592ea61fa
--- /dev/null
+++ b/tests/test_bot_handles.py
@@ -0,0 +1,143 @@
+"""Handle suggestions for new Bots (``docs/plans/bots.md`` D2)."""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from core import bot_handles
+from storage.importer import ensure_sqlite_state
+from tests.ui_server_test_helpers import csrf_headers
+
+
+def conn(monkeypatch, tmp_path):
+ from storage.db import create_sqlite_engine
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ with create_sqlite_engine().connect() as connection:
+ yield connection
+
+
+ ("display_name", "proposal", "expected"),
+ [
+ # An ASCII name is normalized; the model is not asked, and its answer would not count.
+ ("Researcher", "ignored", ("researcher", "transliteration")),
+ ("首席安全官", "cso", ("cso", "model")),
+ ("首席安全官", "`CSO`", ("cso", "model")),
+ ("首席安全官", "Chief Security Officer", ("shouxianquanguan", "transliteration")),
+ ("首席安全官", "cso-", ("shouxianquanguan", "transliteration")),
+ ("首席安全官", None, ("shouxianquanguan", "transliteration")),
+ ("小爱", "ops", ("ops-2", "model")),
+ ],
+)
+def test_suggestions_follow_the_d2_order(conn, display_name, proposal, expected):
+ assert bot_handles.suggest_handle(conn, display_name=display_name, proposal=proposal) == expected
+
+
+def test_only_names_without_an_ascii_handle_need_the_model():
+ assert not bot_handles.needs_model("Researcher")
+ assert bot_handles.needs_model("首席安全官")
+ assert bot_handles.needs_model("42")
+
+
+ ("efforts", "expected"),
+ [(("high", "low", "medium"), "low"), (("max", "minimal"), "minimal"), (("turbo",), "turbo"), ((), None)],
+)
+def test_lowest_effort(efforts, expected):
+ assert bot_handles.lowest_effort(efforts) == expected
+
+
+def _controller(runtime, model="main-model"):
+ store = SimpleNamespace(get_main_bot_agent=lambda: SimpleNamespace(model=model))
+ return SimpleNamespace(vibe_agent_store=store, model_hub_runtime=runtime)
+
+
+def test_the_main_bots_model_answers_at_its_lowest_effort(monkeypatch):
+ from core.agent_core.ai.provider import TextDelta
+ from modules.agents import model_hub
+ from modules.agents.vibey import models
+
+ resolved, retired, sent = [], [], []
+
+ class Runtime:
+ async def resolve(self, backend, model, *, process_scope):
+ resolved.append((backend, model, process_scope))
+ return model_hub.ModelHubLaunch(
+ backend="vibey", channel="hub", requested_model=model, target_model=model, runtime_model=model,
+ source_id="src", source_identity="identity", gateway_base_url="http://127.0.0.1:1",
+ gateway_token="token", protocol="anthropic", provider="anthropic",
+ supports_reasoning=True, reasoning_efforts=("high", "low", "medium"),
+ )
+
+ def retire_process_scope(self, backend, scope):
+ retired.append((backend, scope))
+
+ class Adapter:
+ async def stream(self, request, _cancel):
+ sent.append(request)
+ yield TextDelta(index=0, delta=" cs")
+ yield TextDelta(index=0, delta="o\n")
+
+ monkeypatch.setattr(models, "registry_providers", lambda **_kwargs: lambda _protocol: Adapter())
+ handle = asyncio.run(
+ bot_handles.propose_handle_with_model(_controller(Runtime()), display_name="首席安全官", role="Security")
+ )
+ assert handle == "cso"
+ assert resolved[0][:2] == ("vibey", "main-model")
+ assert retired == [("vibey", resolved[0][2])]
+ request = sent[0]
+ assert (request.reasoning_effort, request.tools) == ("low", ())
+ assert "首席安全官" in request.messages[0].content[0].text and "Security" in request.messages[0].content[0].text
+
+
+def test_no_route_or_no_answer_in_time_means_no_proposal():
+ class Unroutable:
+ async def resolve(self, *_args, **_kwargs):
+ raise RuntimeError("mapping_target_unavailable")
+
+ def retire_process_scope(self, *_args):
+ pass
+
+ class Silent(Unroutable):
+ async def resolve(self, *_args, **_kwargs):
+ await asyncio.sleep(10)
+
+ assert asyncio.run(bot_handles.propose_handle_with_model(_controller(Unroutable()), display_name="小爱")) is None
+ assert (
+ asyncio.run(bot_handles.propose_handle_with_model(_controller(Silent()), display_name="小爱", budget_seconds=0.05))
+ is None
+ )
+ assert asyncio.run(bot_handles.propose_handle_with_model(_controller(Unroutable(), model=None), display_name="x")) is None
+
+
+def test_the_route_transliterates_when_the_controller_cannot_answer(conn, monkeypatch):
+ from vibe import internal_client
+ from vibe.ui_server import app
+
+ calls = []
+
+ async def unavailable(display_name, role, **_kwargs):
+ calls.append((display_name, role))
+ raise internal_client.InternalServerUnavailable("down")
+
+ monkeypatch.setattr(internal_client, "propose_bot_handle", unavailable)
+ client = app.test_client()
+ response = client.post(
+ "/api/bots/handle-suggestion", json={"display_name": "小爱", "role": "Helps"}, headers=csrf_headers(client)
+ )
+ assert response.status_code == 200, response.get_json()
+ assert response.get_json() == {"ok": True, "handle": "xiaoai", "source": "transliteration"}
+ assert calls == [("小爱", "Helps")]
+
+ async def proposes(*_args, **_kwargs):
+ return "aide"
+
+ monkeypatch.setattr(internal_client, "propose_bot_handle", proposes)
+ response = client.post("/api/bots/handle-suggestion", json={"display_name": "小爱"}, headers=csrf_headers(client))
+ assert response.get_json() == {"ok": True, "handle": "aide", "source": "model"}
diff --git a/tests/test_bots.py b/tests/test_bots.py
new file mode 100644
index 000000000..b95dec5b2
--- /dev/null
+++ b/tests/test_bots.py
@@ -0,0 +1,389 @@
+"""Bots: Agent metadata plus a reserved Session and a directory (``docs/plans/bots.md`` D1, D2, D7, D9)."""
+
+from __future__ import annotations
+
+import subprocess
+
+import pytest
+
+from storage.importer import ensure_sqlite_state
+
+
+def home(monkeypatch, tmp_path):
+ from core.vibe_agents import VibeAgentStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agents([])
+ finally:
+ store.close()
+ yield tmp_path
+
+
+def service(home):
+ from core.bots import BotService
+
+ with BotService() as bots:
+ yield bots
+
+
+def _store():
+ from core.vibe_agents import VibeAgentStore
+
+ return VibeAgentStore()
+
+
+def _session(session_id: str):
+ from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import get_session
+
+ with create_sqlite_engine().connect() as conn:
+ return get_session(conn, session_id)
+
+
+def _git(directory, *args) -> str:
+ return subprocess.run(["git", "-C", str(directory), *args], check=True, capture_output=True, text=True).stdout
+
+
+# --- the main Bot -------------------------------------------------------------------------------------------------
+
+
+def test_the_main_bot_is_a_dedicated_builtin_agent_beside_vibey(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ store = _store()
+ try:
+ vibey = store.ensure_builtin_default_agent(backend="vibey")
+ store.update(vibey.name, model="vibey-model", reasoning_effort="low")
+ # A user Agent already holds the name: the main Bot's Agent takes the next free one.
+ store.create(name="main", backend="vibey")
+ store.ensure_builtin_default_agents([])
+ main = store.get_main_bot_agent()
+ assert (main.name, main.backend, main.source, main.enabled) == ("main-2", "vibey", "builtin", True)
+ assert (main.model, main.reasoning_effort) == ("vibey-model", "low")
+ assert main.description == "The user's main Bot and first point of contact."
+ # Vibey keeps its built-in identity (and its preamble); the main Bot never becomes the default for new chats.
+ assert store.get_builtin_default_agent_for_backend("vibey").id == vibey.id
+ assert store.get_default_agent().id == vibey.id
+ assert store.ensure_main_bot_agent().id == main.id
+ finally:
+ store.close()
+
+
+def test_the_main_bot_is_always_enabled_and_cannot_leave(service):
+ from core.bots import BotError
+ from core.vibe_agents import AgentAlwaysEnabledError, AgentArchiveError, AgentBotLockedError
+
+ bot = service.ensure_main_bot()
+ assert (bot.handle, bot.session_id, bot.builtin, bot.display_name) == ("main", "ses_main", True, "")
+ assert bot.to_payload()["avatar"] == {"kind": "mascot"}
+ store = service.store
+ with pytest.raises(AgentAlwaysEnabledError):
+ store.update(bot.agent.name, enabled=False)
+ with pytest.raises(AgentBotLockedError):
+ store.rename(bot.agent.name, "other")
+ with pytest.raises(AgentArchiveError) as archived:
+ store.archive(bot.agent.name)
+ assert archived.value.code == "agent_is_bot"
+ with pytest.raises(BotError) as removed:
+ service.remove_bot("main")
+ assert removed.value.code == "bot_main_not_removable"
+ renamed = service.update_bot("main", display_name="歪比")
+ assert (renamed.display_name, _session("ses_main")["title"]) == ("歪比", "歪比")
+ assert service.update_bot("main", display_name="").display_name == ""
+ assert _session("ses_main")["title"] is None
+
+
+# --- Bot fields are the catalog's ---------------------------------------------------------------------------------
+
+
+def test_ordinary_agent_writes_cannot_forge_or_strip_bot_fields(service):
+ store = service.store
+ forged = store.create(
+ name="forger", backend="vibey", metadata={"bot": {"handle": "forger"}, "builtin_bot": "main", "note": 1}
+ )
+ assert forged.metadata == {"note": 1}
+ assert service.list_bots()[-1].handle == "main"
+
+ bot = service.create_bot(display_name="Researcher")
+ kept = store.update(bot.agent.name, metadata={"note": 2})
+ assert kept.metadata["bot"]["handle"] == "researcher"
+ assert kept.metadata["note"] == 2
+ overwritten = store.update(bot.agent.name, metadata={"bot": {"handle": "other", "removed_at": "now"}})
+ assert overwritten.metadata["bot"]["handle"] == "researcher"
+ assert "removed_at" not in overwritten.metadata["bot"]
+
+
+def test_a_bot_agent_keeps_its_name_row_and_enabled_state_until_removed(service):
+ from core.vibe_agents import AgentArchiveError, AgentBotLockedError
+
+ bot = service.create_bot(display_name="Researcher")
+ store = service.store
+ with pytest.raises(AgentBotLockedError):
+ store.update(bot.agent.name, enabled=False)
+ with pytest.raises(AgentBotLockedError):
+ store.rename(bot.agent.name, "scholar")
+ with pytest.raises(AgentArchiveError):
+ store.archive(bot.agent.name)
+ with pytest.raises(AgentBotLockedError):
+ store.remove(bot.agent.name)
+
+ service.remove_bot(bot.handle)
+ assert store.rename(bot.agent.name, "scholar").name == "scholar"
+ assert store.update("scholar", enabled=False).enabled is False
+
+
+# --- custom Bots --------------------------------------------------------------------------------------------------
+
+
+def test_a_new_bot_gets_an_agent_a_session_and_a_directory_with_only_git(service, home):
+ main = service.ensure_main_bot()
+ service.store.update(main.agent.name, model="main-model", reasoning_effort="medium")
+ bot = service.create_bot(display_name="首席安全官", role="Reviews security risks.", avatar={"emoji": "🛡️", "hue": 210})
+
+ assert bot.handle == "shouxianquanguan"
+ agent = bot.agent
+ assert (agent.name, agent.backend, agent.description) == (bot.handle, "vibey", "Reviews security risks.")
+ assert (agent.model, agent.reasoning_effort) == ("main-model", "medium")
+ assert agent.system_prompt is None
+ session = _session(bot.session_id)
+ assert session["id"] == f"ses_{bot.handle}"
+ assert session["scope_id"] is None
+ assert session["workdir"] == str(home / "bots" / bot.handle)
+ assert session["title"] == "首席安全官"
+ assert session["metadata"]["kind"] == "bot"
+ assert sorted(path.name for path in (home / "bots" / bot.handle).iterdir()) == [".git"]
+ assert _git(home / "bots" / bot.handle, "rev-list", "--all") == ""
+ assert bot.to_payload()["avatar"] == {"kind": "emoji", "emoji": "🛡️", "hue": 210}
+ assert [item.handle for item in service.list_bots()] == ["main", bot.handle]
+
+
+ ("display_name", "expected"),
+ [("Researcher", "researcher"), ("小爱", "xiaoai"), ("Main", "main-2"), ("Ops", "ops-2"), ("42", "bot")],
+)
+def test_generated_handles_normalize_transliterate_and_skip_reserved(service, display_name, expected):
+ assert service.create_bot(display_name=display_name).handle == expected
+
+
+def test_generated_handles_add_a_suffix_on_collision(service):
+ service.store.create(name="xiaoai", backend="claude")
+ assert service.create_bot(display_name="小爱").handle == "xiaoai-2"
+ assert service.create_bot(display_name="小爱").handle == "xiaoai-3"
+
+
+ ("handle", "code"),
+ [
+ ("Bad Handle", "bot_handle_invalid"),
+ ("a", "bot_handle_invalid"),
+ # An Agent name never ends in a hyphen, so the Bot's Agent could not be named after this one.
+ ("researcher-", "bot_handle_invalid"),
+ ("memory", "bot_handle_reserved"),
+ ],
+)
+def test_a_chosen_handle_is_checked_never_rewritten(service, handle, code):
+ from core.bots import BotError
+
+ with pytest.raises(BotError) as refused:
+ service.create_bot(display_name="Anything", handle=handle)
+ assert refused.value.code == code
+
+
+def test_a_chosen_handle_that_is_taken_is_refused(service):
+ from core.bots import BotError
+
+ service.create_bot(display_name="Security", handle="cso")
+ with pytest.raises(BotError) as refused:
+ service.create_bot(display_name="Another", handle="cso")
+ assert (refused.value.code, refused.value.status) == ("bot_handle_taken", 409)
+
+
+def test_removing_hides_and_setting_again_reconnects(service, home):
+ bot = service.create_bot(display_name="Researcher")
+ service.remove_bot(bot.handle)
+ assert [item.handle for item in service.list_bots()] == ["main"]
+ assert _session(bot.session_id)["status"] == "active"
+ assert (home / "bots" / bot.handle / ".git").is_dir()
+
+ # Its Agent can be renamed once it is no longer a Bot; setting it again still reconnects the old handle.
+ service.store.rename(bot.agent.name, "scholar")
+ again = service.set_bot("scholar", display_name="Scholar")
+ assert (again.handle, again.session_id) == ("researcher", bot.session_id)
+ session = _session(bot.session_id)
+ assert (session["agent_name"], session["title"]) == ("scholar", "Scholar")
+
+
+def test_only_enabled_vibey_agents_can_be_set(service):
+ from core.bots import BotError
+
+ service.store.create(name="coder", backend="claude")
+ service.store.create(name="idle", backend="vibey", enabled=False)
+ for name, code in (("coder", "bot_agent_backend"), ("idle", "bot_agent_disabled"), ("ghost", "bot_agent_not_found")):
+ with pytest.raises(BotError) as refused:
+ service.set_bot(name, display_name="X")
+ assert refused.value.code == code
+ service.store.create(name="writer_1", backend="vibey")
+ bot = service.set_bot("writer_1", display_name="Writer")
+ assert bot.handle == "writer-1"
+ with pytest.raises(BotError) as twice:
+ service.set_bot("writer_1", display_name="Writer")
+ assert twice.value.code == "bot_agent_is_bot"
+
+
+def test_positions_order_bots_after_the_main_bot(service):
+ from core.bots import BotError
+
+ for name in ("Alpha", "Beta", "Gamma"):
+ service.create_bot(display_name=name)
+ service.update_bot("gamma", position=1)
+ assert [bot.handle for bot in service.list_bots()] == ["main", "gamma", "alpha", "beta"]
+ service.remove_bot("alpha")
+ assert [bot.position for bot in service.list_bots()] == [0, 1, 2]
+ with pytest.raises(BotError):
+ service.update_bot("main", position=2)
+
+
+def test_bot_operations_are_the_owners(service):
+ from vibe.authorization import AuthorizationContext, InstanceAuthorizationError
+
+ member = AuthorizationContext(instance_role="member", is_remote=True, subject="m1")
+ with pytest.raises(InstanceAuthorizationError):
+ service.list_bots(authorization_context=member)
+ with pytest.raises(InstanceAuthorizationError):
+ service.create_bot(display_name="X", authorization_context=member)
+
+
+# --- Bot Sessions -------------------------------------------------------------------------------------------------
+
+
+def test_bot_sessions_are_reserved_and_owner_only(service):
+ from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import (
+ ReservedSessionError,
+ archive_session,
+ list_sessions,
+ update_session,
+ )
+ from vibe.authorization import AuthorizationContext
+
+ bot = service.create_bot(display_name="Researcher")
+ member = AuthorizationContext(instance_role="member", is_remote=True, subject="m1")
+ with create_sqlite_engine().begin() as conn:
+ assert update_session(conn, bot.session_id, model="other-model")["model"] == "other-model"
+ for fields in ({"title": "x"}, {"agent_name": "vibey"}, {"visibility": "background"}, {"scope_id": None}):
+ with pytest.raises(ReservedSessionError):
+ update_session(conn, bot.session_id, **fields)
+ with pytest.raises(ReservedSessionError):
+ archive_session(conn, bot.session_id)
+ listed = {row["id"] for row in list_sessions(conn, status="all")["sessions"]}
+ searched = {row["id"] for row in list_sessions(conn, title_query="Research")["sessions"]}
+ assert bot.session_id not in listed | searched
+ from storage import project_access_service
+
+ assert project_access_service.get_effective_session_role(conn, member, bot.session_id) is None
+
+
+def test_the_inbox_includes_bot_sessions_for_the_owner_only(service):
+ from core.bots import hidden_bot_session_ids
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from vibe.authorization import AuthorizationContext, instance_owner_context
+
+ shown = service.create_bot(display_name="Shown")
+ removed = service.create_bot(display_name="Removed")
+ with create_sqlite_engine().begin() as conn:
+ for bot in (shown, removed):
+ messages_service.append(
+ conn, scope_id=None, session_id=bot.session_id, platform="avibe", author="agent",
+ message_type="result", text="done",
+ )
+ service.remove_bot(removed.handle)
+ member = AuthorizationContext(instance_role="member", is_remote=True, subject="m1")
+ with create_sqlite_engine().connect() as conn:
+ owner_hidden = hidden_bot_session_ids(conn, instance_owner_context())
+ feed = messages_service.list_inbox_sessions(conn, hidden_session_ids=owner_hidden)
+ assert [row["session_id"] for row in feed["sessions"]] == [shown.session_id]
+ assert messages_service.unread_counts_by_session(conn, hidden_session_ids=owner_hidden) == {shown.session_id: 1}
+ member_hidden = hidden_bot_session_ids(conn, member)
+ assert messages_service.list_inbox_sessions(conn, hidden_session_ids=member_hidden)["sessions"] == []
+ assert messages_service.total_unread(conn, hidden_session_ids=member_hidden) == 0
+
+
+def test_agents_list_exposes_bot_info(service):
+ from vibe import api
+
+ bot = service.create_bot(display_name="Researcher")
+ agents = {row["name"]: row for row in api.get_vibe_agents()["agents"]}
+ assert agents[bot.agent.name]["bot"] == {"handle": "researcher", "display_name": "Researcher", "builtin": False}
+ assert agents["main"]["bot"]["builtin"] is True
+ assert agents["vibey"]["bot"] is None
+
+
+def test_an_uploaded_avatar_is_a_256px_png_in_the_bot_directory(service, home):
+ import io
+
+ from PIL import Image
+
+ bot = service.create_bot(display_name="Researcher")
+ source = io.BytesIO()
+ Image.new("RGB", (800, 400), "red").save(source, format="JPEG")
+ updated = service.set_avatar_image(bot.handle, source.getvalue())
+ stored = home / "bots" / bot.handle / "avatar.png"
+ with Image.open(stored) as image:
+ assert (image.format, image.size) == ("PNG", (256, 256))
+ assert updated.to_payload()["avatar"]["url"].startswith(f"/api/bots/{bot.handle}/avatar?v=")
+ assert service.avatar_path(bot.handle) == stored
+
+
+def test_two_starts_racing_create_one_main_bot(home, monkeypatch):
+ """The main Bot is decided under the writer lock, not by an Agent-name collision."""
+ from sqlalchemy import func, select
+
+ from storage.models import agents
+
+ store = _store()
+ try:
+ existing = store.ensure_main_bot_agent()
+ # The other process read "no main Bot" before this one committed it.
+ real, stale = store.get_main_bot_agent, [True]
+ monkeypatch.setattr(store, "get_main_bot_agent", lambda: None if stale and stale.pop() else real())
+ assert store.ensure_main_bot_agent().id == existing.id
+ with store.engine.connect() as conn:
+ marked = conn.execute(
+ select(func.count()).select_from(agents).where(
+ func.json_extract(agents.c.metadata_json, "$.builtin_bot") == "main"
+ )
+ ).scalar_one()
+ assert marked == 1
+ finally:
+ store.close()
+
+
+def test_the_cli_session_list_hides_removed_bots_and_other_members_bots(service):
+ from storage.db import create_sqlite_engine
+ from storage.workbench_sessions_service import list_sessions_page
+ from vibe.authorization import AuthorizationContext, instance_owner_context
+
+ shown = service.create_bot(display_name="Shown")
+ removed = service.create_bot(display_name="Removed")
+ service.remove_bot(removed.handle)
+ member = AuthorizationContext(instance_role="member", is_remote=True, subject="m1")
+ with create_sqlite_engine().connect() as conn:
+ owner_ids = {row["id"] for row in list_sessions_page(conn, limit=50, authorization_context=instance_owner_context()).items}
+ member_ids = {row["id"] for row in list_sessions_page(conn, limit=50, authorization_context=member).items}
+ assert shown.session_id in owner_ids and removed.session_id not in owner_ids
+ assert not {shown.session_id, removed.session_id} & member_ids
+
+
+def test_bot_change_events_reach_only_the_owner():
+ from vibe.authorization import AuthorizationContext, can_receive_workbench_event, instance_owner_context
+
+ assert can_receive_workbench_event(instance_owner_context(), "bots.changed")
+ for role in ("member", "editor", "viewer"):
+ member = AuthorizationContext(instance_role=role, is_remote=True, subject="m1")
+ assert not can_receive_workbench_event(member, "bots.changed")
diff --git a/tests/test_bots_api.py b/tests/test_bots_api.py
new file mode 100644
index 000000000..f4c379a91
--- /dev/null
+++ b/tests/test_bots_api.py
@@ -0,0 +1,110 @@
+"""The Bots Web API (``docs/plans/bots.md`` "Web API (owner-only)")."""
+
+from __future__ import annotations
+
+import io
+
+import pytest
+
+from storage.importer import ensure_sqlite_state
+from tests.ui_server_test_helpers import csrf_headers
+from vibe.ui_server import app
+
+
+def client(monkeypatch, tmp_path):
+ from core.vibe_agents import VibeAgentStore
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ store = VibeAgentStore()
+ try:
+ store.ensure_builtin_default_agents([])
+ finally:
+ store.close()
+ return app.test_client()
+
+
+def test_every_bots_route_is_owner_only():
+ from vibe.authorization import http_authorization_policy
+
+ for method, path in (
+ ("GET", "/api/bots"),
+ ("POST", "/api/bots"),
+ ("POST", "/api/bots/set"),
+ ("POST", "/api/bots/handle-suggestion"),
+ ("PATCH", "/api/bots/cso"),
+ ("DELETE", "/api/bots/cso"),
+ ("PUT", "/api/bots/cso/avatar"),
+ ("GET", "/api/bots/cso/avatar"),
+ ):
+ assert http_authorization_policy(method, path).minimum_role == "owner", (method, path)
+
+
+def test_the_bot_lifecycle_over_http(client, tmp_path):
+ listed = client.get("/api/bots")
+ assert listed.status_code == 200, listed.get_json()
+ (main,) = listed.get_json()["bots"]
+ assert main == {
+ "handle": "main",
+ "display_name": "",
+ "avatar": {"kind": "mascot"},
+ "role": "The user's main Bot and first point of contact.",
+ "agent_name": "main",
+ "session_id": "ses_main",
+ "position": 0,
+ "builtin": True,
+ }
+ assert client.get("/api/sessions/ses_main").status_code == 200
+
+ created = client.post(
+ "/api/bots",
+ json={"display_name": "首席安全官", "handle": "cso", "role": "Reviews security.", "avatar": {"emoji": "🛡️", "hue": 210}},
+ headers=csrf_headers(client),
+ )
+ assert created.status_code == 201, created.get_json()
+ bot = created.get_json()["bot"]
+ assert (bot["handle"], bot["session_id"], bot["agent_name"], bot["position"]) == ("cso", "ses_cso", "cso", 1)
+
+ taken = client.post("/api/bots", json={"display_name": "Again", "handle": "cso"}, headers=csrf_headers(client))
+ assert (taken.status_code, taken.get_json()["error"]["code"]) == (409, "bot_handle_taken")
+
+ patched = client.patch("/api/bots/cso", json={"display_name": "安全官"}, headers=csrf_headers(client))
+ assert patched.get_json()["bot"]["display_name"] == "安全官"
+ assert client.get("/api/sessions/ses_cso").get_json()["title"] == "安全官"
+ refused = client.patch("/api/bots/cso", json={"handle": "x"}, headers=csrf_headers(client))
+ assert refused.status_code == 400
+
+ image = io.BytesIO()
+ from PIL import Image
+
+ Image.new("RGB", (64, 64), "blue").save(image, format="PNG")
+ uploaded = client.put(
+ "/api/bots/cso/avatar", content=image.getvalue(), headers={**csrf_headers(client), "content-type": "image/png"}
+ )
+ assert uploaded.status_code == 200, uploaded.get_json()
+ url = uploaded.get_json()["bot"]["avatar"]["url"]
+ served = client.get(url)
+ assert (served.status_code, served.headers["content-type"]) == (200, "image/png")
+ assert (tmp_path / "bots" / "cso" / "avatar.png").read_bytes() == served.content
+
+ assert client.delete("/api/bots/main", headers=csrf_headers(client)).status_code == 409
+ removed = client.delete("/api/bots/cso", headers=csrf_headers(client))
+ assert removed.get_json() == {"ok": True, "removed": "cso", "agent_name": "cso", "session_id": "ses_cso"}
+ assert [row["handle"] for row in client.get("/api/bots").get_json()["bots"]] == ["main"]
+
+ again = client.post("/api/bots/set", json={"agent_name": "cso", "display_name": "CSO"}, headers=csrf_headers(client))
+ assert again.get_json()["bot"]["session_id"] == "ses_cso"
+
+
+def test_bot_sessions_refuse_archive_and_title_edits(client):
+ client.post("/api/bots", json={"display_name": "Researcher"}, headers=csrf_headers(client))
+ archived = client.delete("/api/sessions/ses_researcher", headers=csrf_headers(client))
+ assert (archived.status_code, archived.get_json()["error"]["code"]) == (403, "reserved_session")
+ renamed = client.patch("/api/sessions/ses_researcher", json={"title": "x"}, headers=csrf_headers(client))
+ assert renamed.status_code == 403
+ assert client.patch(
+ "/api/sessions/ses_researcher", json={"pinned": True}, headers=csrf_headers(client)
+ ).status_code == 200
+ searched = client.get("/api/sessions?q=Research").get_json()["sessions"]
+ assert all(row["id"] != "ses_researcher" for row in searched)
diff --git a/tests/test_cli_pagination.py b/tests/test_cli_pagination.py
index 02b105947..50f6267ea 100644
--- a/tests/test_cli_pagination.py
+++ b/tests/test_cli_pagination.py
@@ -71,6 +71,7 @@ def test_all_collection_commands_share_bounded_pagination_contract() -> None:
collection_commands = {
("agent", "list"),
("agent", "models"),
+ ("bot", "list"),
("runs", "list"),
("session", "list"),
("session", "queue", "list"),
diff --git a/tests/test_desktop_mini_session.py b/tests/test_desktop_mini_session.py
index 3f0a05e1b..9eba7d769 100644
--- a/tests/test_desktop_mini_session.py
+++ b/tests/test_desktop_mini_session.py
@@ -58,17 +58,28 @@ def _ensure(principal: str, agent_name: str):
)
-def _ensure_main(principal: str, agent_name: str):
+def _ensure_main(principal: str):
+ """The main Bot's ``ses_main``, through the one path every surface uses (``core.bots``)."""
+ from core.bots import BotService
from storage.db import create_sqlite_engine
- from storage.workbench_sessions_service import ensure_main_session
+ from storage.workbench_sessions_service import MAIN_SESSION_ID, get_session
- with create_sqlite_engine().begin() as conn:
- return ensure_main_session(
- conn,
- agent_name=agent_name,
- title="Vibey",
- authorization_context=_context(principal),
- )
+ with BotService() as service:
+ service.ensure_main_bot(authorization_context=_context(principal))
+ with create_sqlite_engine().connect() as conn:
+ return get_session(conn, MAIN_SESSION_ID, authorization_context=_context(principal))
+
+
+def _main_agent():
+ from core.vibe_agents import VibeAgentStore
+
+ store = VibeAgentStore()
+ try:
+ agent = store.get_main_bot_agent()
+ finally:
+ store.close()
+ assert agent is not None
+ return agent
def _touch(project_id: str, when: str) -> None:
@@ -158,24 +169,25 @@ def test_main_session_is_created_reused_and_recreated_without_a_project(state):
from storage.models import agent_sessions
from storage.workbench_sessions_service import MAIN_SESSION_ID
- tmp_path, vibey = state
- first = _ensure_main("local", vibey.name)
+ tmp_path, _vibey = state
+ first = _ensure_main("local")
+ main = _main_agent()
assert first["id"] == MAIN_SESSION_ID
assert first["scope_id"] is None
- assert first["agent_name"] == vibey.name
+ assert (first["agent_id"], first["agent_name"]) == (main.id, main.name)
assert first["agent_backend"] == "vibey"
assert first["metadata"]["kind"] == "main"
- expected_workdir = str(paths.get_vibe_remote_dir() / "main" / "owner")
+ expected_workdir = str(paths.get_vibe_remote_dir() / "bots" / "main")
assert first["workdir"] == expected_workdir
- assert (tmp_path / "main" / "owner").is_dir()
- assert _ensure_main("local", vibey.name)["id"] == first["id"]
- remote = _ensure_main("remote:3c6111ab", vibey.name)
+ assert (tmp_path / "bots" / "main" / ".git").is_dir()
+ assert _ensure_main("local")["id"] == first["id"]
+ remote = _ensure_main("remote:3c6111ab")
assert remote["id"] == first["id"]
assert remote["workdir"] == expected_workdir
with create_sqlite_engine().begin() as conn:
conn.execute(delete(agent_sessions).where(agent_sessions.c.id == MAIN_SESSION_ID))
- rebuilt = _ensure_main("local", vibey.name)
+ rebuilt = _ensure_main("local")
assert rebuilt["id"] == MAIN_SESSION_ID
assert rebuilt["workdir"] == first["workdir"]
@@ -185,7 +197,6 @@ def test_main_session_is_created_reused_and_recreated_without_a_project(state):
[
("scope_id", "avibe::project::proj_invalid"),
("agent_id", "agent_invalid"),
- ("agent_name", "agent_invalid"),
("agent_backend", "claude"),
("agent_variant", "claude"),
("session_anchor", "ses_other"),
@@ -201,8 +212,8 @@ def test_existing_main_session_must_keep_all_built_in_invariants(state, field, v
from storage.models import agent_sessions
from storage.workbench_sessions_service import MainSessionInvariantError
- tmp_path, vibey = state
- first = _ensure_main("local", vibey.name)
+ tmp_path, _vibey = state
+ first = _ensure_main("local")
if field == "scope_id":
value = _project(tmp_path, "invariant-scope")["scope_id"]
with create_sqlite_engine().begin() as conn:
@@ -213,10 +224,68 @@ def test_existing_main_session_must_keep_all_built_in_invariants(state, field, v
)
with pytest.raises(MainSessionInvariantError) as exc:
- _ensure_main("local", vibey.name)
+ _ensure_main("local")
assert exc.value.code == "main_session_invalid"
+def test_the_released_main_session_shape_is_rewritten_in_place(state):
+ """``bots.md`` D9: ``ses_main`` on the built-in Vibey Agent in ``~/.avibe/main/owner`` moves to the main Bot.
+
+ The row keeps its id, history, and settings; only its Agent and workdir change. No data moves with it.
+ """
+ from sqlalchemy import select
+
+ from config import paths
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions, messages
+ from storage import messages_service
+ from storage.workbench_sessions_service import MAIN_SESSION_ID, create_session
+
+ tmp_path, vibey = state
+ legacy_workdir = paths.get_vibe_remote_dir() / "main" / "owner"
+ legacy_workdir.mkdir(parents=True)
+ (legacy_workdir / "notes.md").write_text("kept where it is\n")
+ with create_sqlite_engine().begin() as conn:
+ create_session(
+ conn,
+ scope_id=None,
+ session_id=MAIN_SESSION_ID,
+ agent_backend="",
+ agent_name=vibey.name,
+ title="Vibey · Desktop mini",
+ model="legacy-model",
+ workdir=str(legacy_workdir),
+ metadata={"kind": "main"},
+ workdir_prepared=True,
+ )
+ messages_service.append(
+ conn, scope_id=None, session_id=MAIN_SESSION_ID, platform="avibe", author="user", text="hello"
+ )
+
+ session = _ensure_main("local")
+ main = _main_agent()
+ assert (session["agent_id"], session["agent_name"]) == (main.id, main.name)
+ assert session["workdir"] == str(tmp_path / "bots" / "main")
+ assert (session["title"], session["model"]) == ("Vibey · Desktop mini", "legacy-model")
+ with create_sqlite_engine().connect() as conn:
+ assert conn.execute(select(messages.c.content_text).where(messages.c.session_id == MAIN_SESSION_ID)).scalars().all() == ["hello"]
+ assert conn.execute(select(agent_sessions.c.id).where(agent_sessions.c.id == MAIN_SESSION_ID)).scalar_one()
+ assert (legacy_workdir / "notes.md").read_text() == "kept where it is\n"
+ assert not (tmp_path / "bots" / "main" / "notes.md").exists()
+
+
+def test_a_renamed_agent_name_on_the_main_session_follows_the_agent(state):
+ from sqlalchemy import update
+
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions
+
+ first = _ensure_main("local")
+ with create_sqlite_engine().begin() as conn:
+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == first["id"]).values(agent_name="stale"))
+ assert _ensure_main("local")["agent_name"] == _main_agent().name
+
+
def test_archived_main_session_is_terminal_and_cannot_be_reopened(state):
from sqlalchemy import select, update
@@ -225,8 +294,7 @@ def test_archived_main_session_is_terminal_and_cannot_be_reopened(state):
from storage.models import agent_sessions
from storage.workbench_sessions_service import MainSessionArchivedError
- _tmp_path, vibey = state
- first = _ensure_main("local", vibey.name)
+ first = _ensure_main("local")
with create_sqlite_engine().begin() as conn:
with pytest.raises(workbench_sessions_service.ReservedSessionError):
workbench_sessions_service.update_session(
@@ -243,7 +311,7 @@ def test_archived_main_session_is_terminal_and_cannot_be_reopened(state):
)
with pytest.raises(MainSessionArchivedError):
- _ensure_main("local", vibey.name)
+ _ensure_main("local")
with create_sqlite_engine().connect() as conn:
assert conn.execute(
select(agent_sessions.c.status).where(agent_sessions.c.id == first["id"])
@@ -258,23 +326,24 @@ def test_archived_main_session_is_terminal_and_cannot_be_reopened(state):
workbench_sessions_service.archive_session(conn, first["id"])
-def test_main_session_is_owner_only(state):
[email protected]("role", ["member", "editor"])
+def test_main_session_is_owner_only(state, role):
from vibe.authorization import AuthorizationContext, InstanceAuthorizationError
from storage.db import create_sqlite_engine
- from storage.workbench_sessions_service import ensure_main_session
+ from storage.workbench_sessions_service import MAIN_SESSION_ID, ensure_main_session, get_session
- _tmp_path, vibey = state
+ first = _ensure_main("local")
+ other = AuthorizationContext(instance_role=role, is_remote=True, subject="member")
with create_sqlite_engine().begin() as conn:
with pytest.raises(InstanceAuthorizationError):
ensure_main_session(
conn,
- agent_name=vibey.name,
- authorization_context=AuthorizationContext(
- instance_role="editor",
- is_remote=True,
- subject="member",
- ),
+ agent={"id": first["agent_id"], "name": first["agent_name"]},
+ authorization_context=other,
)
+ # Bots are the Owner's (bots.md D1): no other member reads the Session either.
+ with pytest.raises(LookupError):
+ get_session(conn, MAIN_SESSION_ID, authorization_context=other)
@pytest.mark.parametrize(
@@ -282,15 +351,13 @@ def test_main_session_is_owner_only(state):
[
("model", "vibey-model"),
("reasoning_effort", "high"),
- ("title", "Renamed main"),
("pinned", True),
],
)
def test_main_session_allows_user_settings_updates(state, field, value):
from storage.workbench_sessions_service import MAIN_SESSION_ID
- _tmp_path, vibey = state
- _ensure_main("local", vibey.name)
+ _ensure_main("local")
client = app.test_client()
response = client.patch(
f"/api/sessions/{MAIN_SESSION_ID}",
@@ -301,15 +368,16 @@ def test_main_session_allows_user_settings_updates(state, field, value):
assert response.get_json()[field] == value
-def test_main_session_rejects_protected_patch_fields_with_403(state):
[email protected]("payload", [{"visibility": "background"}, {"title": "Renamed main"}])
+def test_main_session_rejects_protected_patch_fields_with_403(state, payload):
+ """Its title follows the main Bot's display name, so it is not a Session edit either."""
from storage.workbench_sessions_service import MAIN_SESSION_ID
- _tmp_path, vibey = state
- _ensure_main("local", vibey.name)
+ _ensure_main("local")
client = app.test_client()
response = client.patch(
f"/api/sessions/{MAIN_SESSION_ID}",
- json={"visibility": "background"},
+ json=payload,
headers=csrf_headers(client),
)
assert response.status_code == 403
@@ -319,7 +387,6 @@ def test_main_session_rejects_protected_patch_fields_with_403(state):
def test_main_workdir_is_prepared_before_writer_lock(state, monkeypatch):
from storage import workbench_sessions_service
- _tmp_path, vibey = state
lock_acquired = False
original_reserve = workbench_sessions_service.reserve_write_lock
original_mkdir = Path.mkdir
@@ -333,9 +400,13 @@ def test_main_workdir_is_prepared_before_writer_lock(state, monkeypatch):
assert not lock_acquired
return original_mkdir(path, *args, **kwargs)
- monkeypatch.setattr(workbench_sessions_service, "reserve_write_lock", reserve)
- monkeypatch.setattr(Path, "mkdir", mkdir)
- _ensure_main("local", vibey.name)
+ from core.bots import BotService
+
+ with BotService() as service:
+ monkeypatch.setattr(workbench_sessions_service, "reserve_write_lock", reserve)
+ monkeypatch.setattr(Path, "mkdir", mkdir)
+ service.ensure_main_bot(authorization_context=_context("local"))
+ assert lock_acquired
def test_main_route_returns_the_stable_session_and_can_chat_without_a_project(state):
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index 14aefa6ce..a3b01421e 100644
--- a/tests/test_member_management_parity.py
+++ b/tests/test_member_management_parity.py
@@ -115,6 +115,15 @@ _RETAINED_OWNER_ROUTES = {
("POST", "/api/bind-codes"),
("DELETE", "/api/bind-codes/{code}"),
("GET", "/api/setup/first-bind-code"),
+ # Bots are the instance Owner's (docs/plans/bots.md D1, "Web API (owner-only)").
+ ("GET", "/api/bots"),
+ ("POST", "/api/bots"),
+ ("POST", "/api/bots/set"),
+ ("POST", "/api/bots/handle-suggestion"),
+ ("PATCH", "/api/bots/{handle}"),
+ ("DELETE", "/api/bots/{handle}"),
+ ("PUT", "/api/bots/{handle}/avatar"),
+ ("GET", "/api/bots/{handle}/avatar"),
}
@@ -126,7 +135,8 @@ def test_complete_registered_api_management_inventory():
for method in (getattr(route, "methods", None) or ())
if method not in {"HEAD", "OPTIONS"}
}
- assert len(endpoints) == 307 # master 297 + 10 MCP Hub routes, classified in tests/test_mcp_hub_api.py
+ # master 297 + 10 MCP Hub routes, classified in tests/test_mcp_hub_api.py, + 8 Bots routes (Owner, above)
+ assert len(endpoints) == 315
# Editors who use Vault read avault's authorization state; the handler admits only
# instance managers to raise the Keychain dialog on the host.
for method in ("GET", "POST"):
diff --git a/tests/test_vibey_backend_registration.py b/tests/test_vibey_backend_registration.py
index eef5058a3..2ac82c9b6 100644
--- a/tests/test_vibey_backend_registration.py
+++ b/tests/test_vibey_backend_registration.py
@@ -232,6 +232,26 @@ def test_vibey_agent_runs_its_catalogs_first_model_until_it_has_one(tmp_path, sq
store.close()
[email protected]("main_model", [None, "chosen-model"])
+def test_the_main_bot_follows_vibeys_first_model_until_it_has_one(tmp_path, sqlite_db_factory, main_model):
+ """A new install creates the main Bot's Agent before any model exists; it then follows Vibey's (bots.md D9)."""
+ store = VibeAgentStore(sqlite_db_factory(tmp_path / "agents.sqlite"))
+ try:
+ store.ensure_builtin_default_agents(["vibey"])
+ main = store.get_main_bot_agent()
+ assert main.model is None
+ if main_model:
+ store.update(main.name, model=main_model)
+ controller = Controller.__new__(Controller)
+ controller.vibe_agent_store = store
+ controller.model_hub_service = _hub_catalog("gpt-5.5", "claude-opus-5-5")
+ controller._reconcile_vibey_agent_model()
+ assert store.get("vibey").model == "gpt-5.5"
+ assert store.get_main_bot_agent().model == (main_model or "gpt-5.5")
+ finally:
+ store.close()
+
+
def test_a_lost_vibey_model_hand_off_heals_on_the_next_start(tmp_path, sqlite_db_factory, monkeypatch):
"""MH-VIBEY-007: a failed Agent write after a committed seed heals at the next start."""
store = VibeAgentStore(sqlite_db_factory(tmp_path / "agents.sqlite"))
@@ -471,7 +491,10 @@ def test_an_im_picker_routes_to_exactly_the_agent_it_lists(tmp_path, sqlite_db_f
controller.get_cwd = lambda _context: str(tmp_path)
context = MessageContext(user_id="U1", channel_id="C-test", platform="slack")
listed = {agent.name: agent for agent in asyncio.run(handler._gather_routing_modal_data(context)).agents}
- expected = {built_in.name: "vibey", "claude": "claude", **({"vibey": "claude"} if name_taken else {})}
+ # The main Bot's Agent is an enabled Vibey Agent too, and routes like any other (docs/plans/bots.md D4).
+ expected = {
+ built_in.name: "vibey", "claude": "claude", "main": "vibey", **({"vibey": "claude"} if name_taken else {})
+ }
assert set(listed) == set(expected)
for name, backend in expected.items():
diff --git a/uv.lock b/uv.lock
index 23d251d54..69314626e 100644
--- a/uv.lock
+++ b/uv.lock
@@ -265,6 +265,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643, upload-time = "2024-05-20T21:33:24.1Z" },
]
+[[package]]
+name = "anyascii"
+version = "0.3.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/db/ba/edebda727008390936da4a9bf677c19cd63b32d51e864656d2cbd1028e25/anyascii-0.3.3.tar.gz", hash = "sha256:c94e9dd9d47b3d9494eca305fef9447d00b4bf1a32aff85aa746fa3ec7fb95c3", size = 264680, upload-time = "2025-06-29T03:33:30.427Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c2/76/783b75a21ce3563b8709050de030ae253853b147bd52e141edc1025aa268/anyascii-0.3.3-py3-none-any.whl", hash = "sha256:f5ab5e53c8781a36b5a40e1296a0eeda2f48c649ef10c3921c1381b1d00dee7a", size = 345090, upload-time = "2025-06-29T03:33:28.356Z" },
+]
+
[[package]]
name = "anyio"
version = "4.15.1"
@@ -372,6 +381,7 @@ dependencies = [
{ name = "aiohttp" },
{ name = "aiohttp-socks" },
{ name = "alembic" },
+ { name = "anyascii" },
{ name = "anyio" },
{ name = "apscheduler" },
{ name = "certifi" },
@@ -426,6 +436,7 @@ requires-dist = [
{ name = "aiohttp", specifier = ">=3.8.0" },
{ name = "aiohttp-socks", specifier = ">=0.8.0" },
{ name = "alembic", specifier = ">=1.13.0" },
+ { name = "anyascii", specifier = ">=0.3.2" },
{ name = "anyio", specifier = ">=4.0.0" },
{ name = "apscheduler", specifier = ">=3.10.4" },
{ name = "certifi", specifier = ">=2026.10.23" },
diff --git a/vibe/api.py b/vibe/api.py
index d73837c82..00ab4d8e6 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -129,6 +129,7 @@ from modules.agents.catalog import (
from modules.agents.subagent_router import list_codex_subagents
from core.vibe_agents import (
AgentAlwaysEnabledError,
+ AgentBotLockedError,
AgentArchivedEditError,
AgentArchiveError,
AgentNameValidationError,
@@ -2100,6 +2101,8 @@ def _vibe_agent_payload(agent, *, brief: bool = False, remote_safe: bool = False
"archived_at": payload["archived_at"],
"source": payload["source"],
"updated_at": payload["updated_at"],
+ # The Bot this Agent is, if any (``docs/plans/bots.md`` D1): handle and display name.
+ "bot": payload["bot"],
}
if remote_safe:
projected.update(
@@ -2352,7 +2355,7 @@ def update_vibe_agent(name: str, payload: dict, *, user_context: Any = None) ->
)
except AgentNameValidationError as exc:
return _agent_name_validation_error(exc)
- except (AgentArchivedEditError, AgentAlwaysEnabledError) as exc:
+ except (AgentArchivedEditError, AgentAlwaysEnabledError, AgentBotLockedError) as exc:
return _agent_lifecycle_error(exc)
except AgentReferenceRewriteError as exc:
return _agent_reference_rewrite_error(exc)
@@ -2375,7 +2378,7 @@ def _agent_name_validation_error(exc: AgentNameValidationError) -> dict:
}
-def _agent_lifecycle_error(exc: AgentArchivedEditError | AgentAlwaysEnabledError) -> dict:
+def _agent_lifecycle_error(exc: AgentArchivedEditError | AgentAlwaysEnabledError | AgentBotLockedError) -> dict:
try:
lang = V2Config.load().language
except Exception:
diff --git a/vibe/cli.py b/vibe/cli.py
index 4f865110a..15eb06534 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -57,7 +57,7 @@ from core.caller_context import (
from core.command_runner import command_line_preview
from core.cron_weekday import ambiguous_weekday_field, weekday_readings
from core.install_integrity import verify_python_environment, verify_site_packages
-from core.vibe_agents import AgentAlwaysEnabledError, AgentArchivedEditError, AgentArchiveError, AgentNameValidationError, AgentReferenceRewriteError, VibeAgent, VibeAgentAccessError, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
+from core.vibe_agents import AgentAlwaysEnabledError, AgentArchivedEditError, AgentBotLockedError, AgentArchiveError, AgentNameValidationError, AgentReferenceRewriteError, VibeAgent, VibeAgentAccessError, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backend
from core.watches import (
DEFAULT_RETRY_EXIT_CODE,
NO_EVENT_EXIT_CODE,
@@ -5735,7 +5735,7 @@ def cmd_agent_update(args):
agent = _agent_store().update(args.name, **kwargs)
_print_cli_payload("agent", agent=_agent_payload(agent), **_agent_value_warning_fields(agent))
return 0
- except (AgentArchivedEditError, AgentAlwaysEnabledError) as exc:
+ except (AgentArchivedEditError, AgentAlwaysEnabledError, AgentBotLockedError) as exc:
_print_task_error(_agent_lifecycle_cli_error(exc))
return 1
except Exception as exc:
@@ -5748,7 +5748,7 @@ def cmd_agent_set_enabled(args, *, enabled: bool):
agent = _agent_store().set_enabled(args.name, enabled)
_print_cli_payload("agent", agent=_agent_payload(agent))
return 0
- except (AgentArchivedEditError, AgentAlwaysEnabledError) as exc:
+ except (AgentArchivedEditError, AgentAlwaysEnabledError, AgentBotLockedError) as exc:
_print_task_error(_agent_lifecycle_cli_error(exc))
return 1
except Exception as exc:
@@ -5756,7 +5756,9 @@ def cmd_agent_set_enabled(args, *, enabled: bool):
return 1
-def _agent_lifecycle_cli_error(exc: AgentArchivedEditError | AgentAlwaysEnabledError) -> TaskCliError:
+def _agent_lifecycle_cli_error(
+ exc: AgentArchivedEditError | AgentAlwaysEnabledError | AgentBotLockedError,
+) -> TaskCliError:
key = f"error.agentLifecycle.{exc.code}"
return TaskCliError(
i18n_t(f"{key}.message", agent=exc.agent_name),
@@ -6677,9 +6679,227 @@ def _release_cli_session_reservation(session_id: str, *, reason: str) -> bool:
)
+def _bot_cli_payload(bot) -> dict:
+ return {**bot.to_payload(), "directory": str(bot.directory)}
+
+
+def _bot_cli_error(exc: Exception, *, help_command: str) -> int:
+ from core.bots import BotError
+
+ if isinstance(exc, BotError):
+ exc = TaskCliError(str(exc), code=exc.code, help_command=help_command, details=exc.details or None)
+ _print_task_error(exc, help_command=help_command)
+ return 1
+
+
+def _bot_avatar_arg(args, *, help_command: str):
+ """``--emoji`` with ``--hue``, ``--clear-avatar``, or nothing (``...``)."""
+ emoji = (getattr(args, "emoji", None) or "").strip()
+ hue = getattr(args, "hue", None)
+ if getattr(args, "clear_avatar", False):
+ return None
+ if not emoji and hue is None:
+ return ...
+ if not emoji or hue is None:
+ raise TaskCliError(
+ "--emoji and --hue go together",
+ code="bot_avatar_invalid",
+ hint="Pass one emoji and a hue from 0 to 359, for example --emoji '🛡️' --hue 210.",
+ help_command=help_command,
+ )
+ return {"emoji": emoji, "hue": hue}
+
+
+def cmd_bot_list(args):
+ from core.bots import BotService
+
+ try:
+ page_request = _page_request_from_args(args, help_command="vibe bot list --help")
+ with BotService() as service:
+ service.ensure_main_bot()
+ bots = service.list_bots()
+ result = page_sequence(bots, page_request)
+ _print_cli_payload(
+ "bots",
+ bots=[_bot_cli_payload(bot) for bot in result.items],
+ **_paginated_fields(result, command=["vibe", "bot", "list"]),
+ )
+ return 0
+ except Exception as exc:
+ return _bot_cli_error(exc, help_command="vibe bot list --help")
+
+
+def cmd_bot_show(args):
+ from core.bots import MAIN_BOT_HANDLE, BotService
+
+ try:
+ with BotService() as service:
+ bot = service.ensure_main_bot() if args.handle == MAIN_BOT_HANDLE else service.get_bot(args.handle)
+ _print_cli_payload("bot", bot=_bot_cli_payload(bot))
+ return 0
+ except Exception as exc:
+ return _bot_cli_error(exc, help_command="vibe bot show --help")
+
+
+def cmd_bot_create(args):
+ from core.bots import BotService
+
+ help_command = "vibe bot create --help"
+ try:
+ avatar = _bot_avatar_arg(args, help_command=help_command)
+ with BotService() as service:
+ bot = service.create_bot(
+ display_name=args.name,
+ handle=args.handle,
+ role=args.role,
+ avatar=None if avatar is ... else avatar,
+ model=args.model,
+ reasoning_effort=args.reasoning_effort,
+ )
+ _print_cli_payload("bot", bot=_bot_cli_payload(bot))
+ return 0
+ except Exception as exc:
+ return _bot_cli_error(exc, help_command=help_command)
+
+
+def cmd_bot_set(args):
+ from core.bots import BotService
+
+ help_command = "vibe bot set --help"
+ try:
+ avatar = _bot_avatar_arg(args, help_command=help_command)
+ with BotService() as service:
+ bot = service.set_bot(args.agent, display_name=args.name, avatar=None if avatar is ... else avatar)
+ _print_cli_payload("bot", bot=_bot_cli_payload(bot))
+ return 0
+ except Exception as exc:
+ return _bot_cli_error(exc, help_command=help_command)
+
+
+def cmd_bot_update(args):
+ from core.bots import BotService
+
+ help_command = "vibe bot update --help"
+ try:
+ fields: dict = {}
+ if args.name is not None:
+ fields["display_name"] = args.name
+ avatar = _bot_avatar_arg(args, help_command=help_command)
+ if avatar is not ...:
+ fields["avatar"] = avatar
+ if args.position is not None:
+ fields["position"] = args.position
+ if not fields:
+ raise TaskCliError(
+ "no Bot fields were changed",
+ code="no_bot_changes",
+ hint="Pass --name, --emoji with --hue, --clear-avatar, or --position. The handle never changes.",
+ help_command=help_command,
+ )
+ with BotService() as service:
+ bot = service.update_bot(args.handle, **fields)
+ _print_cli_payload("bot", bot=_bot_cli_payload(bot))
+ return 0
+ except Exception as exc:
+ return _bot_cli_error(exc, help_command=help_command)
+
+
+def cmd_bot_remove(args):
+ from core.bots import BotService
+
+ try:
+ with BotService() as service:
+ bot = service.remove_bot(args.handle)
+ _print_cli_payload(
+ "bot_removed",
+ handle=bot.handle,
+ agent_name=bot.agent.name,
+ session_id=bot.session_id,
+ directory=str(bot.directory),
+ )
+ return 0
+ except Exception as exc:
+ return _bot_cli_error(exc, help_command="vibe bot remove --help")
+
+
+def _bot_examples_text() -> str:
+ return dedent(
+ """\
+ A Bot is an enabled Vibey Agent with one permanent Session and its own directory,
+ ~/.avibe/bots/<handle>/, which is its memory. Its role is the Agent's description.
+ Message a Bot with `vibe agent run --bot <handle> --message ...`.
+
+ Examples:
+ vibe bot list
+ vibe bot create --name 'Chief Security Officer' --handle cso --role 'Reviews security risks.'
+ vibe bot set reviewer --name 'Reviewer'
+ vibe bot update cso --emoji '🛡️' --hue 210
+ vibe bot remove cso
+ """
+ )
+
+
+_BOT_RUN_CONFLICTS = (
+ ("agent", "--agent"),
+ ("session_id", "--session-id"),
+ ("fork_session", "--fork-session"),
+ ("fork_self", "--fork-self"),
+ ("model", "--model"),
+ ("reasoning_effort", "--reasoning-effort"),
+ ("same_scope", "--same-scope"),
+ ("scope_id", "--scope-id"),
+ ("visibility", "--visible"),
+ ("cwd", "--cwd"),
+ ("close_after", "--close-after"),
+)
+
+
+def _resolve_bot_run_target(args) -> None:
+ """``--bot <handle>``: the Bot's permanent Session, queued (``docs/plans/bots.md`` D4).
+
+ A Bot keeps one conversation on its own model, so the flags that pick or shape a Session do not apply. The
+ Session and directory are prepared here when missing, then the run continues as a queued ``--session-id`` run.
+ """
+ from core.bots import MAIN_BOT_HANDLE, BotError, BotService
+
+ handle = (getattr(args, "bot", None) or "").strip()
+ conflicts = [flag for attr, flag in _BOT_RUN_CONFLICTS if getattr(args, attr, None)]
+ if conflicts:
+ raise TaskCliError(
+ f"--bot cannot be combined with {', '.join(conflicts)}",
+ code="bot_run_conflict",
+ hint=(
+ "A Bot has one permanent Session on its own model. Message it with --bot alone; "
+ "start a fresh worker of an Agent with --agent instead."
+ ),
+ help_command="vibe agent run --help",
+ )
+ try:
+ with BotService() as service:
+ bot = (
+ service.ensure_main_bot()
+ if handle == MAIN_BOT_HANDLE
+ else service.get_bot(handle)
+ )
+ if bot.handle != MAIN_BOT_HANDLE:
+ service.ensure_home(bot)
+ except BotError as exc:
+ raise TaskCliError(
+ str(exc),
+ code=exc.code,
+ hint="List the Bots with `vibe bot list`.",
+ help_command="vibe agent run --help",
+ details={"bot": handle},
+ ) from exc
+ args.session_id = bot.session_id
+ args.queue = True
+
+
def cmd_agent_run(args):
reserved_session_id: Optional[str] = None
try:
+ if (getattr(args, "bot", None) or "").strip():
+ _resolve_bot_run_target(args)
caller_context = caller_context_from_env()
visibility = (getattr(args, "visibility", None) or "background").strip()
run_async = _agent_run_is_async(args)
@@ -17575,7 +17795,7 @@ def build_parser():
"run",
help="Run an Avibe Agent",
description=(
- "Run an Agent turn in a new background Session (--agent), an existing Session "
+ "Run an Agent turn in a new background Session (--agent), an existing Session "
"(--session-id), or a fork. Runs are async: the final result returns to the caller Session."
),
epilog=_agent_run_examples_text(),
@@ -17583,6 +17803,9 @@ def build_parser():
error_help_command="vibe agent run --help",
)
agent_run_parser.add_argument("--agent", metavar="NAME", help="Agent for a new Session (a fork: same backend only)")
+ agent_run_parser.add_argument(
+ "--bot", metavar="BOT", help="Message a Bot's Session"
+ )
agent_run_parser.add_argument(
"--session-id", metavar="ID", help="Join this Session's running turn, or start one if idle"
)
@@ -17598,7 +17821,7 @@ def build_parser():
const="foreground",
help="Make the new Session user-facing",
)
- agent_run_parser.add_argument("--model", help="Model the new Session keeps; see 'vibe agent models <agent>'")
+ agent_run_parser.add_argument("--model", help="Model the new Session keeps ('vibe agent models')")
agent_run_parser.add_argument("--reasoning-effort", metavar="EFFORT", help="Reasoning effort the new Session keeps")
agent_run_parser.add_argument("--cwd", metavar="DIR", help="Working directory for a new, unforked Session")
agent_run_parser.add_argument("--callback-session-id", metavar="ID", help="Send the result to this Session instead")
@@ -17619,6 +17842,88 @@ def build_parser():
agent_message_group.add_argument("--message-file", metavar="PATH", help="Read the message from a UTF-8 file")
_add_json_noop(agent_run_parser)
+ bot_parser = subparsers.add_parser(
+ "bot",
+ help="Manage Bots",
+ description=(
+ "List, create, and manage Bots: standing members with one permanent Session and a directory of "
+ "their own memory. Bots belong to the instance Owner."
+ ),
+ epilog=_bot_examples_text(),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe bot --help",
+ )
+ bot_subparsers = bot_parser.add_subparsers(dest="bot_command", metavar="{list,show,create,set,update,remove}")
+ bot_subparsers.required = True
+ bot_list_parser = bot_subparsers.add_parser("list", help="List Bots, the main Bot first")
+ _add_pagination_args(bot_list_parser, help_command="vibe bot list --help")
+ _add_json_noop(bot_list_parser)
+ bot_show_parser = bot_subparsers.add_parser("show", help="Show one Bot")
+ bot_show_parser.add_argument("handle", help="Bot handle, such as main")
+ _add_json_noop(bot_show_parser)
+
+ def add_avatar_args(parser, *, clear: bool) -> None:
+ parser.add_argument("--emoji", help="Avatar emoji, with --hue")
+ parser.add_argument("--hue", type=int, metavar="0-359", help="Avatar background hue, with --emoji")
+ if clear:
+ parser.add_argument("--clear-avatar", action="store_true", help="Go back to the default avatar")
+
+ bot_create_parser = bot_subparsers.add_parser(
+ "create",
+ help="Create a Vibey Agent and its Bot",
+ description=(
+ "Create a Vibey Agent, named after the handle, and make it a Bot with its Session and directory. "
+ "Without --handle the handle comes from the name. Without --model the Bot follows the main Bot's model."
+ ),
+ error_help_command="vibe bot create --help",
+ )
+ bot_create_parser.add_argument("--name", required=True, help="Display name, in any language")
+ bot_create_parser.add_argument(
+ "--handle", help="Lowercase handle, 2 to 24 letters, digits, or hyphens; frozen once created"
+ )
+ bot_create_parser.add_argument("--role", help="The Bot's role, stored as its Agent's description")
+ bot_create_parser.add_argument("--model", help="Model for the Bot's Agent")
+ bot_create_parser.add_argument("--reasoning-effort", metavar="EFFORT", help="Reasoning effort for the Bot's Agent")
+ add_avatar_args(bot_create_parser, clear=False)
+ _add_json_noop(bot_create_parser)
+
+ bot_set_parser = bot_subparsers.add_parser(
+ "set",
+ help="Make an existing Vibey Agent a Bot",
+ description=(
+ "Make an enabled Vibey Agent a Bot. Its handle is its Agent name; an Agent that was a Bot before "
+ "gets its old handle back, with its Session and directory."
+ ),
+ error_help_command="vibe bot set --help",
+ )
+ bot_set_parser.add_argument("agent", help="Agent name")
+ bot_set_parser.add_argument("--name", required=True, help="Display name, in any language")
+ add_avatar_args(bot_set_parser, clear=False)
+ _add_json_noop(bot_set_parser)
+
+ bot_update_parser = bot_subparsers.add_parser(
+ "update",
+ help="Change a Bot's display name, avatar, or position",
+ description=(
+ "Change a Bot's display name, emoji avatar, or position among the other Bots. Change its role, model, "
+ "or instructions with `vibe agent update`."
+ ),
+ error_help_command="vibe bot update --help",
+ )
+ bot_update_parser.add_argument("handle", help="Bot handle")
+ bot_update_parser.add_argument("--name", help="New display name")
+ add_avatar_args(bot_update_parser, clear=True)
+ bot_update_parser.add_argument("--position", type=int, metavar="N", help="Position among the other Bots, from 1")
+ _add_json_noop(bot_update_parser)
+
+ bot_remove_parser = bot_subparsers.add_parser(
+ "remove",
+ help="Remove the Bot role, keeping the Agent, Session, and directory",
+ error_help_command="vibe bot remove --help",
+ )
+ bot_remove_parser.add_argument("handle", help="Bot handle")
+ _add_json_noop(bot_remove_parser)
+
runs_parser = subparsers.add_parser(
"runs",
help="Inspect and manage Agent run records",
@@ -19132,6 +19437,13 @@ _CLI_COMMAND_FLOORS: dict[tuple[str, ...], Optional[str]] = {
("agent", "remove"): "member",
("agent", "import"): "member",
("agent", "default"): "member",
+ # Bots are the instance Owner's (docs/plans/bots.md D1); ``agent run --bot`` asks the same in the Bot service.
+ ("bot", "list"): "owner",
+ ("bot", "show"): "owner",
+ ("bot", "create"): "owner",
+ ("bot", "set"): "owner",
+ ("bot", "update"): "owner",
+ ("bot", "remove"): "owner",
# Harness: one instance-wide Editor floor for reads and ordinary control.
("runs", "list"): "editor",
("runs", "show"): "editor",
@@ -19441,6 +19753,19 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:
if args.agent_command == "run":
sys.exit(cmd_agent_run(args))
parser.error("agent command is required")
+ if args.command == "bot":
+ commands = {
+ "list": cmd_bot_list,
+ "show": cmd_bot_show,
+ "create": cmd_bot_create,
+ "set": cmd_bot_set,
+ "update": cmd_bot_update,
+ "remove": cmd_bot_remove,
+ }
+ command = commands.get(args.bot_command)
+ if command is None:
+ parser.error("bot command is required")
+ sys.exit(command(args))
if args.command == "runs":
if args.runs_command == "list":
sys.exit(cmd_runs_list(args))
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index b1b5d122e..bf21a8f8b 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -359,6 +359,10 @@
"tooLarge": "Attachment '{name}' exceeds the attachment size limit."
},
"agentArchive": {
+ "agent_is_bot": {
+ "message": "Agent `{agent}` is a Bot and cannot be deleted.",
+ "hint": "Remove it from Bots first; its conversation and memory are kept."
+ },
"agent_builtin": {
"message": "Agent `{agent}` is built in and cannot be deleted.",
"hint": "Built-in default Agents are created from enabled Backends and cannot be deleted."
@@ -373,6 +377,10 @@
}
},
"agentLifecycle": {
+ "agent_is_bot": {
+ "message": "Agent `{agent}` is a Bot, so it stays enabled and keeps its name.",
+ "hint": "Remove it from Bots first; you can still change its model, effort, description, and system prompt."
+ },
"agent_always_enabled": {
"message": "Agent `{agent}` is built in and always enabled.",
"hint": "You can still change its model, effort, and system prompt."
@@ -386,6 +394,26 @@
"hint": "Repair or remove the malformed task or watch metadata, then try again."
}
},
+ "bots": {
+ "sessionProtected": "A Bot's conversation is managed by Avibe: it cannot be archived, and its title follows the Bot's name.",
+ "bot_not_found": "Bot `@{handle}` was not found.",
+ "bot_handle_invalid": "`{handle}` is not a valid handle. Use 2 to 24 lowercase letters, digits, or hyphens, starting with a letter and not ending with a hyphen.",
+ "bot_handle_reserved": "The handle `{handle}` is reserved for a built-in Bot.",
+ "bot_handle_taken": "The handle `{handle}` is already taken.",
+ "bot_display_name_required": "Give the Bot a name.",
+ "bot_display_name_too_long": "A Bot's name can have at most 64 characters.",
+ "bot_avatar_invalid": "The avatar is not valid. Choose one emoji with a color, or upload an image.",
+ "bot_avatar_too_large": "The avatar image is larger than 10 MB.",
+ "bot_avatar_missing": "This Bot has no uploaded avatar.",
+ "bot_agent_not_found": "That Agent was not found.",
+ "bot_agent_backend": "Only Vibey Agents can be set as Bots.",
+ "bot_agent_disabled": "Enable the Agent before setting it as a Bot.",
+ "bot_agent_is_bot": "This Agent is already a Bot.",
+ "bot_main_not_removable": "The main Bot cannot be removed.",
+ "bot_main_position": "The main Bot always comes first.",
+ "bot_position_invalid": "A Bot's position is a whole number from 1.",
+ "bot_main_unavailable": "The main Bot is not available right now."
+ },
"agentNameValidation": {
"agent_name_reserved": {
"message": "Agent names starting with `_` are reserved for Avibe.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 9eab56a26..ecd6663f0 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -359,6 +359,10 @@
"tooLarge": "附件“{name}”超过附件大小限制。"
},
"agentArchive": {
+ "agent_is_bot": {
+ "message": "Agent `{agent}` 是伙伴,无法删除。",
+ "hint": "请先将它移出伙伴;它的对话与记忆会保留。"
+ },
"agent_builtin": {
"message": "Agent `{agent}` 是内置 Agent,无法删除。",
"hint": "内置默认 Agent 由已启用的 Backend 创建,无法删除。"
@@ -373,6 +377,10 @@
}
},
"agentLifecycle": {
+ "agent_is_bot": {
+ "message": "Agent `{agent}` 是伙伴,因此保持启用并保留名称。",
+ "hint": "请先将它移出伙伴;仍可调整它的模型、Effort、描述与系统提示词。"
+ },
"agent_always_enabled": {
"message": "Agent `{agent}` 是内置 Agent,始终启用。",
"hint": "仍可调整它的模型、Effort 与系统提示词。"
@@ -386,6 +394,26 @@
"hint": "请修复或删除元数据异常的任务或监控,然后重试。"
}
},
+ "bots": {
+ "sessionProtected": "伙伴的对话由 Avibe 管理:不能归档,标题跟随伙伴的名字。",
+ "bot_not_found": "找不到伙伴 `@{handle}`。",
+ "bot_handle_invalid": "`{handle}` 不是有效的标识。请使用 2 到 24 个小写字母、数字或连字符,以字母开头,且不以连字符结尾。",
+ "bot_handle_reserved": "标识 `{handle}` 已保留给内置伙伴。",
+ "bot_handle_taken": "标识 `{handle}` 已被占用。",
+ "bot_display_name_required": "请给伙伴起个名字。",
+ "bot_display_name_too_long": "伙伴的名字最多 64 个字符。",
+ "bot_avatar_invalid": "头像无效。请选择一个 emoji 和颜色,或上传一张图片。",
+ "bot_avatar_too_large": "头像图片超过 10 MB。",
+ "bot_avatar_missing": "这个伙伴没有上传头像。",
+ "bot_agent_not_found": "找不到这个 Agent。",
+ "bot_agent_backend": "只有 Vibey Agent 可以设为伙伴。",
+ "bot_agent_disabled": "请先启用这个 Agent,再设为伙伴。",
+ "bot_agent_is_bot": "这个 Agent 已经是伙伴。",
+ "bot_main_not_removable": "主伙伴不能移出。",
+ "bot_main_position": "主伙伴始终排在第一位。",
+ "bot_position_invalid": "伙伴的位置是从 1 开始的整数。",
+ "bot_main_unavailable": "主伙伴暂时不可用。"
+ },
"agentNameValidation": {
"agent_name_reserved": {
"message": "Agent 名称不能以下划线 `_` 开头;该命名空间由 Avibe 保留。",
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index fa3f3949e..61998eae9 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -857,6 +857,37 @@ async def test_backend_auth(
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+async def propose_bot_handle(
+ display_name: str,
+ role: str = "",
+ *,
+ socket_path: Optional[Path] = None,
+ timeout: float = 6.0,
+) -> Optional[str]:
+ """Ask the controller for the main Bot's model's handle proposal (``core.bot_handles``); None without one."""
+
+ endpoint = await _resolve_endpoint_async(socket_path)
+ transport = _async_transport(endpoint)
+ try:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url=endpoint.base_url,
+ headers=endpoint.headers,
+ timeout=httpx.Timeout(timeout, connect=2.0),
+ ) as client:
+ resp = await client.post(
+ "/internal/bots/handle-suggestion", json={"display_name": display_name, "role": role}
+ )
+ _validate_response(resp, endpoint)
+ except _SOCKET_CONNECT_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ except httpx.TimeoutException as exc:
+ raise InternalServerTimeout(str(exc)) from exc
+ body = resp.json() if resp.content else {}
+ handle = body.get("handle") if isinstance(body, dict) and resp.status_code == 200 else None
+ return handle if isinstance(handle, str) and handle else None
+
+
async def notify_vault_request_created(
request_payload: dict[str, Any],
*,
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 4f1d37be0..ac524321b 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -9158,6 +9158,13 @@ def _accessible_project_scope_ids_for_context(conn, context) -> list[str] | None
)
+def _hidden_bot_session_ids(conn, context) -> list[str]:
+ """Bot Sessions this reader may not see: all of them for a non-Owner, a removed Bot's for the Owner."""
+ from core.bots import hidden_bot_session_ids
+
+ return hidden_bot_session_ids(conn, context)
+
+
def _request_accessible_project_scope_ids(conn) -> list[str] | None:
return _accessible_project_scope_ids_for_context(
conn,
@@ -10071,40 +10078,34 @@ def desktop_mini_session_ensure():
@app.route("/api/sessions/main", methods=["GET"])
def sessions_main():
- """Return the caller's stable built-in main session, creating it on first use."""
+ """Return the main Bot's ``ses_main``, creating it on first use (``docs/plans/bots.md`` D9)."""
+ from core.bots import BotError, BotService
from core.services import sessions as workbench_sessions_service
- from core.vibe_agents import VibeAgentAccessError, VibeAgentStore
+ from core.vibe_agents import VibeAgentAccessError
from vibe.authorization import InstanceAuthorizationError
from storage.workbench_sessions_service import (
+ MAIN_SESSION_ID,
MainSessionArchivedError,
MainSessionInvariantError,
- ensure_main_session,
)
- store = VibeAgentStore()
- try:
- vibey = store.get_builtin_default_agent_for_backend("vibey")
- finally:
- store.close()
lang = _request_ui_language()
- if vibey is None:
- return _coded_error_response("builtin_agent_unavailable", t("desktopMini.builtinAgentUnavailable", lang), 409)
-
authorization_context = getattr(g, "authorization_context", None)
- engine = _projects_engine()
try:
- with engine.begin() as conn:
- session = ensure_main_session(
- conn,
- agent_name=vibey.name,
- title=t("desktopMini.sessionTitle", lang),
- authorization_context=authorization_context,
+ with BotService() as service:
+ service.ensure_main_bot(authorization_context=authorization_context)
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ session = workbench_sessions_service.get_session(
+ conn, MAIN_SESSION_ID, authorization_context=authorization_context
)
except InstanceAuthorizationError:
return jsonify(
{"ok": False, "error": "instance_access_forbidden", "required_role": "owner"}
), 403
+ except BotError:
+ return _coded_error_response("builtin_agent_unavailable", t("desktopMini.builtinAgentUnavailable", lang), 409)
except (VibeAgentAccessError, workbench_sessions_service.ProjectAccessDeniedError):
return _coded_error_response("project_access_denied", t("error.projectAccessDenied", lang), 403)
except MainSessionArchivedError:
@@ -10129,6 +10130,211 @@ def sessions_main():
)
+# --- Bots (docs/plans/bots.md "Web API"): every route is the instance Owner's. ---
+
+
+def _bot_error_response(exc: Exception):
+ from core.bots import BotError
+ from vibe.authorization import InstanceAuthorizationError
+
+ if isinstance(exc, InstanceAuthorizationError):
+ return jsonify({"ok": False, "error": "instance_access_forbidden", "required_role": "owner"}), 403
+ if isinstance(exc, BotError):
+ lang = _request_ui_language()
+ key = f"error.bots.{exc.code}"
+ message = t(key, lang, handle=exc.details.get("handle", ""))
+ return _coded_error_response(exc.code, str(exc) if message == key else message, exc.status, details=exc.details)
+ if isinstance(exc, PermissionError):
+ return jsonify({"ok": False, "error": "instance_access_forbidden", "required_role": "owner"}), 403
+ raise exc
+
+
+def _bot_owner_context():
+ from vibe.authorization import require_instance_role
+
+ return require_instance_role(getattr(g, "authorization_context", None), "owner")
+
+
+def _publish_bots_changed(handle: str | None = None) -> None:
+ """Tell the Owner's open Workbench to refetch ``GET /api/bots``; an unlisted event stays Owner-only."""
+ from vibe.sse_broker import broker
+
+ broker.publish("bots.changed", {"handle": handle} if handle else {})
+
+
[email protected]("/api/bots", methods=["GET"])
+def bots_list():
+ from core.bots import BotService
+
+ try:
+ context = _bot_owner_context()
+ with BotService() as service:
+ service.ensure_main_bot(authorization_context=context)
+ bots = service.list_bots(authorization_context=context)
+ except Exception as exc:
+ return _bot_error_response(exc)
+ return jsonify({"ok": True, "bots": [bot.to_payload() for bot in bots]})
+
+
[email protected]("/api/bots", methods=["POST"])
+def bots_create():
+ from core.bots import BotService
+
+ payload = request.json or {}
+ try:
+ context = _bot_owner_context()
+ with BotService() as service:
+ bot = service.create_bot(
+ display_name=payload.get("display_name"),
+ handle=payload.get("handle"),
+ role=payload.get("role"),
+ avatar=payload.get("avatar"),
+ model=payload.get("model"),
+ reasoning_effort=payload.get("reasoning_effort"),
+ authorization_context=context,
+ )
+ except Exception as exc:
+ return _bot_error_response(exc)
+ _publish_bots_changed(bot.handle)
+ return jsonify({"ok": True, "bot": bot.to_payload()}), 201
+
+
[email protected]("/api/bots/set", methods=["POST"])
+def bots_set():
+ from core.bots import BotService
+
+ payload = request.json or {}
+ try:
+ context = _bot_owner_context()
+ with BotService() as service:
+ bot = service.set_bot(
+ str(payload.get("agent_name") or ""),
+ display_name=payload.get("display_name"),
+ avatar=payload.get("avatar"),
+ authorization_context=context,
+ )
+ except Exception as exc:
+ return _bot_error_response(exc)
+ _publish_bots_changed(bot.handle)
+ return jsonify({"ok": True, "bot": bot.to_payload()})
+
+
[email protected]("/api/bots/handle-suggestion", methods=["POST"])
+async def bots_handle_suggestion():
+ """A free handle for a new Bot and where it came from: ``model`` or ``transliteration`` (D2)."""
+
+ from core.bot_handles import MODEL_BUDGET_SECONDS, needs_model, suggest_handle
+ from core.bots import BotError
+ from vibe import internal_client
+
+ payload = request.json or {}
+ display_name = " ".join(str(payload.get("display_name") or "").split())
+ role = str(payload.get("role") or "")
+ try:
+ _bot_owner_context()
+ if not display_name:
+ raise BotError("bot_display_name_required", "A Bot needs a display name")
+ except Exception as exc:
+ return _bot_error_response(exc)
+ proposal = None
+ if needs_model(display_name):
+ try:
+ proposal = await asyncio.wait_for(
+ internal_client.propose_bot_handle(display_name, role, timeout=MODEL_BUDGET_SECONDS + 1),
+ timeout=MODEL_BUDGET_SECONDS + 1,
+ )
+ except Exception:
+ # No controller, no route, or no answer in time: the handle comes from transliteration.
+ proposal = None
+
+ def suggest() -> tuple[str, str]:
+ with _projects_engine().connect() as conn:
+ return suggest_handle(conn, display_name=display_name, proposal=proposal)
+
+ handle, source = await asyncio.to_thread(suggest)
+ return jsonify({"ok": True, "handle": handle, "source": source})
+
+
[email protected]("/api/bots/<handle>", methods=["PATCH"])
+def bots_update(handle):
+ from core.bots import BotService
+
+ payload = request.json or {}
+ fields = {key: payload[key] for key in ("display_name", "avatar", "position") if key in payload}
+ unknown = sorted(set(payload) - {"display_name", "avatar", "position"})
+ try:
+ context = _bot_owner_context()
+ if unknown or not fields:
+ from core.bots import BotError
+
+ raise BotError("bot_update_invalid", "Change the display name, the emoji avatar, or the position")
+ with BotService() as service:
+ bot = service.update_bot(handle, authorization_context=context, **fields)
+ except Exception as exc:
+ return _bot_error_response(exc)
+ _publish_bots_changed(bot.handle)
+ return jsonify({"ok": True, "bot": bot.to_payload()})
+
+
[email protected]("/api/bots/<handle>", methods=["DELETE"])
+def bots_remove(handle):
+ from core.bots import BotService
+
+ try:
+ context = _bot_owner_context()
+ with BotService() as service:
+ bot = service.remove_bot(handle, authorization_context=context)
+ except Exception as exc:
+ return _bot_error_response(exc)
+ _publish_bots_changed(bot.handle)
+ return jsonify({"ok": True, "removed": bot.handle, "agent_name": bot.agent.name, "session_id": bot.session_id})
+
+
[email protected]("/api/bots/{handle}/avatar", include_in_schema=False)
+async def bots_avatar_upload(handle: str, starlette_request: FastAPIRequest):
+ """Store an uploaded image as the Bot's ``avatar.png``: the request body is the image itself."""
+
+ async def handler():
+ from core.bots import AVATAR_MAX_UPLOAD_BYTES, BotError, BotService
+
+ try:
+ context = _bot_owner_context()
+ length = starlette_request.headers.get("content-length")
+ if length is not None and length.isdigit() and int(length) > AVATAR_MAX_UPLOAD_BYTES:
+ raise BotError("bot_avatar_too_large", "The avatar upload is larger than 10 MB", status=413)
+ data = bytearray()
+ async for chunk in starlette_request.stream():
+ data.extend(chunk)
+ if len(data) > AVATAR_MAX_UPLOAD_BYTES:
+ raise BotError("bot_avatar_too_large", "The avatar upload is larger than 10 MB", status=413)
+
+ def store():
+ with BotService() as service:
+ return service.set_avatar_image(handle, bytes(data), authorization_context=context)
+
+ bot = await asyncio.to_thread(store)
+ except Exception as exc:
+ return _bot_error_response(exc)
+ _publish_bots_changed(bot.handle)
+ return jsonify({"ok": True, "bot": bot.to_payload()})
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
[email protected]("/api/bots/<handle>/avatar", methods=["GET"])
+def bots_avatar(handle):
+ from core.bots import BotService
+
+ try:
+ context = _bot_owner_context()
+ with BotService() as service:
+ path = service.avatar_path(handle, authorization_context=context)
+ except Exception as exc:
+ return _bot_error_response(exc)
+ response = send_file(path, mimetype="image/png")
+ response.headers["Cache-Control"] = "private, max-age=31536000, immutable"
+ return response
+
def _session_fork_error_response(err: Exception):
"""Map a ``SessionForkError`` to its machine code, in the STRUCTURED body.
@@ -10545,7 +10751,18 @@ def _session_archived_response():
#: The archive/edit refusal's copy: the row exists to receive notices and cannot be
#: torn down or re-labelled. Used by the DELETE and PATCH guards.
RESERVED_SESSION_PROTECTED_I18N_KEY = "harness.notice.workspaceSessionProtected"
-MAIN_SESSION_PROTECTED_I18N_KEY = "desktopMini.mainSessionProtected"
+# A Bot's Session, ``ses_main`` included (``docs/plans/bots.md`` D5): no archive, no rename.
+MAIN_SESSION_PROTECTED_I18N_KEY = "error.bots.sessionProtected"
+
+
+def _is_bot_session(session_id: str) -> bool:
+ """Whether a Bot owns ``session_id``; only ids in the Bots' namespace read the catalog."""
+ from storage.agent_session_rows import is_bot_session, is_bot_session_id
+
+ if not is_bot_session_id(session_id):
+ return False
+ with _projects_engine().connect() as conn:
+ return is_bot_session(conn, session_id)
#: The send refusal's copy. A SEPARATE key on purpose: "cannot be archived or modified"
#: is not an answer to "why did my message not send", and the composer's own inert-state
#: notice has to say the same thing this body says.
@@ -10758,7 +10975,7 @@ def _publish_session_update_activity(
@app.route("/api/sessions/<session_id>", methods=["PATCH"])
async def sessions_update(session_id: str):
from core.services import sessions as workbench_sessions_service
- from storage.workbench_sessions_service import MAIN_SESSION_ID, MAIN_SESSION_UPDATABLE_FIELDS
+ from storage.workbench_sessions_service import BOT_SESSION_UPDATABLE_FIELDS
from vibe import internal_client
from vibe.sse_broker import broker
@@ -10782,9 +10999,7 @@ async def sessions_update(session_id: str):
}
if not updatable:
return jsonify({"error": "no updatable fields supplied"}), 400
- if str(session_id) == MAIN_SESSION_ID and not set(updatable).issubset(
- MAIN_SESSION_UPDATABLE_FIELDS
- ):
+ if not set(updatable).issubset(BOT_SESSION_UPDATABLE_FIELDS) and _is_bot_session(session_id):
return _reserved_session_response(
MAIN_SESSION_PROTECTED_I18N_KEY,
code="reserved_session",
@@ -10883,7 +11098,7 @@ async def sessions_update(session_id: str):
# route's 403 + localized copy so the two guards read as one contract.
return _reserved_session_response(
MAIN_SESSION_PROTECTED_I18N_KEY
- if str(session_id) == MAIN_SESSION_ID
+ if _is_bot_session(session_id)
else RESERVED_SESSION_PROTECTED_I18N_KEY,
code=getattr(err, "code", "reserved_session"),
)
@@ -11073,7 +11288,6 @@ async def sessions_archive(session_id: str):
from core.show_pages import ShowPageError, require_show_page_management
from sqlalchemy import select
from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
- from storage.workbench_sessions_service import MAIN_SESSION_ID
from storage.models import show_pages
from vibe.sse_broker import broker
@@ -11083,7 +11297,7 @@ async def sessions_archive(session_id: str):
RESERVED_SESSION_PROTECTED_I18N_KEY,
code="reserved_session",
)
- if str(session_id) == MAIN_SESSION_ID:
+ if _is_bot_session(session_id):
return _reserved_session_response(
MAIN_SESSION_PROTECTED_I18N_KEY,
code="reserved_session",
@@ -11125,7 +11339,7 @@ async def sessions_archive(session_id: str):
if code == "reserved_session":
return _reserved_session_response(
MAIN_SESSION_PROTECTED_I18N_KEY
- if str(session_id) == MAIN_SESSION_ID
+ if _is_bot_session(session_id)
else RESERVED_SESSION_PROTECTED_I18N_KEY,
code=code,
)
@@ -11156,7 +11370,7 @@ async def sessions_archive(session_id: str):
if status_code == 403 and body.get("error") == "reserved_session":
return _reserved_session_response(
MAIN_SESSION_PROTECTED_I18N_KEY
- if str(session_id) == MAIN_SESSION_ID
+ if _is_bot_session(session_id)
else RESERVED_SESSION_PROTECTED_I18N_KEY,
code="reserved_session",
)
@@ -11338,6 +11552,7 @@ def search_messages_list():
limit=limit,
include_archived=include_archived,
scope_ids=_request_accessible_project_scope_ids(conn),
+ hidden_session_ids=_hidden_bot_session_ids(conn, getattr(g, "authorization_context", None)),
)
return jsonify(result)
@@ -13011,15 +13226,18 @@ def sessions_mark_read(session_id: str):
conn, session_id, until_message_id=until_message_id
)
accessible_scope_ids = _request_accessible_project_scope_ids(conn)
+ hidden_session_ids = _hidden_bot_session_ids(conn, authorization_context)
unread_counts = messages_service.unread_counts(
conn,
platform="avibe",
scope_ids=accessible_scope_ids,
+ hidden_session_ids=hidden_session_ids,
)
unread_by_session = messages_service.unread_counts_by_session(
conn,
platform="avibe",
scope_ids=accessible_scope_ids,
+ hidden_session_ids=hidden_session_ids,
)
except LookupError as err:
return jsonify({"error": str(err)}), 404
@@ -13262,6 +13480,12 @@ def _workbench_event_visible_to_context(context, event_type: str, payload: str)
# ACL. Project ACL gates page creation/editing, while §3.2 instance
# admission gates Viewer reads and live event delivery.
return context.has_role("viewer")
+ if not context.is_instance_owner:
+ # Bots are the Owner's (``docs/plans/bots.md`` D1): no other member hears about a Bot's Session.
+ data = _workbench_event_data(payload)
+ session_id = data.get("session_id") if data is not None else None
+ if isinstance(session_id, str) and _is_bot_session(session_id):
+ return False
if _has_runtime_management_access(context):
return True
if event_type in {"authorization.changed", "workbench.events.bridge.status"}:
@@ -13381,15 +13605,18 @@ def _workbench_event_payload_for_context(context, event_type: str, payload: str)
engine = _projects_engine()
with engine.connect() as conn:
scope_ids = _accessible_project_scope_ids_for_context(conn, context)
+ hidden_session_ids = _hidden_bot_session_ids(conn, context)
unread_counts = messages_service.unread_counts(
conn,
platform="avibe",
scope_ids=scope_ids,
+ hidden_session_ids=hidden_session_ids,
)
unread_by_session = messages_service.unread_counts_by_session(
conn,
platform="avibe",
scope_ids=scope_ids,
+ hidden_session_ids=hidden_session_ids,
)
return json.dumps(
{
@@ -13605,6 +13832,8 @@ def inbox_list():
engine = _projects_engine()
with engine.connect() as conn:
accessible_scope_ids = _request_accessible_project_scope_ids(conn)
+ # Bot Sessions belong in the feed (``docs/plans/bots.md`` D5), the Owner's only.
+ hidden_session_ids = _hidden_bot_session_ids(conn, getattr(g, "authorization_context", None))
result = messages_service.list_inbox_sessions(
conn,
platform=scope_filter,
@@ -13613,6 +13842,7 @@ def inbox_list():
before=before,
only_session=only_session,
scope_ids=accessible_scope_ids,
+ hidden_session_ids=hidden_session_ids,
)
# Pagination-independent unread map for the sidebar badges (a session
# with unread may sit past the first inbox page) + header totals.
@@ -13620,6 +13850,7 @@ def inbox_list():
conn,
platform=scope_filter,
scope_ids=accessible_scope_ids,
+ hidden_session_ids=hidden_session_ids,
)
result["unread_by_session"] = per_session
result["unread_total"] = sum(per_session.values())