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(reply): add file attachment and quick-reply button enhancements

cyh150ecefbc087
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 6fbafb57b..3d392069f 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -391,6 +391,27 @@ class MessageHandler(BaseHandler):
)
await self.controller.agent_service.handle_message("claude", request)
+ elif callback_data.startswith("quick_reply:"):
+ # Quick-reply button: treat the button text as a new user message
+ reply_text = callback_data[len("quick_reply:") :]
+ if reply_text:
+ # Remove buttons from the original message
+ if context.message_id:
+ try:
+ await self.im_client.remove_inline_keyboard(context, context.message_id)
+ except Exception as err:
+ logger.debug(f"Failed to remove quick-reply buttons: {err}")
+
+ # Dispatch as a normal user message
+ context_for_reply = MessageContext(
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ thread_id=context.thread_id,
+ message_id=None,
+ platform_specific=context.platform_specific,
+ )
+ await self.handle_user_message(context_for_reply, reply_text)
+
else:
logger.warning(f"Unknown callback data: {callback_data}")
await self.im_client.send_message(
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 623b65dbc..55aec0f8f 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -154,8 +154,22 @@ class SessionHandler(BaseHandler):
# Determine final model: explicit override > agent frontmatter > global default
effective_model = explicit_model or agent_model or self.config.claude.default_model
- # Determine final system prompt: agent prompt takes precedence over config
- final_system_prompt = agent_system_prompt or self.config.claude.system_prompt
+ # Determine final system prompt: agent prompt takes precedence over config.
+ # When neither is set, use the claude_code preset with our enhancements
+ # appended so the built-in tools/instructions remain intact.
+ from core.reply_enhancer import REPLY_ENHANCEMENTS_PROMPT
+
+ base_prompt = agent_system_prompt or self.config.claude.system_prompt
+ if base_prompt:
+ # Agent file or config already specifies a full prompt – append ours
+ final_system_prompt = f"{base_prompt}\n\n{REPLY_ENHANCEMENTS_PROMPT}"
+ else:
+ # No explicit prompt – use the claude_code preset + append
+ final_system_prompt = {
+ "type": "preset",
+ "preset": "claude_code",
+ "append": REPLY_ENHANCEMENTS_PROMPT,
+ }
# 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 d09f1735b..e3ac97204 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -11,6 +11,7 @@ import asyncio
from typing import Optional
from modules.im import MessageContext
+from core.reply_enhancer import process_reply
logger = logging.getLogger(__name__)
@@ -142,30 +143,48 @@ class ConsolidatedMessageDispatcher:
if canonical_type == "result":
target_context = self._get_target_context(context)
- if len(text) <= self._get_result_max_chars():
- await im_client.send_message(target_context, text, parse_mode=parse_mode)
- return
- summary = self._build_result_summary(text, self._get_result_max_chars())
- await im_client.send_message(target_context, summary, parse_mode=parse_mode)
+ # --- Reply enhancements: extract file links & quick-reply buttons ---
+ enhanced = process_reply(text)
+ display_text = enhanced.text or text
- if self.controller.config.platform in {"slack", "discord", "lark"} and hasattr(
- im_client, "upload_markdown"
- ):
- try:
- await im_client.upload_markdown(
- target_context,
- title="result.md",
- content=text,
- filetype="markdown",
- )
- except Exception as err:
- logger.warning(f"Failed to upload result attachment: {err}")
- await im_client.send_message(
+ if len(display_text) <= self._get_result_max_chars():
+ if enhanced.buttons:
+ await self._send_with_quick_replies(
+ im_client,
target_context,
- "Failed to upload attachment. Want me to split the result into multiple messages?",
- parse_mode=parse_mode,
+ display_text,
+ enhanced.buttons,
+ parse_mode,
)
+ else:
+ await im_client.send_message(target_context, display_text, parse_mode=parse_mode)
+ else:
+ summary = self._build_result_summary(display_text, self._get_result_max_chars())
+ await im_client.send_message(target_context, summary, parse_mode=parse_mode)
+
+ if self.controller.config.platform in {"slack", "discord", "lark"} and hasattr(
+ im_client, "upload_markdown"
+ ):
+ try:
+ await im_client.upload_markdown(
+ target_context,
+ title="result.md",
+ content=display_text,
+ filetype="markdown",
+ )
+ except Exception as err:
+ logger.warning(f"Failed to upload result attachment: {err}")
+ await im_client.send_message(
+ target_context,
+ "Failed to upload attachment. Want me to split the result into multiple messages?",
+ parse_mode=parse_mode,
+ )
+
+ # Upload extracted file attachments
+ if enhanced.files:
+ await self._upload_file_links(im_client, target_context, enhanced.files)
+
return
if canonical_type not in {"system", "assistant", "toolcall"}:
@@ -281,3 +300,58 @@ class ConsolidatedMessageDispatcher:
self._consolidated_message_ids[consolidated_key] = new_id
except Exception as err:
logger.error(f"Failed to send Log Message: {err}", exc_info=True)
+
+ # ------------------------------------------------------------------
+ # Reply-enhancement helpers
+ # ------------------------------------------------------------------
+
+ async def _send_with_quick_replies(
+ self,
+ im_client,
+ context: MessageContext,
+ text: str,
+ buttons,
+ parse_mode,
+ ) -> None:
+ """Send a message with quick-reply buttons appended."""
+ from modules.im.base import InlineButton, InlineKeyboard
+
+ row = []
+ for btn in buttons:
+ display = f":{btn.emoji}: {btn.text}"
+ callback = f"quick_reply:{btn.text}"
+ row.append(InlineButton(text=display, callback_data=callback))
+
+ keyboard = InlineKeyboard(buttons=[row])
+ await im_client.send_message_with_buttons(
+ context,
+ text,
+ keyboard,
+ parse_mode=parse_mode,
+ )
+
+ async def _upload_file_links(
+ self,
+ im_client,
+ context: MessageContext,
+ files,
+ ) -> None:
+ """Upload local files referenced by ``file://`` links."""
+ import os
+
+ if not hasattr(im_client, "upload_file_from_path"):
+ logger.debug("IM client does not support upload_file_from_path; skipping file uploads")
+ return
+
+ for fl in files:
+ if not os.path.isfile(fl.path):
+ logger.warning("File not found, skipping upload: %s", fl.path)
+ continue
+ try:
+ await im_client.upload_file_from_path(
+ context,
+ file_path=fl.path,
+ title=fl.label or os.path.basename(fl.path),
+ )
+ except Exception as err:
+ logger.warning("Failed to upload file %s: %s", fl.path, err)
diff --git a/core/reply_enhancer.py b/core/reply_enhancer.py
new file mode 100644
index 000000000..7a742d8c0
--- /dev/null
+++ b/core/reply_enhancer.py
@@ -0,0 +1,172 @@
+"""Reply enhancer: parse agent responses for file attachments and quick-reply buttons.
+
+Extracts two special syntaxes from agent reply text:
+
+1. **File links** – Markdown links whose URL starts with ``file://``
+ e.g. ``[screenshot](file:///tmp/shot.png)``
+
+2. **Quick-reply buttons** – A ``---`` separator followed by
+ ``[:emoji:label]`` tokens separated by ``|``
+ e.g. ``---\\n[:ok_hand:好的] | [:white_check_mark:提PR吧]``
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+from dataclasses import dataclass, field
+from typing import List, Tuple
+from urllib.parse import unquote, urlparse
+
+logger = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# Data classes
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class FileLink:
+ """A file reference extracted from agent reply text."""
+
+ label: str # Markdown link text (e.g. "screenshot")
+ path: str # Absolute local path (e.g. "/tmp/shot.png")
+
+
+@dataclass
+class QuickReplyButton:
+ """A quick-reply button extracted from the trailing block."""
+
+ emoji: str # Slack emoji name without colons (e.g. "ok_hand")
+ text: str # Button label / reply text (e.g. "好的")
+
+
+@dataclass
+class EnhancedReply:
+ """Result of processing an agent reply through the enhancer."""
+
+ text: str # Cleaned message text (file links & button block removed)
+ files: List[FileLink] = field(default_factory=list)
+ buttons: List[QuickReplyButton] = field(default_factory=list)
+
+
+# ---------------------------------------------------------------------------
+# Regex patterns
+# ---------------------------------------------------------------------------
+
+# Matches markdown links with file:// URLs: [label](file:///path)
+_FILE_LINK_RE = re.compile(r"\[([^\]]*)\]\((file://[^)]+)\)")
+
+# Matches the quick-reply button block at the end of the text.
+# A horizontal rule (``---``) on its own line, followed by one or more
+# ``[:emoji:text]`` tokens separated by ``|`` or full-width ``|``.
+# We allow optional whitespace and tolerance for the Chinese full-width pipe.
+_BUTTON_BLOCK_RE = re.compile(
+ r"\n-{3,}\s*\n" # --- separator line
+ r"((?:\s*\[:[\w+-]+:\s*[^\]]*\]\s*(?:[||]\s*)?)+)" # button tokens
+ r"\s*$", # trailing whitespace / end of string
+)
+
+# Individual button token: [:emoji_name:button text]
+_BUTTON_TOKEN_RE = re.compile(r"\[:([\w+-]+):\s*([^\]]*)\]")
+
+
+# ---------------------------------------------------------------------------
+# Public API
+# ---------------------------------------------------------------------------
+
+
+def process_reply(text: str) -> 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.
+ """
+ files = _extract_file_links(text)
+ text_no_files = _strip_file_links(text) if files else text
+ buttons, text_clean = _extract_buttons(text_no_files)
+ return EnhancedReply(text=text_clean.rstrip(), files=files, buttons=buttons)
+
+
+# ---------------------------------------------------------------------------
+# Internal helpers
+# ---------------------------------------------------------------------------
+
+
+def _extract_file_links(text: str) -> List[FileLink]:
+ """Return all ``FileLink`` instances found in *text*."""
+ results: List[FileLink] = []
+ for label, url in _FILE_LINK_RE.findall(text):
+ parsed = urlparse(url)
+ if parsed.scheme != "file":
+ continue
+ path = unquote(parsed.path)
+ if not os.path.isabs(path):
+ logger.warning("Skipping non-absolute file link: %s", url)
+ continue
+ results.append(FileLink(label=label, path=path))
+ return results
+
+
+def _strip_file_links(text: str) -> str:
+ """Replace ``[label](file://…)`` with just the label."""
+
+ def _replacer(m: re.Match) -> str:
+ label = m.group(1)
+ url = m.group(2)
+ if url.startswith("file://"):
+ return label # keep the label text, drop the link
+ return m.group(0)
+
+ return _FILE_LINK_RE.sub(_replacer, text)
+
+
+def _extract_buttons(text: str) -> Tuple[List[QuickReplyButton], str]:
+ """Extract trailing quick-reply buttons and return ``(buttons, cleaned_text)``."""
+ m = _BUTTON_BLOCK_RE.search(text)
+ if not m:
+ return [], text
+
+ block = m.group(1)
+ buttons: List[QuickReplyButton] = []
+ for emoji, label in _BUTTON_TOKEN_RE.findall(block):
+ label = label.strip()
+ if label:
+ buttons.append(QuickReplyButton(emoji=emoji, text=label))
+
+ if not buttons:
+ return [], text
+
+ cleaned = text[: m.start()]
+ return buttons, cleaned
+
+
+# ---------------------------------------------------------------------------
+# System prompt for injection into agent backends
+# ---------------------------------------------------------------------------
+
+REPLY_ENHANCEMENTS_PROMPT = """\
+## Vibe Remote Enhanced Reply
+
+You have two optional reply capabilities:
+
+### 1. Send Files
+To send a local file to the user, use a Markdown link with `file://` protocol:
+[description](file:///absolute/path/to/file)
+Example: [screenshot](file:///tmp/result.png)
+The system will auto-attach the file. Use this for images, logs, diffs, etc.
+
+### 2. Quick Reply Buttons
+To offer the user clickable shortcut buttons, append a `---` block at the very end of your message:
+---
+[:emoji_name:button text] | [:emoji_name:button text]
+Example:
+---
+[:ok_hand:好的] | [:white_check_mark:提交PR] | [:mag:先review一下]
+Rules:
+- Must be the last content in your message, after a `---` line.
+- Each button: `[:slack_emoji_name:short text]`, separated by `|`.
+- Infer likely user replies from conversation context; only add when genuinely helpful.
+- Keep 2-4 buttons max, each label under 20 chars.\
+"""
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 5e4b146ca..35b57560d 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -254,10 +254,13 @@ class CodexAgent(BaseAgent):
request: AgentRequest,
) -> str:
"""Create a new Codex thread and return its threadId."""
+ from core.reply_enhancer import REPLY_ENHANCEMENTS_PROMPT
+
params: Dict[str, Any] = {
"cwd": request.working_path,
"approvalPolicy": "never",
"sandbox": "danger-full-access",
+ "developerInstructions": REPLY_ENHANCEMENTS_PROMPT,
}
resp = await transport.send_request("thread/start", params)
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 81cffb316..f3a750a86 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -225,6 +225,9 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
# Prepare message with file attachment info if present
prompt_text = self._prepare_message_with_files(request)
+ # Inject reply-enhancement instructions via the system field (appended by OpenCode)
+ from core.reply_enhancer import REPLY_ENHANCEMENTS_PROMPT
+
await server.prompt_async(
session_id=session_id,
directory=request.working_path,
@@ -232,6 +235,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
agent=agent_to_use,
model=model_dict,
reasoning_effort=reasoning_effort,
+ system=REPLY_ENHANCEMENTS_PROMPT,
)
logger.info(
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index a35dc2d85..d2e28e5e0 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -94,25 +94,15 @@ class OpenCodeServerManager:
async def _get_http_session(self) -> aiohttp.ClientSession:
current_loop = asyncio.get_running_loop()
# Recreate session if it's closed or bound to a different event loop
- if (
- self._http_session is None
- or self._http_session.closed
- or self._http_session_loop is not current_loop
- ):
+ if self._http_session is None or self._http_session.closed or self._http_session_loop is not current_loop:
# Close old session if it exists and is not closed
if self._http_session is not None and not self._http_session.closed:
try:
await self._http_session.close()
except Exception:
pass
- total_timeout: Optional[int] = (
- None
- if self.request_timeout_seconds <= 0
- else self.request_timeout_seconds
- )
- self._http_session = aiohttp.ClientSession(
- timeout=aiohttp.ClientTimeout(total=total_timeout)
- )
+ total_timeout: Optional[int] = None if self.request_timeout_seconds <= 0 else self.request_timeout_seconds
+ self._http_session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=total_timeout))
self._http_session_loop = current_loop
return self._http_session
@@ -183,11 +173,7 @@ class OpenCodeServerManager:
def _is_opencode_serve_cmd(command: str, port: int) -> bool:
if not command:
return False
- return (
- "opencode" in command
- and " serve" in command
- and f"--port={port}" in command
- )
+ return "opencode" in command and " serve" in command and f"--port={port}" in command
def _is_port_available(self) -> bool:
try:
@@ -259,11 +245,7 @@ class OpenCodeServerManager:
self._clear_pid_file()
return
- if (
- self._process
- and self._process.returncode is None
- and self._process.pid == pid
- ):
+ if self._process and self._process.returncode is None and self._process.pid == pid:
return
# Check if the server is healthy before deciding to kill it.
@@ -275,28 +257,18 @@ class OpenCodeServerManager:
if actual_pids:
actual_pid = actual_pids[0]
if actual_pid != pid:
- logger.info(
- f"Adopting healthy OpenCode server (updating stale PID {pid} -> {actual_pid})"
- )
+ logger.info(f"Adopting healthy OpenCode server (updating stale PID {pid} -> {actual_pid})")
self._write_pid_file(actual_pid)
else:
- logger.info(
- f"Adopting healthy OpenCode server pid={pid} from previous run"
- )
+ logger.info(f"Adopting healthy OpenCode server pid={pid} from previous run")
else:
# Server is healthy but we can't find its PID - clear stale file
- logger.info(
- f"Adopting healthy OpenCode server (clearing stale PID file, pid={pid} not found)"
- )
+ logger.info(f"Adopting healthy OpenCode server (clearing stale PID file, pid={pid} not found)")
self._clear_pid_file()
return
cmd = self._get_pid_command(pid)
- if (
- cmd
- and self._is_opencode_serve_cmd(cmd, self.port)
- and self._pid_exists(pid)
- ):
+ if cmd and self._is_opencode_serve_cmd(cmd, self.port) and self._pid_exists(pid):
await self._terminate_pid(pid, reason="orphaned and unhealthy")
self._clear_pid_file()
@@ -335,9 +307,7 @@ class OpenCodeServerManager:
async def _is_healthy(self) -> bool:
try:
session = await self._get_http_session()
- async with session.get(
- f"{self.base_url}/global/health", timeout=aiohttp.ClientTimeout(total=5)
- ) as resp:
+ async with session.get(f"{self.base_url}/global/health", timeout=aiohttp.ClientTimeout(total=5)) as resp:
if resp.status == 200:
data = await resp.json()
return data.get("healthy", False)
@@ -379,8 +349,7 @@ class OpenCodeServerManager:
self._write_pid_file(self._process.pid)
except FileNotFoundError:
raise RuntimeError(
- f"OpenCode CLI not found at '{self.binary}'. "
- "Please install OpenCode or set OPENCODE_CLI_PATH."
+ f"OpenCode CLI not found at '{self.binary}'. Please install OpenCode or set OPENCODE_CLI_PATH."
)
start_time = time.monotonic()
@@ -395,8 +364,7 @@ class OpenCodeServerManager:
self._clear_pid_file()
self._process = None
raise RuntimeError(
- f"OpenCode server failed to start within {SERVER_START_TIMEOUT}s. "
- f"Process exit code: {exit_code}"
+ f"OpenCode server failed to start within {SERVER_START_TIMEOUT}s. Process exit code: {exit_code}"
)
async def stop(self) -> None:
@@ -409,9 +377,7 @@ class OpenCodeServerManager:
# Don't terminate OpenCode server on vibe-remote shutdown.
# Let it continue running so the next vibe-remote instance can adopt it.
# This prevents interrupting tasks that are still in progress.
- logger.info(
- "OpenCode server left running for next vibe-remote instance to adopt"
- )
+ logger.info("OpenCode server left running for next vibe-remote instance to adopt")
# Keep pid_file so next instance knows about the running server.
self._process = None
@@ -419,9 +385,7 @@ class OpenCodeServerManager:
def stop_sync(self) -> None:
if self._http_session and self._http_session_loop:
try:
- future = asyncio.run_coroutine_threadsafe(
- self._http_session.close(), self._http_session_loop
- )
+ future = asyncio.run_coroutine_threadsafe(self._http_session.close(), self._http_session_loop)
future.result(timeout=5)
except Exception as e:
logger.debug(f"Failed to close OpenCode HTTP session: {e}")
@@ -432,9 +396,7 @@ class OpenCodeServerManager:
# Don't terminate OpenCode server on vibe-remote shutdown.
# Let it continue running so the next vibe-remote instance can adopt it.
# This prevents interrupting tasks that are still in progress.
- logger.info(
- "OpenCode server left running for next vibe-remote instance to adopt"
- )
+ logger.info("OpenCode server left running for next vibe-remote instance to adopt")
# Keep pid_file so next instance knows about the running server.
# Don't clear _process reference - just let it be garbage collected.
@@ -448,13 +410,9 @@ class OpenCodeServerManager:
# Don't terminate OpenCode server on vibe-remote shutdown.
# Let it continue running so the next vibe-remote instance can adopt it.
- logger.info(
- "OpenCode server left running for next vibe-remote instance to adopt"
- )
+ logger.info("OpenCode server left running for next vibe-remote instance to adopt")
- async def create_session(
- self, directory: str, title: Optional[str] = None
- ) -> Dict[str, Any]:
+ async def create_session(self, directory: str, title: Optional[str] = None) -> Dict[str, Any]:
session = await self._get_http_session()
body: Dict[str, Any] = {}
if title:
@@ -498,9 +456,7 @@ class OpenCodeServerManager:
) as resp:
if resp.status != 200:
error_text = await resp.text()
- raise RuntimeError(
- f"Failed to send message: {resp.status} {error_text}"
- )
+ raise RuntimeError(f"Failed to send message: {resp.status} {error_text}")
return await resp.json()
async def prompt_async(
@@ -511,6 +467,7 @@ class OpenCodeServerManager:
agent: Optional[str] = None,
model: Optional[Dict[str, str]] = None,
reasoning_effort: Optional[str] = None,
+ system: Optional[str] = None,
) -> None:
"""Start a prompt asynchronously without holding the HTTP request open."""
@@ -525,6 +482,8 @@ class OpenCodeServerManager:
body["model"] = model
if reasoning_effort:
body["variant"] = reasoning_effort
+ if system:
+ body["system"] = system
async with session.post(
f"{self.base_url}/session/{session_id}/prompt_async",
@@ -534,13 +493,9 @@ class OpenCodeServerManager:
# OpenCode returns 204 when accepted.
if resp.status not in (200, 204):
error_text = await resp.text()
- raise RuntimeError(
- f"Failed to start async prompt: {resp.status} {error_text}"
- )
+ raise RuntimeError(f"Failed to start async prompt: {resp.status} {error_text}")
- async def list_messages(
- self, session_id: str, directory: str
- ) -> List[Dict[str, Any]]:
+ async def list_messages(self, session_id: str, directory: str) -> List[Dict[str, Any]]:
session = await self._get_http_session()
async with session.get(
f"{self.base_url}/session/{session_id}/message",
@@ -548,14 +503,10 @@ class OpenCodeServerManager:
) as resp:
if resp.status != 200:
error_text = await resp.text()
- raise RuntimeError(
- f"Failed to list messages: {resp.status} {error_text}"
- )
+ raise RuntimeError(f"Failed to list messages: {resp.status} {error_text}")
return await resp.json()
- async def get_message(
- self, session_id: str, message_id: str, directory: str
- ) -> Dict[str, Any]:
+ async def get_message(self, session_id: str, message_id: str, directory: str) -> Dict[str, Any]:
session = await self._get_http_session()
async with session.get(
f"{self.base_url}/session/{session_id}/message/{message_id}",
@@ -566,9 +517,7 @@ class OpenCodeServerManager:
raise RuntimeError(f"Failed to get message: {resp.status} {error_text}")
return await resp.json()
- async def list_questions(
- self, directory: Optional[str] = None
- ) -> List[Dict[str, Any]]:
+ async def list_questions(self, directory: Optional[str] = None) -> List[Dict[str, Any]]:
session = await self._get_http_session()
params = {"directory": directory} if directory else None
async with session.get(
@@ -577,15 +526,11 @@ class OpenCodeServerManager:
) as resp:
if resp.status != 200:
error_text = await resp.text()
- raise RuntimeError(
- f"Failed to list questions: {resp.status} {error_text}"
- )
+ raise RuntimeError(f"Failed to list questions: {resp.status} {error_text}")
data = await resp.json()
return data if isinstance(data, list) else []
- async def reply_question(
- self, question_id: str, directory: str, answers: List[List[str]]
- ) -> bool:
+ async def reply_question(self, question_id: str, directory: str, answers: List[List[str]]) -> bool:
session = await self._get_http_session()
async with session.post(
f"{self.base_url}/question/{question_id}/reply",
@@ -594,9 +539,7 @@ class OpenCodeServerManager:
) as resp:
if resp.status != 200:
error_text = await resp.text()
- raise RuntimeError(
- f"Failed to reply question: {resp.status} {error_text}"
- )
+ raise RuntimeError(f"Failed to reply question: {resp.status} {error_text}")
data = await resp.json()
return bool(data)
@@ -613,9 +556,7 @@ class OpenCodeServerManager:
logger.warning(f"Failed to abort session {session_id}: {e}")
return False
- async def get_session(
- self, session_id: str, directory: str
- ) -> Optional[Dict[str, Any]]:
+ async def get_session(self, session_id: str, directory: str) -> Optional[Dict[str, Any]]:
session = await self._get_http_session()
try:
async with session.get(
@@ -645,11 +586,7 @@ class OpenCodeServerManager:
if resp.status == 200:
agents = await resp.json()
# Filter to primary agents (build, plan), exclude hidden/subagent
- return [
- a
- for a in agents
- if a.get("mode") == "primary" and not a.get("hidden", False)
- ]
+ return [a for a in agents if a.get("mode") == "primary" and not a.get("hidden", False)]
return []
except Exception as e:
logger.warning(f"Failed to get available agents: {e}")
@@ -728,9 +665,7 @@ class OpenCodeServerManager:
return None
- def _get_agent_config(
- self, config: Dict[str, Any], agent_name: Optional[str]
- ) -> Dict[str, Any]:
+ def _get_agent_config(self, config: Dict[str, Any], agent_name: Optional[str]) -> Dict[str, Any]:
"""Get agent-specific config from opencode.json with type safety."""
if not agent_name:
@@ -758,9 +693,7 @@ class OpenCodeServerManager:
agent_config = self._get_agent_config(config, agent_name)
model = agent_config.get("model")
if isinstance(model, str) and model:
- logger.debug(
- f"Found model '{model}' for agent '{agent_name}' in opencode.json"
- )
+ logger.debug(f"Found model '{model}' for agent '{agent_name}' in opencode.json")
return model
# Fall back to global default model
@@ -770,9 +703,7 @@ class OpenCodeServerManager:
return model
return None
- def get_agent_reasoning_effort_from_config(
- self, agent_name: Optional[str]
- ) -> Optional[str]:
+ def get_agent_reasoning_effort_from_config(self, agent_name: Optional[str]) -> Optional[str]:
"""Read agent's reasoningEffort from user's opencode.json config file."""
config = self._load_opencode_user_config()
@@ -787,27 +718,19 @@ class OpenCodeServerManager:
reasoning_effort = agent_config.get("reasoningEffort")
if isinstance(reasoning_effort, str) and reasoning_effort:
if reasoning_effort in valid_efforts:
- logger.debug(
- f"Found reasoningEffort '{reasoning_effort}' for agent '{agent_name}' in opencode.json"
- )
+ logger.debug(f"Found reasoningEffort '{reasoning_effort}' for agent '{agent_name}' in opencode.json")
return reasoning_effort
else:
- logger.debug(
- f"Ignoring unknown reasoningEffort '{reasoning_effort}' for agent '{agent_name}'"
- )
+ logger.debug(f"Ignoring unknown reasoningEffort '{reasoning_effort}' for agent '{agent_name}'")
# Fall back to global default reasoningEffort
reasoning_effort = config.get("reasoningEffort")
if isinstance(reasoning_effort, str) and reasoning_effort:
if reasoning_effort in valid_efforts:
- logger.debug(
- f"Using global default reasoningEffort '{reasoning_effort}' from opencode.json"
- )
+ logger.debug(f"Using global default reasoningEffort '{reasoning_effort}' from opencode.json")
return reasoning_effort
else:
- logger.debug(
- f"Ignoring unknown global reasoningEffort '{reasoning_effort}'"
- )
+ logger.debug(f"Ignoring unknown global reasoningEffort '{reasoning_effort}'")
return None
def get_default_agent_from_config(self) -> Optional[str]:
diff --git a/modules/im/base.py b/modules/im/base.py
index 8b3a0716c..e2212665a 100644
--- a/modules/im/base.py
+++ b/modules/im/base.py
@@ -240,6 +240,24 @@ class BaseIMClient(ABC):
"""Upload markdown content as a file (optional per platform)."""
raise NotImplementedError
+ async def upload_file_from_path(
+ self,
+ context: MessageContext,
+ file_path: str,
+ title: Optional[str] = None,
+ ) -> str:
+ """Upload a local file to the conversation (optional per platform).
+
+ Args:
+ context: Message context (channel, thread, etc)
+ file_path: Absolute path to the local file
+ title: Display title (defaults to the file basename)
+
+ Returns:
+ File ID or empty string on failure
+ """
+ raise NotImplementedError
+
@abstractmethod
async def edit_message(
self,
diff --git a/modules/im/slack.py b/modules/im/slack.py
index a8004aaf9..ecf0d09e3 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -242,6 +242,31 @@ class SlackBot(BaseIMClient):
file_id = result.get("files", [{}])[0].get("id")
return file_id or ""
+ async def upload_file_from_path(
+ self,
+ context: MessageContext,
+ file_path: str,
+ title: Optional[str] = None,
+ ) -> str:
+ """Upload a local file to the Slack conversation."""
+ import os
+
+ self._ensure_clients()
+ filename = os.path.basename(file_path)
+ display_title = title or filename
+
+ result = await self.web_client.files_upload_v2(
+ channel=context.channel_id,
+ thread_ts=context.thread_id,
+ file=file_path,
+ filename=filename,
+ title=display_title,
+ )
+ file_id = result.get("file", {}).get("id")
+ if not file_id:
+ file_id = result.get("files", [{}])[0].get("id")
+ return file_id or ""
+
async def download_file(
self,
file_info: Dict[str, Any],