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.

fix(prompt): centralize system prompt injection

cyh658ad2743127
diff --git a/config/v2_config.py b/config/v2_config.py
index a8679614c..e2225707f 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -269,7 +269,7 @@ class V2Config:
ack_mode: str = "typing"
show_duration: bool = False # Show task duration in result messages
include_user_info: bool = True # Prepend user identity to agent messages
- reply_enhancements: bool = True # Enable file sending & quick-reply buttons
+ reply_enhancements: bool = True # Enable quick-reply buttons
language: str = "en" # Global language setting (see vibe/i18n)
@classmethod
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index f81d252ac..c26985361 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -253,8 +253,6 @@ class MessageHandler(BaseHandler):
# Prepend user identity when include_user_info is enabled
if is_human and self.config.include_user_info:
message = await self._prepend_user_info(context, message)
- if is_human:
- message = self._prepend_agent_identity(context, message)
message = self._append_attachment_errors(message, attachment_errors)
@@ -324,14 +322,6 @@ class MessageHandler(BaseHandler):
uid = self._sanitize_identity(context.user_id)
return f"[{name}<{uid}>] {message}"
- def _prepend_agent_identity(self, context: MessageContext, message: str) -> str:
- """Add platform identity context without rewriting the user's message."""
- payload = context.platform_specific or {}
- bot_mention = payload.get("bot_mention")
- if isinstance(bot_mention, str) and bot_mention.strip():
- return f"[Agent Identity] Slack bot mention: {bot_mention.strip()}\n{message}"
- return message
-
@staticmethod
def _get_control_message(context: MessageContext, message: str) -> str:
payload = context.platform_specific or {}
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index e19f64048..1f98560d4 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -516,33 +516,30 @@ class SessionHandler(BaseHandler):
effective_effort = normalize_claude_reasoning_effort(effective_model, explicit_effort)
# Determine final system prompt: agent prompt takes precedence over config.
- # When reply_enhancements is enabled and no explicit prompt is set,
- # use the claude_code preset with our enhancements appended so the
- # built-in tools/instructions remain intact.
+ # Always append Vibe Remote system prompt injection so transport
+ # capabilities remain available; reply_enhancements only controls
+ # quick-reply button instructions.
base_prompt = agent_system_prompt or self.config.claude.system_prompt
- reply_enhancements_on = getattr(self.config, "reply_enhancements", True)
+ quick_replies_on = getattr(self.config, "reply_enhancements", True)
- if reply_enhancements_on:
- from core.reply_enhancer import build_reply_enhancements_prompt
+ from core.system_prompt_injection import build_system_prompt_injection
- platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platform
+ platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platform
- reply_prompt = build_reply_enhancements_prompt(
- include_quick_replies=platform != "wechat",
- context=context,
- fallback_platform=platform,
- )
+ system_prompt_injection = build_system_prompt_injection(
+ include_quick_replies=quick_replies_on and platform != "wechat",
+ context=context,
+ fallback_platform=platform,
+ )
- if base_prompt:
- final_system_prompt = f"{base_prompt}\n\n{reply_prompt}"
- else:
- final_system_prompt = {
- "type": "preset",
- "preset": "claude_code",
- "append": reply_prompt,
- }
+ if base_prompt:
+ final_system_prompt = f"{base_prompt}\n\n{system_prompt_injection}"
else:
- final_system_prompt = base_prompt
+ final_system_prompt = {
+ "type": "preset",
+ "preset": "claude_code",
+ "append": system_prompt_injection,
+ }
# Create extra_args for CLI passthrough (fallback for model)
extra_args: Dict[str, str | None] = {}
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 98e903d53..2199a848a 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -337,14 +337,10 @@ class ConsolidatedMessageDispatcher:
scheduled_anchor_message_id: Optional[str] = None
delivered_as_attachment = False
- # --- Reply enhancements: extract file links & quick-reply buttons ---
- reply_enhancements_on = getattr(self.controller.config, "reply_enhancements", True)
- if reply_enhancements_on:
- enhanced = process_reply(text)
- display_text = enhanced.text if enhanced.text.strip() else text
- else:
- enhanced = None
- display_text = text
+ # Extract file links and optional quick-reply buttons.
+ quick_replies_on = getattr(self.controller.config, "reply_enhancements", True)
+ enhanced = process_reply(text, include_quick_replies=quick_replies_on)
+ display_text = enhanced.text if enhanced.text.strip() else text
if self._result_within_limit(context, display_text):
try:
@@ -493,11 +489,7 @@ class ConsolidatedMessageDispatcher:
)
return None
- reply_enhancements_on = getattr(self.controller.config, "reply_enhancements", True)
- if reply_enhancements_on:
- chunk = strip_file_links(text).strip()
- else:
- chunk = text.strip()
+ chunk = strip_file_links(text).strip()
if not chunk:
return None
diff --git a/core/reply_enhancer.py b/core/reply_enhancer.py
index 00463c0bd..d983762db 100644
--- a/core/reply_enhancer.py
+++ b/core/reply_enhancer.py
@@ -1,4 +1,4 @@
-"""Reply enhancer: parse agent responses for file attachments and quick-reply buttons.
+"""Reply parser for silent blocks, file attachments, and quick-reply buttons.
Extracts special syntaxes from agent reply text:
@@ -20,12 +20,9 @@ import ntpath
import os
import re
from dataclasses import dataclass, field
-from typing import List, Optional, Tuple
+from typing import List, Tuple
from urllib.parse import unquote, urlparse
-from config import paths
-from modules.im import MessageContext
-
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
@@ -91,16 +88,19 @@ _UNTERMINATED_SILENT_RE = re.compile(r"<silent\b[^>]*>.*\Z", re.IGNORECASE | re.
# ---------------------------------------------------------------------------
-def process_reply(text: str) -> EnhancedReply:
+def process_reply(text: str, *, include_quick_replies: bool = True) -> EnhancedReply:
"""Parse *text* and return an ``EnhancedReply``.
The returned ``.text`` has file-link markup converted to plain labels and
- the trailing button block (if any) stripped.
+ the trailing button block stripped when quick replies are enabled.
"""
text = strip_silent_blocks(text)
files = _extract_file_links(text)
text_no_files = _strip_file_links(text) if files else text
- buttons, text_clean = _extract_buttons(text_no_files)
+ if include_quick_replies:
+ buttons, text_clean = _extract_buttons(text_no_files)
+ else:
+ buttons, text_clean = [], text_no_files
return EnhancedReply(text=text_clean.rstrip(), files=files, buttons=buttons)
@@ -189,163 +189,3 @@ def _extract_buttons(text: str) -> Tuple[List[QuickReplyButton], str]:
cleaned = text[: m.start()]
return buttons, cleaned
-
-
-# ---------------------------------------------------------------------------
-# System prompt for injection into agent backends
-# ---------------------------------------------------------------------------
-
-_FILES_PROMPT = """\
-# Vibe Remote
-
-Vibe Remote is a middleware layer that connects AI agents to IM platforms such as Slack, Discord, Telegram, WeChat, and Lark/Feishu. \
-The user is interacting with you through an IM app via Vibe Remote forwarding.
-
-If the user asks you to configure, repair, or operate Vibe Remote itself, read `https://github.com/cyhhao/vibe-remote/raw/master/skills/use-vibe-remote/SKILL.md` before making changes. Use it for configuration file locations, scope rules, routing behavior, scheduled-task operations, and troubleshooting steps.
-
-Vibe Remote provides optional capabilities:
-
-## Silent replies
-If you decide no user-facing response is needed, respond only with a silent block:
-`<silent>reason not shown to the user</silent>`
-
-Rules:
-- Vibe Remote strips all `<silent>...</silent>` blocks before sending messages.
-- If nothing remains after stripping silent blocks, Vibe Remote sends no message.
-- Use this for thread messages where you have received context but should not interrupt.
-
-## 1. Send files
-You can send a local file to the user by using a Markdown link with the `file://` protocol:
-Example: [File 1](file:///tmp/result.pdf)
-Vibe Remote will automatically send the file as an attachment.
-
-### Image syntax
-If you want it sent as an image attachment rather than a regular file, use Markdown image syntax:
-Example: ![Page screenshot](file:///tmp/screenshot.jpg)
-"""
-
-_QUICK_REPLIES_PROMPT = """\
-
-## 2. Quick-reply buttons
-At the very end of the message, add a `---` separator followed by `[button text]` to provide clickable quick replies. Example:
----
-[👌 Continue] | [✅ Submit PR] | [👀 Review first]
-Rules:
-- Infer likely next replies from the conversation context and the user's habits; only add them when they are genuinely helpful
-- Do not add filler unrelated to the user's likely next intent, such as: got it, received, thanks
-- They must appear at the very end of the message, after the `---` separator
-- Wrap each button in `[text]` and separate them with `|`; you may start with emoji to improve clarity
-- Use at most 2-4 buttons, each no longer than 20 characters
-"""
-
-_SCHEDULED_TASKS_PROMPT = """\
-
-## 3. Scheduled tasks, watches, and hooks
-Use `vibe task add` for saved work that should run later on a schedule or at one exact time.
-Use `vibe watch add` for managed background waiters that should keep running until a condition is met and then send a follow-up.
-Use `vibe hook send --session-key ... --prompt ...` for one-shot asynchronous sends without saving a task or watch.
-
-Current conversation targeting:
-- Default session key: `{default_session_key}`
-- Channel-level session key: `{channel_session_key}`
-
-Rules:
-- `session_key` controls the conversation scope that Vibe Remote will continue using.
-- When you do not want to keep the current session and instead want to start or reuse a higher-level session, usually use the higher-level session key. For example, if the default key is `slack::channel::C123::thread::171717.123`, then `slack::channel::C123` creates or reuses the channel-scoped session.
-- `--post-to` changes the delivery target, not the session scope. Use `--post-to channel` when the session should stay thread-scoped but the follow-up message should be posted to the parent channel.
-- Use `--cron "<expr>"` for recurring tasks or `--at "<ISO-8601>"` for one-off stored tasks.
-- Use `vibe watch list`, `vibe watch show`, `vibe watch pause`, `vibe watch resume`, and `vibe watch remove` to manage background work after creation.
-- Prefer `vibe watch add` over ad-hoc `nohup` or shell-detached jobs when the user wants a managed background task.
-- If `--timezone` is omitted, the task uses the local system timezone at creation time.
-- Use `--prompt "..."` or `--prompt-file <path>` for task and hook content. Use `--prefix "..."` on watches for the follow-up instruction that is prepended before waiter stdout; when both exist, Vibe Remote joins them with a blank line.
-- If this is your first time using these commands, read `vibe task add --help`, `vibe watch add --help`, or `vibe hook send --help` before creating anything. The help text and relevant skills explain not just the argument syntax but also runtime effects such as how follow-up messages are built and how tasks or watches are stored and managed.
-"""
-
-
-_USER_PREFERENCES_PROMPT = """\
-
-## 4. User Context and Preferences
-A shared user context and preferences file is available at `{preferences_path}`.
-
-From first principles, serving the user better means thinking proactively about how to make full use of the available context, reduce repetitive communication, and make judgments that better fit the user's habits. For example, the user may currently be receiving your messages through an IM channel, possibly on a mobile device or in a fragmented-attention context.
-
-Use this file proactively when it is helpful, especially when it can help you understand the user's stable habits, preferences, or working style, reduce repeated questions, and choose among multiple reasonable ways to proceed in a way that better fits the user.
-
-You do not need to read it for every simple request; but if consulting it could improve personalization, efficiency, or continuity, prefer checking it early.
-
-You may also update it, usually in the current user's section: `{user_section}`.
-Only record durable, factual, reusable information there.
-Keep entries short, deduplicated, and free of secrets unless the user explicitly asks.
-"""
-
-
-def _build_prompt_session_key(
- context: MessageContext,
- *,
- include_thread: bool,
- fallback_platform: Optional[str] = None,
-) -> str:
- platform_specific = context.platform_specific or {}
- platform = context.platform or platform_specific.get("platform") or fallback_platform or "<platform>"
- is_dm = bool(platform_specific.get("is_dm", False))
- scope_type = "user" if is_dm else "channel"
- scope_id = context.user_id if is_dm else context.channel_id
- base = f"{platform}::{scope_type}::{scope_id}"
- if include_thread and context.thread_id:
- return f"{base}::thread::{context.thread_id}"
- return base
-
-
-def _build_scheduled_tasks_prompt(context: MessageContext, *, fallback_platform: Optional[str] = None) -> str:
- default_key = _build_prompt_session_key(
- context,
- include_thread=True,
- fallback_platform=fallback_platform,
- )
- channel_key = _build_prompt_session_key(
- context,
- include_thread=False,
- fallback_platform=fallback_platform,
- )
- return _SCHEDULED_TASKS_PROMPT.format(
- default_session_key=default_key,
- channel_session_key=channel_key,
- )
-
-
-def _build_user_preferences_prompt(
- context: Optional[MessageContext],
- *,
- fallback_platform: Optional[str] = None,
-) -> str:
- platform = fallback_platform
- user_id = "<user_id>"
- if context is not None:
- platform_specific = context.platform_specific or {}
- platform = context.platform or platform_specific.get("platform") or fallback_platform
- user_id = context.user_id or "<user_id>"
- user_section = f"{platform or '<platform>'}/{user_id}"
- return _USER_PREFERENCES_PROMPT.format(
- preferences_path=f"`{paths.get_user_preferences_path()}`",
- user_section=user_section,
- )
-
-
-def build_reply_enhancements_prompt(
- *,
- include_quick_replies: bool = True,
- context: Optional[MessageContext] = None,
- fallback_platform: Optional[str] = None,
-) -> str:
- """Build the reply-enhancement prompt for the current platform/backend."""
-
- prompt = _FILES_PROMPT
- if include_quick_replies:
- prompt += _QUICK_REPLIES_PROMPT
- if context is not None:
- prompt += _build_scheduled_tasks_prompt(context, fallback_platform=fallback_platform)
- prompt += _build_user_preferences_prompt(context, fallback_platform=fallback_platform)
- return prompt
-
-
-REPLY_ENHANCEMENTS_PROMPT = build_reply_enhancements_prompt()
diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.py
new file mode 100644
index 000000000..1531ae028
--- /dev/null
+++ b/core/system_prompt_injection.py
@@ -0,0 +1,184 @@
+"""System prompt injection helpers for Vibe Remote agent backends."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Optional
+
+from config import paths
+from modules.im import MessageContext
+
+
+_BASE_CAPABILITIES_PROMPT = """\
+# Vibe Remote
+
+Vibe Remote is a middleware layer that connects AI agents to IM platforms such as Slack, Discord, Telegram, WeChat, and Lark/Feishu. \
+The user is interacting with you through an IM app via Vibe Remote forwarding.
+
+If the user asks you to configure, repair, or operate Vibe Remote itself, read `https://github.com/cyhhao/vibe-remote/raw/master/skills/use-vibe-remote/SKILL.md` before making changes. Use it for configuration file locations, scope rules, routing behavior, scheduled-task operations, and troubleshooting steps.
+
+Vibe Remote provides optional capabilities:
+
+## Silent replies
+If you decide no user-facing response is needed, respond only with a silent block:
+`<silent>reason not shown to the user</silent>`
+
+Rules:
+- Vibe Remote strips all `<silent>...</silent>` blocks before sending messages.
+- If nothing remains after stripping silent blocks, Vibe Remote sends no message.
+- Use this for thread messages where you have received context but should not interrupt.
+
+## 1. Send files
+You can send a local file to the user by using a Markdown link with the `file://` protocol:
+Example: [File 1](file:///tmp/result.pdf)
+Vibe Remote will automatically send the file as an attachment.
+
+### Image syntax
+If you want it sent as an image attachment rather than a regular file, use Markdown image syntax:
+Example: ![Page screenshot](file:///tmp/screenshot.jpg)
+"""
+
+
+def _build_codex_generated_images_prompt() -> str:
+ codex_home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex").expanduser().resolve()
+ example_uri = (codex_home / "generated_images" / "thread-id" / "image-file.png").as_uri()
+ return (
+ "\n### Codex-generated images\n"
+ "If you generate an image with Codex, include it in the final reply with Markdown image syntax, "
+ f"using a real file URI under the local Codex generated_images directory, for example: "
+ f"`![generated image]({example_uri})`. "
+ "Replace the example thread id and filename with the actual generated image path. "
+ "Never emit variables, placeholder paths, or sandbox paths like `/mnt/data/...`; "
+ "if you cannot determine the real path, leave the final reply empty.\n"
+ )
+
+
+_QUICK_REPLIES_PROMPT = """\
+
+## 2. Quick-reply buttons
+At the very end of the message, add a `---` separator followed by `[button text]` to provide clickable quick replies. Example:
+---
+[👌 Continue] | [✅ Submit PR] | [👀 Review first]
+Rules:
+- Infer likely next replies from the conversation context and the user's habits; only add them when they are genuinely helpful
+- Do not add filler unrelated to the user's likely next intent, such as: got it, received, thanks
+- They must appear at the very end of the message, after the `---` separator
+- Wrap each button in `[text]` and separate them with `|`; you may start with emoji to improve clarity
+- Use at most 2-4 buttons, each no longer than 20 characters
+"""
+
+_SCHEDULED_TASKS_PROMPT = """\
+
+## 3. Scheduled tasks, watches, and hooks
+Use `vibe task add` for saved work that should run later on a schedule or at one exact time.
+Use `vibe watch add` for managed background waiters that should keep running until a condition is met and then send a follow-up.
+Use `vibe hook send --session-key ... --prompt ...` for one-shot asynchronous sends without saving a task or watch.
+
+Current conversation targeting:
+- Default session key: `{default_session_key}`
+- Channel-level session key: `{channel_session_key}`
+
+Rules:
+- `session_key` controls the conversation scope that Vibe Remote will continue using.
+- When you do not want to keep the current session and instead want to start or reuse a higher-level session, usually use the higher-level session key. For example, if the default key is `slack::channel::C123::thread::171717.123`, then `slack::channel::C123` creates or reuses the channel-scoped session.
+- `--post-to` changes the delivery target, not the session scope. Use `--post-to channel` when the session should stay thread-scoped but the follow-up message should be posted to the parent channel.
+- Use `--cron "<expr>"` for recurring tasks or `--at "<ISO-8601>"` for one-off stored tasks.
+- Use `vibe watch list`, `vibe watch show`, `vibe watch pause`, `vibe watch resume`, and `vibe watch remove` to manage background work after creation.
+- Prefer `vibe watch add` over ad-hoc `nohup` or shell-detached jobs when the user wants a managed background task.
+- If `--timezone` is omitted, the task uses the local system timezone at creation time.
+- Use `--prompt "..."` or `--prompt-file <path>` for task and hook content. Use `--prefix "..."` on watches for the follow-up instruction that is prepended before waiter stdout; when both exist, Vibe Remote joins them with a blank line.
+- If this is your first time using these commands, read `vibe task add --help`, `vibe watch add --help`, or `vibe hook send --help` before creating anything. The help text and relevant skills explain not just the argument syntax but also runtime effects such as how follow-up messages are built and how tasks or watches are stored and managed.
+"""
+
+
+_USER_PREFERENCES_PROMPT = """\
+
+## 4. User Context and Preferences
+A shared user context and preferences file is available at `{preferences_path}`.
+
+From first principles, serving the user better means thinking proactively about how to make full use of the available context, reduce repetitive communication, and make judgments that better fit the user's habits. For example, the user may currently be receiving your messages through an IM channel, possibly on a mobile device or in a fragmented-attention context.
+
+Use this file proactively when it is helpful, especially when it can help you understand the user's stable habits, preferences, or working style, reduce repeated questions, and choose among multiple reasonable ways to proceed in a way that better fits the user.
+
+You do not need to read it for every simple request; but if consulting it could improve personalization, efficiency, or continuity, prefer checking it early.
+
+You may also update it, usually in the current user's section: `{user_section}`.
+Only record durable, factual, reusable information there.
+Keep entries short, deduplicated, and free of secrets unless the user explicitly asks.
+"""
+
+
+def _build_prompt_session_key(
+ context: MessageContext,
+ *,
+ include_thread: bool,
+ fallback_platform: Optional[str] = None,
+) -> str:
+ platform_specific = context.platform_specific or {}
+ platform = context.platform or platform_specific.get("platform") or fallback_platform or "<platform>"
+ is_dm = bool(platform_specific.get("is_dm", False))
+ scope_type = "user" if is_dm else "channel"
+ scope_id = context.user_id if is_dm else context.channel_id
+ base = f"{platform}::{scope_type}::{scope_id}"
+ if include_thread and context.thread_id:
+ return f"{base}::thread::{context.thread_id}"
+ return base
+
+
+def _build_scheduled_tasks_prompt(context: MessageContext, *, fallback_platform: Optional[str] = None) -> str:
+ default_key = _build_prompt_session_key(
+ context,
+ include_thread=True,
+ fallback_platform=fallback_platform,
+ )
+ channel_key = _build_prompt_session_key(
+ context,
+ include_thread=False,
+ fallback_platform=fallback_platform,
+ )
+ return _SCHEDULED_TASKS_PROMPT.format(
+ default_session_key=default_key,
+ channel_session_key=channel_key,
+ )
+
+
+def _build_user_preferences_prompt(
+ context: Optional[MessageContext],
+ *,
+ fallback_platform: Optional[str] = None,
+) -> str:
+ platform = fallback_platform
+ user_id = "<user_id>"
+ if context is not None:
+ platform_specific = context.platform_specific or {}
+ platform = context.platform or platform_specific.get("platform") or fallback_platform
+ user_id = context.user_id or "<user_id>"
+ user_section = f"{platform or '<platform>'}/{user_id}"
+ return _USER_PREFERENCES_PROMPT.format(
+ preferences_path=f"`{paths.get_user_preferences_path()}`",
+ user_section=user_section,
+ )
+
+
+def build_system_prompt_injection(
+ *,
+ include_quick_replies: bool = True,
+ include_codex_generated_images: bool = False,
+ context: Optional[MessageContext] = None,
+ fallback_platform: Optional[str] = None,
+) -> str:
+ """Build Vibe Remote system prompt additions for an agent backend."""
+
+ prompt = _BASE_CAPABILITIES_PROMPT
+ if include_codex_generated_images:
+ prompt += _build_codex_generated_images_prompt()
+ if include_quick_replies:
+ prompt += _QUICK_REPLIES_PROMPT
+ if context is not None:
+ prompt += _build_scheduled_tasks_prompt(context, fallback_platform=fallback_platform)
+ prompt += _build_user_preferences_prompt(context, fallback_platform=fallback_platform)
+ return prompt
+
+
+SYSTEM_PROMPT_INJECTION = build_system_prompt_injection()
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 27b6e9d1c..16dd789db 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import asyncio
import logging
-import os
import time
from pathlib import Path
from typing import Any, Dict, Optional
@@ -18,18 +17,6 @@ from modules.agents.codex.turn_state import CodexTurnRegistry
logger = logging.getLogger(__name__)
-def _codex_generated_image_prompt() -> str:
- codex_home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex").expanduser().resolve()
- example_uri = (codex_home / "generated_images" / "thread-id" / "image-file.png").as_uri()
- return (
- "If you generate an image with Codex, include it in the final reply with Markdown image syntax, "
- f"using a real file URI under the local Codex generated_images directory, for example: "
- f"`![generated image]({example_uri})`. "
- "Replace the example thread id and filename with the actual generated image path. "
- "Never emit variables, placeholder paths, or sandbox paths like `/mnt/data/...`; "
- "if you cannot determine the real path, leave the final reply empty."
- )
-
class CodexAgent(BaseAgent):
"""Codex CLI integration via persistent ``codex app-server`` subprocess.
@@ -624,16 +611,17 @@ class CodexAgent(BaseAgent):
if agent_instructions:
instruction_parts.append(agent_instructions)
- if getattr(self.controller.config, "reply_enhancements", True):
- from core.reply_enhancer import build_reply_enhancements_prompt
+ from core.system_prompt_injection import build_system_prompt_injection
- instruction_parts.append(
- build_reply_enhancements_prompt(
- include_quick_replies=platform != "wechat",
- context=request.context,
- fallback_platform=platform,
- )
+ instruction_parts.append(
+ build_system_prompt_injection(
+ include_quick_replies=getattr(self.controller.config, "reply_enhancements", True)
+ and platform != "wechat",
+ include_codex_generated_images=True,
+ context=request.context,
+ fallback_platform=platform,
)
+ )
return "\n\n".join(part for part in instruction_parts if part) or None
@@ -701,7 +689,7 @@ class CodexAgent(BaseAgent):
items: list[Dict[str, Any]] = []
# Text input
- message = self._build_turn_message(request.message)
+ message = request.message
if request.files:
# Append file info like Claude agent does
file_lines = ["", "[User Attachments]"]
@@ -728,15 +716,6 @@ class CodexAgent(BaseAgent):
return items
- def _build_turn_message(self, message: str) -> str:
- if not message:
- return message
- controller = getattr(self, "controller", None)
- config = getattr(controller, "config", None)
- if not getattr(config, "reply_enhancements", True):
- return message
- return f"{_codex_generated_image_prompt()}\n\n{message}"
-
# ------------------------------------------------------------------
# Callback handlers (wired to transport)
# ------------------------------------------------------------------
diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.py
index e42e1fdc2..f487ea87d 100644
--- a/modules/agents/codex/event_handler.py
+++ b/modules/agents/codex/event_handler.py
@@ -361,8 +361,6 @@ class CodexEventHandler:
snapshot = self._image_snapshots_by_turn.pop(turn_id, None)
if snapshot is None:
return None
- if not self._reply_enhancements_enabled():
- return None
thread_id, before = snapshot
current = self._list_generated_images(thread_id)
@@ -419,11 +417,6 @@ class CodexEventHandler:
codex_home = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
return codex_home / "generated_images" / thread_id
- def _reply_enhancements_enabled(self) -> bool:
- controller = getattr(self._agent, "controller", None)
- config = getattr(controller, "config", None)
- return getattr(config, "reply_enhancements", True)
-
def _extract_thread_id(self, params: dict[str, Any]) -> str:
thread_id = params.get("threadId", "")
if not thread_id:
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 8864bf718..12696f31d 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -236,16 +236,14 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
or self.controller.config.platform
)
- # Inject reply-enhancement instructions via the system field (appended by OpenCode)
- reply_system: Optional[str] = None
- if getattr(self.controller.config, "reply_enhancements", True):
- from core.reply_enhancer import build_reply_enhancements_prompt
-
- reply_system = build_reply_enhancements_prompt(
- include_quick_replies=platform != "wechat",
- context=request.context,
- fallback_platform=platform,
- )
+ from core.system_prompt_injection import build_system_prompt_injection
+
+ system_prompt_injection = build_system_prompt_injection(
+ include_quick_replies=getattr(self.controller.config, "reply_enhancements", True)
+ and platform != "wechat",
+ context=request.context,
+ fallback_platform=platform,
+ )
request_tools = {"question": False} if platform == "wechat" else None
@@ -256,7 +254,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
agent=agent_to_use,
model=model_dict,
reasoning_effort=reasoning_effort,
- system=reply_system,
+ system=system_prompt_injection,
tools=request_tools,
)
await server.mark_run_active(session_id)
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 8f56d6156..07f78b487 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -779,14 +779,13 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
thread_id = await agent._start_thread(transport, request)
self.assertEqual(thread_id, "thread-1")
- transport.send_request.assert_awaited_once_with(
- "thread/start",
- {
- "cwd": "/tmp/work",
- "approvalPolicy": "never",
- "sandbox": "danger-full-access",
- },
- )
+ method, params = transport.send_request.await_args.args
+ self.assertEqual(method, "thread/start")
+ self.assertEqual(params["cwd"], "/tmp/work")
+ self.assertEqual(params["approvalPolicy"], "never")
+ self.assertEqual(params["sandbox"], "danger-full-access")
+ self.assertIn("# Vibe Remote", params["developerInstructions"])
+ self.assertNotIn("## 2. Quick-reply buttons", params["developerInstructions"])
async def test_start_thread_includes_codex_agent_developer_instructions(self):
agent = object.__new__(CodexAgent)
@@ -824,17 +823,16 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
await agent._start_thread(transport, request)
load_subagent.assert_called_once_with("reviewer", project_root=Path("/tmp/work"))
- transport.send_request.assert_awaited_once_with(
- "thread/start",
- {
- "cwd": "/tmp/work",
- "approvalPolicy": "never",
- "sandbox": "danger-full-access",
- "developerInstructions": "Focus on regressions.",
- },
- )
-
- async def test_start_thread_does_not_add_codex_generated_image_prompt_to_thread_instructions(self):
+ method, params = transport.send_request.await_args.args
+ self.assertEqual(method, "thread/start")
+ self.assertEqual(params["cwd"], "/tmp/work")
+ self.assertEqual(params["approvalPolicy"], "never")
+ self.assertEqual(params["sandbox"], "danger-full-access")
+ self.assertIn("Focus on regressions.", params["developerInstructions"])
+ self.assertIn("# Vibe Remote", params["developerInstructions"])
+ self.assertNotIn("## 2. Quick-reply buttons", params["developerInstructions"])
+
+ async def test_start_thread_adds_codex_generated_image_prompt_to_thread_instructions(self):
agent = object.__new__(CodexAgent)
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
agent.settings_manager = SimpleNamespace(get_channel_settings=lambda session_key: None)
@@ -858,10 +856,14 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
)
transport = SimpleNamespace(send_request=AsyncMock(return_value={"thread": {"id": "thread-1"}}))
- await agent._start_thread(transport, request)
+ with patch.dict(os.environ, {"CODEX_HOME": "/Users/test/.codex"}):
+ await agent._start_thread(transport, request)
params = transport.send_request.await_args.args[1]
- self.assertNotIn("If you generate an image with Codex", params["developerInstructions"])
+ self.assertIn("## 1. Send files", params["developerInstructions"])
+ self.assertIn("### Codex-generated images", params["developerInstructions"])
+ self.assertIn("If you generate an image with Codex", params["developerInstructions"])
+ self.assertIn("file:///Users/test/.codex/generated_images/thread-id/image-file.png", params["developerInstructions"])
async def test_resume_thread_refreshes_developer_instructions_without_appending(self):
agent = object.__new__(CodexAgent)
@@ -908,13 +910,14 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
developer_instructions = params["developerInstructions"]
self.assertEqual(developer_instructions.count("Focus on regressions."), 1)
self.assertEqual(developer_instructions.count("Default session key:"), 1)
+ self.assertEqual(developer_instructions.count("If you generate an image with Codex"), 1)
self.assertIn(
"Default session key: `slack::channel::C1::thread::171717.123`",
developer_instructions,
)
self.assertIn("Channel-level session key: `slack::channel::C1`", developer_instructions)
- async def test_resume_thread_sends_explicit_null_when_developer_instructions_are_disabled(self):
+ async def test_resume_thread_keeps_system_prompt_injection_when_quick_replies_are_disabled(self):
agent = object.__new__(CodexAgent)
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=False))
agent.settings_manager = SimpleNamespace(get_channel_settings=lambda session_key: None)
@@ -946,9 +949,11 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
method, params = transport.send_request.await_args.args
self.assertEqual(method, "thread/resume")
self.assertIn("developerInstructions", params)
- self.assertIsNone(params["developerInstructions"])
+ self.assertIn("# Vibe Remote", params["developerInstructions"])
+ self.assertIn("If you generate an image with Codex", params["developerInstructions"])
+ self.assertNotIn("## 2. Quick-reply buttons", params["developerInstructions"])
- def test_build_input_adds_codex_generated_image_prompt_to_each_turn(self):
+ def test_build_input_does_not_add_codex_generated_image_prompt_to_each_turn(self):
agent = object.__new__(CodexAgent)
agent.controller = SimpleNamespace(config=SimpleNamespace(reply_enhancements=True))
request = SimpleNamespace(message="hello", files=None)
@@ -956,13 +961,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
with patch.dict(os.environ, {"CODEX_HOME": "/Users/test/.codex"}):
items = agent._build_input(request)
- self.assertTrue(items[0]["text"].startswith("If you generate an image with Codex"))
- self.assertIn("file:///Users/test/.codex/generated_images/thread-id/image-file.png", items[0]["text"])
- self.assertIn("local Codex generated_images directory", items[0]["text"])
- self.assertIn("Replace the example thread id and filename with the actual", items[0]["text"])
- self.assertIn("Never emit variables, placeholder paths, or sandbox paths like `/mnt/data/...`", items[0]["text"])
- self.assertIn("leave the final reply empty", items[0]["text"])
- self.assertTrue(items[0]["text"].endswith("hello"))
+ self.assertEqual(items, [{"type": "text", "text": "hello"}])
async def test_start_turn_uses_sandbox_policy_object(self):
agent = object.__new__(CodexAgent)
diff --git a/tests/test_codex_event_handler.py b/tests/test_codex_event_handler.py
index 2c7564a07..347a9963e 100644
--- a/tests/test_codex_event_handler.py
+++ b/tests/test_codex_event_handler.py
@@ -488,7 +488,7 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):
assert agent.emit_result_message.await_args.args[1] is None
assert handler._image_snapshots_by_turn == {}
- async def test_generated_image_fallback_respects_reply_enhancements_setting(self):
+ async def test_generated_image_fallback_ignores_quick_reply_button_setting(self):
agent = _StubAgent()
agent.controller.config.reply_enhancements = False
handler = CodexEventHandler(agent)
@@ -512,7 +512,8 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):
)
agent.emit_result_message.assert_awaited_once()
- assert agent.emit_result_message.await_args.args[1] is None
+ result = agent.emit_result_message.await_args.args[1]
+ assert "![generated image](" in result
def test_generated_images_dir_rejects_dot_segment_thread_ids(self):
agent = _StubAgent()
diff --git a/tests/test_message_handler_attachments.py b/tests/test_message_handler_attachments.py
index 7ab0f09e0..95ee8c4a5 100644
--- a/tests/test_message_handler_attachments.py
+++ b/tests/test_message_handler_attachments.py
@@ -249,21 +249,5 @@ class MessageHandlerAttachmentTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("Download failed with HTTP 403", message)
self.assertNotIn("/.vibe_remote/attachments/", message)
- def test_prepend_agent_identity_keeps_original_message_text(self):
- handler = MessageHandler(_StubController(_StubIMClient()))
- context = MessageContext(
- user_id="U1",
- channel_id="C1",
- platform_specific={"bot_mention": "<@U_BOT>"},
- )
-
- message = handler._prepend_agent_identity(context, "please <@U_BOT> help <@U_OTHER>")
-
- self.assertEqual(
- message,
- "[Agent Identity] Slack bot mention: <@U_BOT>\nplease <@U_BOT> help <@U_OTHER>",
- )
-
-
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index 8032b5330..e499d96d5 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -421,7 +421,7 @@ class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
_, request = controller.agent_service.requests[0]
self.assertEqual(request.subagent_name, "reviewer")
self.assertEqual(request.subagent_key, "reviewer")
- self.assertEqual(request.message, "[Agent Identity] Slack bot mention: <@U_BOT>\ncheck this")
+ self.assertEqual(request.message, "check this")
self.assertEqual(controller.im_client.reactions, [("C1", "m1", "👀"), ("C1", "m1", "🤖")])
async def test_scheduled_turn_returns_error_string_after_notifying_im(self):
diff --git a/tests/test_reply_enhancer_platform.py b/tests/test_reply_enhancer_platform.py
index 7b111083f..f535ed4f2 100644
--- a/tests/test_reply_enhancer_platform.py
+++ b/tests/test_reply_enhancer_platform.py
@@ -1,3 +1,4 @@
+import os
import sys
import unittest
from pathlib import Path
@@ -6,7 +7,8 @@ from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.message_dispatcher import ConsolidatedMessageDispatcher
-from core.reply_enhancer import build_reply_enhancements_prompt, process_reply
+from core.reply_enhancer import process_reply
+from core.system_prompt_injection import build_system_prompt_injection
from config import paths
from modules.im import MessageContext
@@ -74,7 +76,7 @@ class _StubController:
class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
def test_prompt_can_exclude_quick_replies(self):
with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):
- prompt = build_reply_enhancements_prompt(include_quick_replies=False)
+ prompt = build_system_prompt_injection(include_quick_replies=False)
self.assertIn("## Silent replies", prompt)
self.assertIn("<silent>reason not shown to the user</silent>", prompt)
@@ -90,6 +92,21 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("`/tmp/user_preferences.md`", prompt)
self.assertIn("`<platform>/<user_id>`", prompt)
+ def test_prompt_can_include_codex_generated_image_instructions(self):
+ with (
+ patch.dict(os.environ, {"CODEX_HOME": "/Users/test/.codex"}),
+ patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")),
+ ):
+ prompt = build_system_prompt_injection(
+ include_quick_replies=False,
+ include_codex_generated_images=True,
+ )
+
+ self.assertIn("### Codex-generated images", prompt)
+ self.assertIn("If you generate an image with Codex", prompt)
+ self.assertIn("file:///Users/test/.codex/generated_images/thread-id/image-file.png", prompt)
+ self.assertIn("Never emit variables, placeholder paths, or sandbox paths like `/mnt/data/...`", prompt)
+
def test_process_reply_strips_silent_blocks_before_enhancements(self):
reply = process_reply(
"Visible\n<silent>skip [secret](file:///tmp/secret.txt)\n---\n[Hidden]</silent>\nDone"
@@ -99,6 +116,16 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(reply.files, [])
self.assertEqual(reply.buttons, [])
+ def test_process_reply_can_disable_quick_reply_button_parsing_only(self):
+ reply = process_reply(
+ "Report [file](file:///tmp/report.txt)\n\n---\n[Continue] | [Stop]",
+ include_quick_replies=False,
+ )
+
+ self.assertEqual(reply.text, "Report file\n\n---\n[Continue] | [Stop]")
+ self.assertEqual([file.path for file in reply.files], ["/tmp/report.txt"])
+ self.assertEqual(reply.buttons, [])
+
def test_prompt_includes_task_watch_and_hook_usage_with_thread_default_session_key(self):
context = MessageContext(
user_id="U1",
@@ -109,7 +136,7 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
)
with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):
- prompt = build_reply_enhancements_prompt(include_quick_replies=True, context=context)
+ prompt = build_system_prompt_injection(include_quick_replies=True, context=context)
self.assertIn("## 3. Scheduled tasks, watches, and hooks", prompt)
self.assertIn("`vibe task add`", prompt)
@@ -165,7 +192,7 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
)
with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):
- prompt = build_reply_enhancements_prompt(
+ prompt = build_system_prompt_injection(
include_quick_replies=True,
context=context,
fallback_platform="slack",
@@ -184,7 +211,7 @@ class ReplyEnhancerPlatformTests(unittest.IsolatedAsyncioTestCase):
)
with patch.object(paths, "get_user_preferences_path", return_value=Path("/tmp/user_preferences.md")):
- prompt = build_reply_enhancements_prompt(
+ prompt = build_system_prompt_injection(
include_quick_replies=True,
context=context,
fallback_platform="slack",
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 6efad272d..a70db89c0 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -690,8 +690,8 @@
"showDurationHint": "Display task elapsed time in result messages",
"includeUserInfo": "Include User Info",
"includeUserInfoHint": "Prepend [username<user_id>] to messages sent to agents",
- "replyEnhancements": "Reply Enhancements",
- "replyEnhancementsHint": "Enable file attachments and quick-reply buttons in agent responses",
+ "replyEnhancements": "Quick-reply Buttons",
+ "replyEnhancementsHint": "Allow agents to add clickable quick-reply buttons at the end of result messages",
"slackLinkPreviews": "Suppress Slack Link Previews",
"slackLinkPreviewsHint": "Disable Slack URL and media preview cards for messages sent by Vibe Remote",
"allowedChannels": "Allowed Groups",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index be30523bc..090552d6f 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -690,8 +690,8 @@
"showDurationHint": "在结果消息中显示任务耗时",
"includeUserInfo": "携带用户信息",
"includeUserInfoHint": "在发给 Agent 的消息前添加 [用户名<用户ID>]",
- "replyEnhancements": "增强回复",
- "replyEnhancementsHint": "启用 Agent 回复中的文件附件和快捷回复按钮",
+ "replyEnhancements": "快捷回复按钮",
+ "replyEnhancementsHint": "允许 Agent 在结果消息末尾添加可点击的快捷回复按钮",
"slackLinkPreviews": "关闭 Slack 链接预览",
"slackLinkPreviewsHint": "关闭 Vibe Remote 发送到 Slack 的 URL 和媒体预览卡片",
"allowedChannels": "允许的群组",