diff --git a/.github/workflows/plugins-misc-tests.yml b/.github/workflows/plugins-misc-tests.yml index 2e0b174a2..16ebbae5a 100644 --- a/.github/workflows/plugins-misc-tests.yml +++ b/.github/workflows/plugins-misc-tests.yml @@ -56,8 +56,13 @@ jobs: if [ -s "$plugin/requirements.txt" ]; then install_args+=(-r "$plugin/requirements.txt") fi + if [ "$name" = OASlackBridge ]; then + install_args=(--python "$python_bin" -r "$plugin/requirements-dev.txt") + fi uv pip install "${install_args[@]}" >/dev/null - "$python_bin" -c 'from importlib.metadata import version; assert version("langbot-plugin") == "0.7.4"' + if [ "$name" != OASlackBridge ]; then + "$python_bin" -c 'from importlib.metadata import version; assert version("langbot-plugin") == "0.7.4"' + fi if ! (cd "$plugin" && "$python_bin" -m pytest tests -q -p no:cacheprovider); then echo "::error::$name test suite failed" status=1 diff --git a/plugins/AGENTS.md b/plugins/AGENTS.md index 5e30e565e..56cc716ea 100644 --- a/plugins/AGENTS.md +++ b/plugins/AGENTS.md @@ -15,6 +15,7 @@ Official LangBot plugins, migrated from the archived `langbot-app/langbot-plugin - Never run `lbp build` / `lbp publish` from the repository root or `plugins/`; run them inside one plugin directory. - Keep `metadata.author`, `metadata.name` and component IDs stable. Bump the plugin's manifest (and project) version for a release; never bump Core's version for a plugin change. - Each plugin keeps its own environment and lockfile; run its tests in isolation following its README. CI: `.github/workflows/plugins-*.yml`. +- Bridges combining a Pipeline EventListener and an event Runner stay in `misc/`; Runner-only plugins belong in `Runner/`. - Declare the minimal `spec.permissions` (`workspace_operations`, `capabilities`) the plugin needs; Runners must expose only `ctx.resources.workspace_operations` to models. See `../docs/en/plugin/dev/permissions.mdx`. - Use the Workspace API (`self.plugin.workspace`), the standard platform APIs and `call_platform_api` documented in `../docs/en/plugin/dev/apis/`; plugin runtime code must not import Core (`langbot.*`) or call LangBot's own HTTP routes to bypass installation grants (test scripts may drive a test instance). - Marketplace README convention: English root `README.md`, translations in `readme/README_{lang}.md`, eight-locale `metadata.label` / `description`, live `repository` URL. diff --git a/plugins/catalog.json b/plugins/catalog.json index cce5b2f7c..4cde655e5 100644 --- a/plugins/catalog.json +++ b/plugins/catalog.json @@ -225,7 +225,7 @@ }, { "id": "langbot-team/OASlackBridge", - "version": "0.1.0", + "version": "0.2.0", "category": "misc", "path": "misc/OASlackBridge", "repository": "https://github.com/langbot-app/LangBot/tree/master/plugins/misc/OASlackBridge" diff --git a/plugins/misc/OASlackBridge/README.md b/plugins/misc/OASlackBridge/README.md index 39a918fe8..ca43ff015 100644 --- a/plugins/misc/OASlackBridge/README.md +++ b/plugins/misc/OASlackBridge/README.md @@ -7,12 +7,26 @@ Forward WeChat Official Account messages containing configured keywords to a Sla ## Prerequisites - A verified Official Account with customer-service messaging permission, configured as a LangBot bot with **Mode = auto**. Other modes cannot send asynchronous staff replies; core enforces this restriction. -- A LangBot core containing **langbot-app/LangBot #2863 and #2864**: Official Account `send_message`, Slack `send_message` returning `message_id`, outbound `Quote` as a thread destination, and inbound bot-thread replies carrying `Quote.id`. Older cores cannot run this bridge. +- The minimum Host contract for 0.2.0 includes Unified API, plugin installation permissions, Runner `usages: [event]`, Bot Plugin processor subscriptions, Official Account `send_message`, and Slack thread support (`Quote.id` and `message_id`). Core must also include the standard Runner send authorization and MessageChain conversion shipped with this plugin update. Older Hosts without these capabilities cannot load or run this version. - A Slack App connected through LangBot, invited to the target channel. Enable bot event subscriptions `app_mention` and `message.channels`; for a private channel also enable `message.groups`. Required bridge scopes are `chat:write`, `app_mentions:read`, `channels:history`, and `groups:history` for private channels. Retain the other scopes required by LangBot's Slack adapter. Reinstall the Slack App after changing scopes. Socket Mode also needs an App-Level Token with `connections:write`; webhook mode needs LangBot's reachable event endpoint. -- Enable this plugin for **both bots' message pipelines**. Place it before plugins that answer or consume messages. Restrict membership of the target channel to staff authorized to reply to customers; every human participant in that channel can reply through a mapped thread. +- Restrict membership of the target channel to staff authorized to reply to customers; every human participant in that channel can reply through a mapped thread. + +## Setup and upgrade to 0.2.0 + +1. Install or upgrade the plugin. A Workspace member must confirm `bot.message.send` and `storage.plugin` on the plugin detail page. Version 0.2.0 switches from compatibility mode to strict permissions; declaring permissions does not grant them. No Workspace operations are requested. +2. Fill in the plugin-level configuration below. Both components use this configuration; the processor has no separate settings. +3. Set the Official Account Bot's **main route to a Pipeline with this plugin enabled**, before other plugins that answer or consume messages. The EventListener only runs inside a Pipeline. An Agent main route cannot suppress AI replies during takeover. +4. Create a Plugin processor instance using **Slack reply processor**, then subscribe to it in the Slack Bot detail page's **Plugin processor** section. Installation alone does not subscribe it. The Slack Bot main route can be any target, including **discard**; it no longer needs this plugin in its Pipeline. +5. Staff must reply in the mapped thread **without @bot**. Processor subscriptions run in parallel with the main route and cannot prevent its replies. Mentioning the bot while the main route is AI can therefore also trigger an AI response. + +Existing 0.1.0 sessions and thread mappings remain usable after upgrading the same installation; storage keys are unchanged. The EventListener no longer handles Slack group messages. Complete the processor subscription before resuming staff replies. + +Receipts use the event-scoped standard `ctx.reply`, preserving the source Slack `thread_ts`. The Runner declares `tool_calling: true` and `permissions.tools: [call]` with `permissions.storage: [plugin]`; `event_reply` is automatically available for message events, so no extra platform tools or installation capabilities need enabling. `get_bot_uuid` is also event-scoped. Cross-bot sends use `bot.message.send`; session reads, writes, and deletes use `storage.plugin`. Permission denials are logged without raw diagnostics; the processor posts a missing-permission receipt when event replies remain available. ## Configuration +If plugin storage or sending to Slack is denied, the Official Account listener logs a warning and leaves the normal AI Pipeline enabled for that message, including keyword matches and messages during an existing takeover. It suppresses AI only after bridge handling succeeds. This keeps customers from receiving no response while permissions are unavailable; messages already forwarded to Slack remain visible there. The plugin does not clear suppression set by another Pipeline plugin. + | Key | Default | Meaning | | --- | --- | --- | | `oa_bot` | required | Official Account bot selector, auto mode | @@ -26,8 +40,8 @@ Forward WeChat Official Account messages containing configured keywords to a Sla ## Staff workflow 1. A user sends a keyword. The channel receives a root message containing a shortened openid, the keyword, UTC time, and original text. -2. Reply **inside that thread**. An @mention is optional. Only `Plain` text is sent to WeChat; the reply context and @bot prefix are removed. Slack links, mentions, channel references, and escaped `&`, `<`, `>` are converted to readable plain text. The thread receives `✅` after a successful send, or a bilingual error category and WeChat `errcode` after rejection. -3. Send **`!close`** in the thread to release takeover. `@bot /close` is also supported. A bare `/close` may be interpreted by Slack as a native slash command instead of a message. +2. Reply **inside that thread without @bot**. Only `Plain` text is sent to WeChat; the reply context and any leading @bot prefix are removed. Slack links, mentions, channel references, and escaped `&`, `<`, `>` are converted to readable plain text. The thread receives `✅` after a successful send, or a bilingual error category and WeChat `errcode` after rejection. Unmapped threads are logged and receive no reply. +3. Send **`!close`** in the thread to release takeover. The processor also accepts `/close` if delivered as message text, but Slack may interpret it as a native slash command instead. 4. Once closed or expired, ordinary user messages follow the normal AI pipeline. A new keyword starts a new thread. Expiration is checked on the next event, without a background timer. Staff replies do not extend takeover; user messages do. Turning `forward_followups` off still suppresses AI and refreshes both timestamps during takeover. Changing the configured Slack destination ends the old session when the next user message arrives; a new keyword is required to start a session in the new destination. @@ -51,20 +65,25 @@ Each session is stored separately by installation, Official Account bot UUID, an Storage reads enumerate the plugin's keys. Expired conversations that are never accessed again remain stored and increase that listing; there is no periodic cleanup. -The plugin supports `shared-runtime-v1` / `stateless-v1`; details are in [SHARED_RUNTIME.md](SHARED_RUNTIME.md). It uses only standard `send_message` calls for platform messaging and requires no plugin-specific credentials. +The plugin supports `shared-runtime-v1` / `stateless-v1`; details are in [SHARED_RUNTIME.md](SHARED_RUNTIME.md). Both components share plugin storage and use standard `send_message` and event reply APIs, with no plugin-specific credentials. ## Validation and packaging -From the repository root, with `langbot-plugin`, `pytest`, `pytest-asyncio`, and `PyYAML` installed: +From the repository root, create an isolated environment with the Unified API SDK snapshot: ```sh +uv venv plugins/misc/OASlackBridge/.venv +uv pip install --python plugins/misc/OASlackBridge/.venv/bin/python -r plugins/misc/OASlackBridge/requirements-dev.txt +source plugins/misc/OASlackBridge/.venv/bin/activate python -m pytest plugins/misc/OASlackBridge/tests -q python plugins/scripts/check_catalog.py +python plugins/scripts/test_repository.py +ruff check plugins/misc/OASlackBridge cd plugins/misc/OASlackBridge lbp build -o dist ``` -Tests use real SDK invocation bindings and a mock Host for messaging and storage; they never contact Slack or WeChat. A live acceptance check needs your own authorized test accounts: send a keyword, send a follow-up, reply from Slack both with and without @bot, restart the plugin worker and reply again, then send `!close` and confirm normal AI replies resume. Test in a dedicated channel, not a production customer thread. +Tests use real SDK invocation bindings, RunnerContext dispatch, and a mock Host for messaging and storage; they never contact Slack or WeChat. A live acceptance check needs your own authorized test accounts: subscribe the processor, send a keyword, send a follow-up, reply from Slack without @bot, restart the plugin worker and reply again, then send `!close` and confirm normal AI replies resume. Test in a dedicated channel, not a production customer thread. ## Limitations diff --git a/plugins/misc/OASlackBridge/SHARED_RUNTIME.md b/plugins/misc/OASlackBridge/SHARED_RUNTIME.md index 998a32ebd..1fff86db1 100644 --- a/plugins/misc/OASlackBridge/SHARED_RUNTIME.md +++ b/plugins/misc/OASlackBridge/SHARED_RUNTIME.md @@ -1,9 +1,9 @@ # Shared runtime -OASlackBridge declares `shared-runtime-v1` and `stateless-v1`. The event listener retains no invocation data. The plugin reads configuration and the active installation binding only inside event invocations, not during initialization. +OASlackBridge declares `shared-runtime-v1` and `stateless-v1`. The Official Account EventListener and Slack reply Runner retain no invocation data. Both share the plugin's storage and installation lock. The plugin reads configuration and the active installation binding only inside event invocations, not during initialization. The Runner receives a fresh RunnerContext per invocation and uses the plugin configuration rather than processor instance configuration. Storage keys include the stable `instance_uuid:workspace_uuid:installation_uuid` scope. Runtime revision is excluded so upgrades preserve mappings. Session rows additionally include Official Account bot UUID and full openid; thread lookup rows include Slack bot UUID, channel ID, and root message timestamp. Each row is written separately. A shared worker without a binding refuses storage access; dedicated placement uses a dedicated scope. One process-local lock per installation serializes session creation, updates, and staff sends. This prevents concurrent messages from creating two roots in the same worker and prevents `/close` from racing a send. It deliberately serializes that installation's conversations while allowing other installations to proceed independently. Persistent rows are read on demand, never cached across invocations. Revocation removes only the affected lock and makes no Host calls; destruction releases all locks. No background tasks are created. -The tests run one plugin/listener object graph across separate installation and Workspace bindings over a flat mock Host storage namespace. They verify that identical user/thread IDs do not cross installation boundaries, runtime revision changes preserve routing, and revocation does not delete persistent data or sibling locks. The Host remains responsible for enforcing Workspace-scoped bot and storage authorization. +The tests run one plugin/listener/Runner object graph across separate installation and Workspace bindings over a flat mock Host storage namespace. They verify that identical user/thread IDs do not cross installation boundaries, runtime revision changes and 0.1.0 storage rows preserve routing, and revocation does not delete persistent data or sibling locks. The Host remains responsible for enforcing Workspace-scoped bot and storage authorization. diff --git a/plugins/misc/OASlackBridge/components/event_listener/bridge.py b/plugins/misc/OASlackBridge/components/event_listener/bridge.py index 233e3bab2..6c502e27c 100644 --- a/plugins/misc/OASlackBridge/components/event_listener/bridge.py +++ b/plugins/misc/OASlackBridge/components/event_listener/bridge.py @@ -1,6 +1,10 @@ +import logging + from langbot_plugin.api.definition.components.common.event_listener import EventListener from langbot_plugin.api.entities import events +from main import permission_denied, permission_notice + class BridgeListener(EventListener): async def initialize(self): @@ -8,8 +12,11 @@ class BridgeListener(EventListener): @self.handler(events.PersonMessageReceived) async def on_person(event_context): - await self.plugin.handle_person(event_context) - - @self.handler(events.GroupMessageReceived) - async def on_group(event_context): - await self.plugin.handle_group(event_context) + try: + await self.plugin.handle_person(event_context) + except Exception as error: + if not permission_denied(error): + raise + logging.getLogger(__name__).warning( + permission_notice("storage.plugin / bot.message.send") + ) diff --git a/plugins/misc/OASlackBridge/components/event_listener/bridge.yaml b/plugins/misc/OASlackBridge/components/event_listener/bridge.yaml index e1732d072..b485a7122 100644 --- a/plugins/misc/OASlackBridge/components/event_listener/bridge.yaml +++ b/plugins/misc/OASlackBridge/components/event_listener/bridge.yaml @@ -5,6 +5,21 @@ metadata: label: en_US: Official Account Slack Bridge zh_Hans: 公众号 Slack 桥接 + zh_Hant: 公眾號 Slack 橋接 + ja_JP: 公式アカウント Slack ブリッジ + es_ES: Puente de cuentas oficiales a Slack + ru_RU: Мост между официальным аккаунтом и Slack + th_TH: สะพานเชื่อมบัญชีทางการกับ Slack + vi_VN: Cầu nối tài khoản chính thức với Slack + description: + en_US: Forward Official Account messages and suppress AI during takeover. + zh_Hans: 转发公众号消息,并在接管期间阻断 AI 回复。 + zh_Hant: 轉發公眾號訊息,並在接管期間阻止 AI 回覆。 + ja_JP: 公式アカウントのメッセージを転送し、引き継ぎ中は AI の返信を停止します。 + es_ES: Reenvía mensajes de cuentas oficiales y suspende las respuestas de IA durante la atención humana. + ru_RU: Пересылает сообщения официального аккаунта и отключает ответы ИИ при обслуживании сотрудником. + th_TH: ส่งต่อข้อความจากบัญชีทางการและหยุดคำตอบ AI ระหว่างที่เจ้าหน้าที่ดูแล + vi_VN: Chuyển tiếp tin nhắn tài khoản chính thức và ngăn AI trả lời khi nhân viên tiếp quản. spec: {} execution: python: diff --git a/plugins/misc/OASlackBridge/components/runner/__init__.py b/plugins/misc/OASlackBridge/components/runner/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/plugins/misc/OASlackBridge/components/runner/slack_reply.py b/plugins/misc/OASlackBridge/components/runner/slack_reply.py new file mode 100644 index 000000000..bfb9665ed --- /dev/null +++ b/plugins/misc/OASlackBridge/components/runner/slack_reply.py @@ -0,0 +1,86 @@ +import asyncio +import re +import time + +from langbot_plugin.api.definition.components.runner import Runner, RunnerContext +from langbot_plugin.api.entities.builtin.platform import message +from langbot_plugin.api.entities.builtin.platform.events import MessageReceivedEvent + +from main import from_slack, permission_denied, permission_notice, plain_text, send_error + + +class SlackReplyProcessor(Runner): + async def initialize(self): + await super().initialize() + + @self.handler(MessageReceivedEvent) + async def on_message(ctx: RunnerContext): + event = ctx.platform_event + config = self.plugin.get_config() + if ( + not event.bot_uuid + or event.bot_uuid != config.get("slack_bot") + or str(event.chat_id) != config.get("slack_channel_id") + ): + return + thread = next((part.id for part in event.message_chain if isinstance(part, message.Quote)), "") + if not thread: + return + try: + async with self.plugin._locks.setdefault(self.plugin.scope(), asyncio.Lock()): + await self.handle_reply(ctx, config, thread) + except Exception as error: + if not permission_denied(error): + raise + await ctx.log(permission_notice("storage.plugin"), "warning") + await self.acknowledge(ctx, permission_notice("storage.plugin")) + + async def acknowledge(self, ctx: RunnerContext, text: str): + try: + await ctx.reply(text) + except Exception as error: + if not permission_denied(error): + raise + await ctx.log("Permission denied: event_reply; check processor tools.call authorization.", "warning") + + async def handle_reply(self, ctx: RunnerContext, config: dict, thread: str): + event = ctx.platform_event + mapping = await self.plugin.load(self.plugin.key("thread", event.bot_uuid, str(event.chat_id), thread)) + if not mapping: + await ctx.log("Ignoring Slack thread without a takeover mapping.") + return + key = mapping["session_key"] + session = await self.plugin.load(key) + if not session or session["thread"] != thread or session["oa_bot"] != config.get("oa_bot"): + await ctx.log("Ignoring Slack thread without a matching takeover session.") + return + text = plain_text(event.message_chain) + if any(isinstance(part, message.At) for part in event.message_chain): + text = re.sub(r"^<@[^>]+>\s*", "", text).strip() + now = time.time() + if text in ("/close", "!close"): + await self.plugin.close(key, session) + await self.acknowledge(ctx, "✅ 接管已结束,恢复 AI 回复 / Takeover closed; AI replies resumed.") + return + if now - session["last_user_at"] >= 48 * 3600: + await self.plugin.close(key, session) + await self.acknowledge(ctx, "❌ 48 小时回复窗口已过 / 48-hour reply window expired") + return + if session["expires_at"] <= now: + await self.plugin.close(key, session) + await self.acknowledge(ctx, "❌ 接管已到期,恢复 AI 回复 / Takeover expired; AI replies resumed.") + return + if not text: + await self.acknowledge(ctx, "❌ 仅支持文本回复 / Only text replies are supported.") + return + try: + await self.plugin.send_message( + bot_uuid=session["oa_bot"], target_type="person", target_id=session["openid"], + message_chain=message.MessageChain([message.Plain(text=from_slack(text))]), + ) + except Exception as error: + if permission_denied(error): + await ctx.log(permission_notice("bot.message.send"), "warning") + await self.acknowledge(ctx, send_error(error)) + else: + await self.acknowledge(ctx, "✅ 已发送 / Sent") diff --git a/plugins/misc/OASlackBridge/components/runner/slack_reply.yaml b/plugins/misc/OASlackBridge/components/runner/slack_reply.yaml new file mode 100644 index 000000000..3dcd0fe81 --- /dev/null +++ b/plugins/misc/OASlackBridge/components/runner/slack_reply.yaml @@ -0,0 +1,35 @@ +apiVersion: langbot/v1 +kind: Runner +metadata: + name: slack_reply + label: + en_US: Slack reply processor + zh_Hans: Slack 回复处理器 + zh_Hant: Slack 回覆處理器 + ja_JP: Slack 返信プロセッサー + es_ES: Procesador de respuestas de Slack + ru_RU: Обработчик ответов Slack + th_TH: ตัวประมวลผลการตอบกลับ Slack + vi_VN: Bộ xử lý trả lời Slack + description: + en_US: Send mapped Slack thread replies to Official Account users. + zh_Hans: 将已映射的 Slack thread 回复发送给公众号用户。 + zh_Hant: 將已對應的 Slack 討論串回覆傳送給公眾號使用者。 + ja_JP: 対応する Slack スレッドの返信を公式アカウントのユーザーに送信します。 + es_ES: Envía respuestas de hilos vinculados de Slack a usuarios de cuentas oficiales. + ru_RU: Отправляет ответы из связанных веток Slack пользователям официального аккаунта. + th_TH: ส่งคำตอบจากเธรด Slack ที่เชื่อมโยงไปยังผู้ใช้บัญชีทางการ + vi_VN: Gửi trả lời từ luồng Slack đã liên kết đến người dùng tài khoản chính thức. +spec: + usages: [event] + events: [message.received] + config: [] + capabilities: + tool_calling: true + permissions: + tools: [call] + storage: [plugin] +execution: + python: + path: slack_reply.py + attr: SlackReplyProcessor diff --git a/plugins/misc/OASlackBridge/main.py b/plugins/misc/OASlackBridge/main.py index 4f2eadb7f..89b0fa542 100644 --- a/plugins/misc/OASlackBridge/main.py +++ b/plugins/misc/OASlackBridge/main.py @@ -10,6 +10,7 @@ from urllib.parse import quote from langbot_plugin.api.definition.plugin import BasePlugin from langbot_plugin.api.entities.builtin.platform import message +from langbot_plugin.api.proxies.runner import PermissionDeniedError def plain_text(chain) -> str: @@ -38,6 +39,8 @@ def from_slack(text: str) -> str: def send_error(error: Exception) -> str: + if permission_denied(error): + return permission_notice("bot.message.send") match = re.search(r"errcode=(\d+)", str(error)) if not match: return "❌ 发送失败 / Send failed. 请检查 Bot 配置与连接 / Check bot configuration and connection." @@ -51,6 +54,19 @@ def send_error(error: Exception) -> str: return f"❌ {reason} (errcode={code})" +def permission_denied(error: Exception) -> bool: + return ( + isinstance(error, PermissionDeniedError) + or getattr(getattr(error, "error", error), "code", None) == "permission_denied" + or getattr(error, "data", {}).get("error", {}).get("code") == "permission_denied" + or "permission_denied" in str(error) + ) + + +def permission_notice(capability: str) -> str: + return f"❌ 缺少权限 / Permission denied: {capability}. 请成员确认插件权限 / Ask a member to confirm plugin permissions." + + class OASlackBridge(BasePlugin): def __init__(self): super().__init__() @@ -132,8 +148,6 @@ class OASlackBridge(BasePlugin): ) if not session and not matched: return - event_context.prevent_default() - event_context.prevent_postorder() new_session = session is None if new_session: timestamp = datetime.fromtimestamp(now, UTC).isoformat() @@ -161,52 +175,5 @@ class OASlackBridge(BasePlugin): await self.save(self.thread_key(session), {"session_key": key}) if not new_session and config.get("forward_followups", True): await self.to_slack(config, slack_text(text) or "[非文本消息 / Non-text message]", session["thread"]) - - async def handle_group(self, event_context): - config = self.get_config() - bot = await event_context.get_bot_uuid() - event = event_context.event - if not bot or bot != config.get("slack_bot") or str(event.launcher_id) != config.get("slack_channel_id"): - return - thread = next((part.id for part in event.message_chain if isinstance(part, message.Quote)), "") - if not thread: - return - scope = self.scope() - async with self._locks.setdefault(scope, asyncio.Lock()): - mapping = await self.load(self.key("thread", bot, str(event.launcher_id), thread)) - if not mapping: - return - key = mapping["session_key"] - session = await self.load(key) - if not session or session["thread"] != thread or session["oa_bot"] != config.get("oa_bot"): - return event_context.prevent_default() event_context.prevent_postorder() - text = plain_text(event.message_chain) - if any(isinstance(part, message.At) for part in event.message_chain): - text = re.sub(r"^<@[^>]+>\s*", "", text).strip() - now = time.time() - if text in ("/close", "!close"): - await self.close(key, session) - await self.to_slack(config, "✅ 接管已结束,恢复 AI 回复 / Takeover closed; AI replies resumed.", thread) - return - if now - session["last_user_at"] >= 48 * 3600: - await self.close(key, session) - await self.to_slack(config, "❌ 48 小时回复窗口已过 / 48-hour reply window expired", thread) - return - if session["expires_at"] <= now: - await self.close(key, session) - await self.to_slack(config, "❌ 接管已到期,恢复 AI 回复 / Takeover expired; AI replies resumed.", thread) - return - if not text: - await self.to_slack(config, "❌ 仅支持文本回复 / Only text replies are supported.", thread) - return - try: - await self.send_message( - bot_uuid=session["oa_bot"], target_type="person", target_id=session["openid"], - message_chain=message.MessageChain([message.Plain(text=from_slack(text))]), - ) - except Exception as error: - await self.to_slack(config, send_error(error), thread) - else: - await self.to_slack(config, "✅ 已发送 / Sent", thread) diff --git a/plugins/misc/OASlackBridge/manifest.yaml b/plugins/misc/OASlackBridge/manifest.yaml index 5bd69c841..ed6e8d052 100644 --- a/plugins/misc/OASlackBridge/manifest.yaml +++ b/plugins/misc/OASlackBridge/manifest.yaml @@ -4,15 +4,30 @@ metadata: author: langbot-team name: OASlackBridge repository: https://github.com/langbot-app/LangBot/tree/master/plugins/misc/OASlackBridge - version: 0.1.0 + version: 0.2.0 description: en_US: Forward Official Account keyword messages to Slack and reply from threads. zh_Hans: 公众号关键词消息转发 Slack,员工在 thread 内回复用户。 + zh_Hant: 公眾號關鍵字訊息轉發至 Slack,員工在討論串內回覆使用者。 + ja_JP: 公式アカウントのキーワードメッセージを Slack に転送し、スレッドから返信します。 + es_ES: Reenvía mensajes con palabras clave de cuentas oficiales a Slack y responde desde hilos. + ru_RU: Пересылает сообщения официального аккаунта по ключевым словам в Slack с ответами из веток. + th_TH: ส่งต่อข้อความที่มีคำสำคัญจากบัญชีทางการไปยัง Slack และตอบกลับจากเธรด + vi_VN: Chuyển tiếp tin nhắn có từ khóa từ tài khoản chính thức đến Slack và trả lời từ luồng. label: en_US: Official Account Slack Bridge zh_Hans: 公众号 Slack 桥接 + zh_Hant: 公眾號 Slack 橋接 + ja_JP: 公式アカウント Slack ブリッジ + es_ES: Puente de cuentas oficiales a Slack + ru_RU: Мост между официальным аккаунтом и Slack + th_TH: สะพานเชื่อมบัญชีทางการกับ Slack + vi_VN: Cầu nối tài khoản chính thức với Slack icon: assets/icon.svg spec: + permissions: + capabilities: [bot.message.send, storage.plugin] + workspace_operations: [] config: - name: oa_bot type: bot-selector @@ -57,6 +72,9 @@ spec: en_US: Forward follow-up messages zh_Hans: 转发接管期间的后续消息 components: + Runner: + fromDirs: + - path: components/runner/ EventListener: fromDirs: - path: components/event_listener/ diff --git a/plugins/misc/OASlackBridge/readme/README_zh_Hans.md b/plugins/misc/OASlackBridge/readme/README_zh_Hans.md index bc4df0d8d..b2429f92c 100644 --- a/plugins/misc/OASlackBridge/readme/README_zh_Hans.md +++ b/plugins/misc/OASlackBridge/readme/README_zh_Hans.md @@ -7,10 +7,26 @@ - 已认证且拥有客服消息接口权限的公众号,在 LangBot 中配置为 **Mode = auto**。其他模式无法异步发送员工回复,core 会拒绝发送。 - LangBot core 必须包含 **langbot-app/LangBot #2863 和 #2864**:公众号 `send_message`、Slack 返回 `message_id`、出站 `Quote` 指定 thread、bot thread 内回复带入站 `Quote.id`。旧版本 core 无法使用本插件。 - Slack App 已接入 LangBot,并已加入目标频道。订阅 bot events:`app_mention`、`message.channels`;私有频道还需要 `message.groups`。桥接所需 scopes:`chat:write`、`app_mentions:read`、`channels:history`,私有频道还需要 `groups:history`。保留 LangBot Slack 适配器要求的其他权限,修改 scope 后重新安装 App。Socket Mode 还需带 `connections:write` 的 App-Level Token;webhook 模式需要可访问的 LangBot 事件端点。 -- 在**两个 Bot 的消息流水线**中启用本插件,排在会回复或消费消息的其他插件之前。目标频道成员应仅包含有权回复客户的员工;频道中所有能在映射 thread 内发言的员工都可以回传消息。 +- 目标频道成员应仅包含有权回复客户的员工;频道中所有能在映射 thread 内发言的员工都可以回传消息。 + +## 配置步骤与 0.2.0 升级 + +0.2.0 的最低 Host 能力要求为:Unified API、插件安装权限、Runner `usages: [event]`、Bot Plugin processor 订阅、公众号标准发送及 Slack thread 支持;同时需要本次更新包含的 Runner 标准发送权限检查和 MessageChain 转换。缺少这些能力的旧版 Host 无法加载或运行本版本。 + +1. 使用支持 Unified API、Runner 事件处理器和 Bot Plugin processor 订阅的 LangBot。安装或升级插件后,由 Workspace 成员在插件详情页确认 `bot.message.send` 和 `storage.plugin`。0.2.0 从 compatibility mode 转为 strict;声明权限不等于获得授权,不申请 Workspace operations。 +2. 填写下方插件级配置,两个组件共用这份配置,处理器没有独立配置项。 +3. 公众号 Bot 的**主路由必须是启用了本插件的 Pipeline**,插件排在会回复或消费消息的其他插件之前。EventListener 只在 Pipeline 内运行;如果主路由是 Agent,就无法阻断接管期间的 AI 回复。 +4. 创建使用 **Slack 回复处理器** 的 Plugin processor 实例,在 Slack Bot 详情页的 **Plugin processor** 中订阅。只安装插件不会自动订阅。Slack Bot 主路由可以是任意目标,也可以设为 **discard**,无需再通过启用了本插件的 Pipeline 处理 Slack 回复。 +5. 员工在映射 thread 内回复时**不要 @bot**。处理器和主路由并行运行,不能阻止主路由回复;如果 @bot 且 Slack Bot 主路由是 AI,AI 也会回复。 + +在同一安装上升级后,0.1.0 已有会话与 thread 映射继续可用,storage key 不变。EventListener 不再处理 Slack 群消息,恢复员工回复前请完成处理器订阅。 + +回执通过事件范围的标准 `ctx.reply` 发送,沿用 Slack 来源事件的 `thread_ts`。Runner 声明 `tool_calling: true` 和 `permissions.tools: [call]`、`permissions.storage: [plugin]`;消息事件自动获得 `event_reply`,无需额外启用平台工具或安装 capability。`get_bot_uuid` 同属事件范围;跨 Bot 发送需要 `bot.message.send`,存储读写和删除需要 `storage.plugin`。权限拒绝会记日志而不输出原始异常;仍能进行事件回复时,处理器会在 Slack 提示缺少的权限。 ## 配置 +插件存储或发送 Slack 的权限被拒绝时,公众号监听器只记录警告,本条消息继续走正常 AI 流水线;关键词命中和已有接管期间的消息同样放行。只有桥接处理成功后才阻断 AI,避免缺少权限时用户收不到回复;已经转发至 Slack 的消息仍会保留。插件不会清除其他流水线插件设置的阻断标记。 + | 配置项 | 默认值 | 说明 | | --- | --- | --- | | `oa_bot` | 必填 | 公众号 Bot,必须为 auto 模式 | @@ -24,8 +40,8 @@ ## 使用方式 1. 用户发送命中关键词的消息,频道中出现根消息,包含截短的 openid、命中词、UTC 时间和原文。 -2. 员工在**这条消息的 thread 内**回复,可不 @bot。插件仅提取 `Plain` 文本,去掉引用上下文与 @bot 前缀,并将 Slack 链接、提及、频道引用及转义的 `&`、`<`、`>` 转成可读纯文本后发送给公众号用户。成功后在 thread 回一条 `✅`;失败则显示中英双语原因和微信 `errcode`。 -3. 在 thread 内发 **`!close`** 结束接管;也支持 `@bot /close`。不要直接使用裸 `/close`,Slack 可能将它当成原生 slash command,而不派发消息。 +2. 员工在**这条消息的 thread 内回复,不要 @bot**。插件仅提取 `Plain` 文本,去掉引用上下文与开头的 @bot 前缀,并将 Slack 链接、提及、频道引用及转义的 `&`、`<`、`>` 转成可读纯文本后发送给公众号用户。成功后在 thread 回一条 `✅`;失败则显示中英双语原因和微信 `errcode`。没有映射的 thread 只记录日志,不回复。 +3. 在 thread 内发 **`!close`** 结束接管;处理器也接受作为消息文本送达的 `/close`,但 Slack 可能将它当成原生 slash command,而不派发消息。 4. 关闭或超时后,普通用户消息恢复走 AI 流水线;再次命中关键词会建立新 thread。超时在下一条相关事件到达时检查,无后台定时器。员工回复不延长接管期,用户每次发言会刷新接管期和 48 小时窗口。 关闭 `forward_followups` 后,接管期间仍阻断 AI 并刷新时间戳,只是不转发后续消息。修改 Slack Bot 或目标频道后,下次用户发言时旧会话结束;需要再次命中关键词才会在新目标建立会话。 @@ -49,20 +65,25 @@ 读取存储时会枚举插件的全部 key。过期且不再被访问的会话仍会保留,并增加枚举量;目前没有定时清理。 -支持 `shared-runtime-v1` 和 `stateless-v1`,运行时边界见 `../SHARED_RUNTIME.md`。平台消息只使用标准 `send_message`,无需为插件单独提供平台密钥。 +支持 `shared-runtime-v1` 和 `stateless-v1`,运行时边界见 `../SHARED_RUNTIME.md`。两个组件共用插件存储;平台消息使用标准 `send_message` 和事件回复 API,无需为插件单独提供平台密钥。 ## 验证与打包 -安装 `langbot-plugin`、`pytest`、`pytest-asyncio`、`PyYAML` 后,在仓库根目录运行: +在仓库根目录创建独立环境,使用 Unified API SDK 快照运行: ```sh +uv venv plugins/misc/OASlackBridge/.venv +uv pip install --python plugins/misc/OASlackBridge/.venv/bin/python -r plugins/misc/OASlackBridge/requirements-dev.txt +source plugins/misc/OASlackBridge/.venv/bin/activate python -m pytest plugins/misc/OASlackBridge/tests -q python plugins/scripts/check_catalog.py +python plugins/scripts/test_repository.py +ruff check plugins/misc/OASlackBridge cd plugins/misc/OASlackBridge lbp build -o dist ``` -测试通过真实 SDK invocation binding 和 mock Host 验证消息与存储,不会访问真实微信或 Slack。真机验收需使用获授权的测试账号和专用频道:关键词触发 → 用户后续消息 → 员工不 @bot/@bot 回复 → 重启插件后继续回复 → `!close` 后恢复 AI。不要在生产客户 thread 中测试。 +测试通过真实 SDK invocation binding、RunnerContext 分派和 mock Host 验证消息与存储,不会访问真实微信或 Slack。真机验收需使用获授权的测试账号和专用频道:订阅处理器 → 关键词触发 → 用户后续消息 → 员工不 @bot 回复 → 重启插件后继续回复 → `!close` 后恢复 AI。不要在生产客户 thread 中测试。 ## 限制 diff --git a/plugins/misc/OASlackBridge/requirements-dev.txt b/plugins/misc/OASlackBridge/requirements-dev.txt new file mode 100644 index 000000000..e1e4cd86a --- /dev/null +++ b/plugins/misc/OASlackBridge/requirements-dev.txt @@ -0,0 +1,5 @@ +langbot-plugin @ git+https://github.com/langbot-app/langbot-plugin-sdk@7cc07a18081fe153a42431b28dd9118d08ffa4d6 +pytest +pytest-asyncio +PyYAML +ruff diff --git a/plugins/misc/OASlackBridge/tests/test_bridge.py b/plugins/misc/OASlackBridge/tests/test_bridge.py index 809ab2a79..d12c9dd85 100644 --- a/plugins/misc/OASlackBridge/tests/test_bridge.py +++ b/plugins/misc/OASlackBridge/tests/test_bridge.py @@ -4,16 +4,21 @@ import asyncio import base64 import importlib.util import json +import sys from pathlib import Path from types import SimpleNamespace from unittest.mock import AsyncMock, Mock import pytest +import yaml from langbot_plugin.api.entities import events +from langbot_plugin.api.definition.components.runner import RunnerContext from langbot_plugin.api.entities.builtin.platform import message from langbot_plugin.api.proxies.invocation import bind_invocation from langbot_plugin.entities.io.actions.enums import PluginToRuntimeAction as Action from langbot_plugin.entities.io.context import InstallationBinding +from langbot_plugin.entities.io.errors import ActionCallError +from langbot_plugin.api.proxies.runner import PermissionDeniedError ROOT = Path(__file__).resolve().parents[1] @@ -26,7 +31,9 @@ def load_module(path, name): bridge = load_module(ROOT / "main.py", "oa_slack_bridge") +sys.modules["main"] = bridge listener_module = load_module(ROOT / "components/event_listener/bridge.py", "oa_slack_listener") +runner_module = load_module(ROOT / "components/runner/slack_reply.py", "oa_slack_runner") CONFIG = { "oa_bot": "oa-1", "slack_bot": "slack-1", "slack_channel_id": "C-1", "keywords": ["help", "人工"], "case_sensitive": False, @@ -43,6 +50,15 @@ class Host: self.root_result = {"message_id": "1234.000001"} async def call_action(self, action, data, *args, **kwargs): + if action == getattr(self, "denied_action", None): + raise self.denial + if action == Action.CALL_TOOL: + return {"result": await self.reply(data["tool_name"], data["parameters"])} + if action == Action.CALL_PLATFORM_API: + assert data["action"] == "send_message" + data = {"bot_uuid": data["bot_uuid"], "target_type": data["params"]["target_type"], + "target_id": data["params"]["target_id"], "message_chain": data["params"]["message"]} + action = Action.SEND_MESSAGE if action == Action.GET_PLUGIN_STORAGE_KEYS: return {"keys": list(self.storage)} if action == Action.GET_PLUGIN_STORAGE: @@ -88,12 +104,48 @@ async def graph(host=None): listener = listener_module.BridgeListener() listener.plugin = plugin await listener.initialize() - return plugin, host, listener.registered_handlers + assert events.GroupMessageReceived not in listener.registered_handlers + runner = runner_module.SlackReplyProcessor() + runner.plugin = plugin + runner.bind_runtime(plugin_runtime_handler=host) + await runner.initialize() + return plugin, host, (listener.registered_handlers, runner, host) async def receive(handlers, ctx, *, group=False): - kind = events.GroupMessageReceived if group else events.PersonMessageReceived - await handlers[kind][0](ctx) + listeners, runner, host = handlers + if not group: + await listeners[events.PersonMessageReceived][0](ctx) + return + bot = await ctx.get_bot_uuid() + data = { + "type": "message.received", "bot_uuid": bot, "chat_id": ctx.event.launcher_id, + "message_chain": ctx.event.message_chain.model_dump(mode="json"), + } + run_ctx = RunnerContext.model_validate({ + "run_id": "test", "trigger": {"type": "message.received"}, + "event": {"event_id": "test", "event_type": "message.received", "source": "test", "data": data}, + "input": {}, "delivery": {"surface": "test"}, + "resources": {"storage": {"plugin_storage": True}, + "tools": [{"tool_name": "event_reply", "tool_type": "platform", "operations": ["call"]}]}, + "runtime": {}, "config": {"oa_bot": "ignored-processor-setting"}, + }) + + async def call_tool(name, parameters): + assert name == "event_reply" + if getattr(host, "reply_failure", None): + raise host.reply_failure + chain = message.MessageChain([ + *(part for part in ctx.event.message_chain if isinstance(part, message.Quote)), + message.Plain(text=parameters["text"]), + ]) + host.sent.append({"bot_uuid": bot, "target_type": "group", "target_id": ctx.event.launcher_id, + "message_chain": chain.model_dump(mode="json")}) + return {"ok": True} + + host.reply = AsyncMock(side_effect=call_tool) + ctx.results = [result async for result in runner.invoke(run_ctx)] + ctx.reply_api = host.reply def contents(payload): @@ -168,7 +220,7 @@ async def test_staff_reply_uses_plain_components_and_acknowledges(mention): assert text(host.sent[1]) == "Answer" assert thread_id(host.sent[2]) == "1234.000001" assert "✅" in text(host.sent[2]) - reply.prevent_default.assert_called_once() + reply.prevent_default.assert_not_called() @pytest.mark.asyncio @@ -215,7 +267,7 @@ async def test_staff_reply_normalizes_slack_without_interpreting_commands(mentio assert text(host.sent[2]) == "✅ 已发送 / Sent" assert thread_id(host.sent[2]) == "1234.000001" assert len(host.storage) == 2 - reply.prevent_default.assert_called_once() + reply.prevent_default.assert_not_called() @pytest.mark.asyncio @@ -287,7 +339,7 @@ async def test_timeout_releases_takeover(monkeypatch, from_staff): assert host.storage == {} if from_staff: assert "expired" in text(host.sent[-1]) - ctx.prevent_default.assert_called_once() + ctx.prevent_default.assert_not_called() assert all(payload["target_type"] == "group" for payload in host.sent) else: ctx.prevent_default.assert_not_called() @@ -411,3 +463,126 @@ async def test_channel_change_creates_new_thread(): assert len(host.storage) == 2 assert host.sent[-1]["target_id"] == "C-2" assert not thread_id(host.sent[-1]) + + +def denied(): + return ActionCallError("Host rejected the operation", { + "error": {"code": "permission_denied", "message": "Host rejected the operation"}, + }) + + +@pytest.mark.asyncio +async def test_version_010_rows_work_without_rewriting_keys(monkeypatch): + monkeypatch.setattr(bridge.time, "time", lambda: 2000) + _plugin, host, handlers = await graph() + key = "oasb:instance-1%3Aworkspace-1%3Afirst:session:oa-1:openid-sensitive-123456789" + mapping_key = "oasb:instance-1%3Aworkspace-1%3Afirst:thread:slack-1:C-1:1234.000001" + session = {"oa_bot": "oa-1", "openid": "openid-sensitive-123456789", "slack_bot": "slack-1", + "channel": "C-1", "thread": "1234.000001", "last_user_at": 1000, "expires_at": 4600} + host.storage = {key: json.dumps(session).encode(), mapping_key: json.dumps({"session_key": key}).encode()} + previous = dict(host.storage) + with bind_invocation(host, config=CONFIG, binding=binding(revision=2)): + reply = context("old session reply", bot="slack-1", thread="1234.000001") + await receive(handlers, reply, group=True) + assert host.storage == previous + assert text(host.sent[0]) == "old session reply" + assert host.sent[0]["target_id"] == session["openid"] + reply.reply_api.assert_awaited_once_with("event_reply", {"text": "✅ 已发送 / Sent"}) + assert reply.results[-1].type == "run.completed" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("missing_session", [False, True]) +async def test_unmapped_threads_log_without_reply(missing_session): + plugin, host, handlers = await graph() + with bind_invocation(host, config=CONFIG): + if missing_session: + await plugin.save(plugin.key("thread", "slack-1", "C-1", "1234.000001"), {"session_key": "missing"}) + reply = context("answer", bot="slack-1", thread="1234.000001") + await receive(handlers, reply, group=True) + assert not host.sent + reply.reply_api.assert_not_called() + assert any("Ignoring Slack" in result.data.get("text", "") for result in reply.results) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("action,command,capability", [ + (Action.GET_PLUGIN_STORAGE_KEYS, "answer", "storage.plugin"), + (Action.GET_PLUGIN_STORAGE, "answer", "storage.plugin"), + (Action.DELETE_PLUGIN_STORAGE, "!close", "storage.plugin"), + (Action.CALL_PLATFORM_API, "answer", "bot.message.send"), +]) +async def test_runner_permission_denial_logs_and_acknowledges(action, command, capability): + _plugin, host, handlers = await graph() + with bind_invocation(host, config=CONFIG): + await receive(handlers, context()) + host.denied_action, host.denial = action, denied() + reply = context(command, bot="slack-1", thread="1234.000001") + await receive(handlers, reply, group=True) + assert len(host.sent) == 2 + assert capability in text(host.sent[-1]) + assert any(capability in result.data.get("text", "") for result in reply.results) + assert reply.results[-1].type == "run.completed" + + +@pytest.mark.asyncio +async def test_denied_receipt_does_not_retry_customer_send(): + _plugin, host, handlers = await graph() + with bind_invocation(host, config=CONFIG): + await receive(handlers, context()) + host.reply_failure = denied() + reply = context("answer", bot="slack-1", thread="1234.000001") + await receive(handlers, reply, group=True) + assert len(host.sent) == 2 + assert host.sent[-1]["target_type"] == "person" + assert any("event_reply" in result.data.get("text", "") for result in reply.results) + assert reply.results[-1].type == "run.completed" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("action,existing,incoming_text", [ + (action, existing, incoming_text) + for action, existing, texts in [ + (Action.GET_PLUGIN_STORAGE_KEYS, False, ["help", "你好,请问营业时间?"]), + (Action.GET_PLUGIN_STORAGE, True, ["help", "你好,请问营业时间?"]), + (Action.SET_PLUGIN_STORAGE, False, ["help"]), + (Action.SET_PLUGIN_STORAGE, True, ["help", "你好,请问营业时间?"]), + (Action.SEND_MESSAGE, False, ["help"]), + (Action.SEND_MESSAGE, True, ["help", "你好,请问营业时间?"]), + ] + for incoming_text in texts +]) +async def test_listener_permission_denial_leaves_pipeline_open(action, existing, incoming_text, caplog): + _plugin, host, handlers = await graph() + with bind_invocation(host, config=CONFIG): + if existing: + await receive(handlers, context()) + host.denied_action, host.denial = action, denied() + incoming = context(incoming_text) + await receive(handlers, incoming) + incoming.prevent_default.assert_not_called() + incoming.prevent_postorder.assert_not_called() + assert "Permission denied" in caplog.text + assert "Host rejected" not in caplog.text + + +def test_sdk_local_permission_denial_is_recognized(): + assert bridge.permission_denied(PermissionDeniedError("Plugin storage is not authorized.")) + assert not bridge.permission_denied(RuntimeError("network failed")) + + +def test_component_and_permission_manifest(): + plugin = yaml.safe_load((ROOT / "manifest.yaml").read_text()) + runner = yaml.safe_load((ROOT / "components/runner/slack_reply.yaml").read_text()) + assert plugin["metadata"]["version"] == "0.2.0" + assert plugin["spec"]["permissions"] == { + "capabilities": ["bot.message.send", "storage.plugin"], "workspace_operations": [], + } + assert runner["spec"]["usages"] == ["event"] + assert runner["spec"]["events"] == ["message.received"] + assert runner["spec"]["permissions"] == {"tools": ["call"], "storage": ["plugin"]} + assert runner["spec"]["config"] == [] + locales = {"en_US", "zh_Hans", "zh_Hant", "ja_JP", "es_ES", "ru_RU", "th_TH", "vi_VN"} + for manifest in (plugin, runner): + for field in ("label", "description"): + assert set(manifest["metadata"][field]) == locales diff --git a/plugins/scripts/check_catalog.py b/plugins/scripts/check_catalog.py index 73a8bd3ff..14ba3d046 100644 --- a/plugins/scripts/check_catalog.py +++ b/plugins/scripts/check_catalog.py @@ -32,7 +32,13 @@ def check_catalog(root: Path = ROOT) -> list[dict]: raise ValueError(f'Duplicate plugin ID: {identity}') identities.add(identity) kinds = manifest['spec']['components'] - category = 'Runner' if 'Runner' in kinds else 'KnowledgeEngine' if 'KnowledgeEngine' in kinds else 'misc' + category = ( + 'Runner' + if 'Runner' in kinds and 'EventListener' not in kinds + else 'KnowledgeEngine' + if 'KnowledgeEngine' in kinds + else 'misc' + ) assert plugin.parent.name == category, path assert metadata['repository'] == REPOSITORY + plugin.relative_to(root).as_posix(), path assert re.fullmatch(r'\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?', str(metadata['version'])), path diff --git a/plugins/scripts/test_repository.py b/plugins/scripts/test_repository.py index 2af5bb192..20de663be 100644 --- a/plugins/scripts/test_repository.py +++ b/plugins/scripts/test_repository.py @@ -86,6 +86,13 @@ class RepositoryTests(unittest.TestCase): for entry in catalog: self.assertIn(f'({entry["path"]}/README.md)', readme) + def test_pipeline_bridge_with_event_runner_remains_misc(self): + entry = next(item for item in check_catalog() if item['id'] == 'langbot-team/OASlackBridge') + self.assertEqual(entry['category'], 'misc') + self.assertEqual(entry['path'], 'misc/OASlackBridge') + manifest = yaml.safe_load((ROOT / entry['path'] / 'manifest.yaml').read_text()) + self.assertEqual(set(manifest['spec']['components']), {'EventListener', 'Runner'}) + def test_original_identities_are_preserved(self): imported = json.loads((ROOT / 'SOURCE.json').read_text()) current = {entry['id']: entry['path'] for entry in check_catalog()} diff --git a/src/langbot/pkg/api/application/plugin_permissions.py b/src/langbot/pkg/api/application/plugin_permissions.py index 4250c66d3..b1ac51c84 100644 --- a/src/langbot/pkg/api/application/plugin_permissions.py +++ b/src/langbot/pkg/api/application/plugin_permissions.py @@ -184,6 +184,8 @@ async def authorize_action(ap, binding, action: str, data: dict) -> None: if definition is not None and definition.scope == 'event': return capability = ACTION_CAPABILITIES.get(action) + if action == PluginToRuntimeAction.CALL_PLATFORM_API.value and data.get('action') == 'send_message': + capability = 'bot.message.send' if action == PluginToRuntimeAction.LIST_TOOLS.value: if not set(effective_grants(ap, setting)['capabilities']) & {'plugin_tools', 'mcp', 'sandbox'}: fail('permission_denied', 'No tool capabilities have been granted') diff --git a/src/langbot/pkg/plugin/handler.py b/src/langbot/pkg/plugin/handler.py index 6d380d269..b56315999 100644 --- a/src/langbot/pkg/plugin/handler.py +++ b/src/langbot/pkg/plugin/handler.py @@ -1491,6 +1491,16 @@ class RuntimeConnectionHandler(handler.Handler): """Call a platform adapter API""" if data.get('run_id') is not None and (data.get('context_tool') or data.get('file_ids') is not None): return await call_run_platform_api(data) + if data.get('action') == 'send_message' and data.get('bot_uuid'): + params = data.get('params') or {} + return await send_message( + { + **data, + 'target_type': params['target_type'], + 'target_id': params['target_id'], + 'message_chain': params['message'], + } + ) action_context, _ = await self._require_plugin_action_context() bot_uuid = data.get('bot_uuid') if not bot_uuid and data.get('run_id'): diff --git a/tests/integration/plugin/test_execution_api_routing.py b/tests/integration/plugin/test_execution_api_routing.py index 90202972f..5b130f2c6 100644 --- a/tests/integration/plugin/test_execution_api_routing.py +++ b/tests/integration/plugin/test_execution_api_routing.py @@ -137,6 +137,35 @@ def _is_union(t: typing.Any) -> bool: return isinstance(t, types.UnionType) or typing.get_origin(t) in (typing.Union, types.UnionType) +@pytest.mark.asyncio +async def test_runner_standard_send_with_minimal_installation_grants(test_host): + host = test_host + permissions = {'workspace_operations': [], 'capabilities': ['bot.message.send', 'storage.plugin']} + host.setting.permission_declaration = permissions + host.setting.permission_grants = permissions + host.setting.permission_snapshot = permissions + adapter = SimpleNamespace(send_message=AsyncMock(return_value={'message_id': 'sent'})) + host.ap.platform_mgr = SimpleNamespace(get_bot_by_uuid=AsyncMock(return_value=SimpleNamespace(adapter=adapter))) + + class Transport: + async def call_action(self, action, data, *args, **kwargs): + response = await host.handler.actions[action.value](data) + assert response.code == 0, response.message + return response.data + + ctx = RunnerContext.model_construct( + run_id='run-123', + runtime=SimpleNamespace(deadline_at=None), + resources=AgentResources(), + ) + api = RunnerAPIProxy(ctx, Transport()) + chain = platform_message.MessageChain([platform_message.Plain(text='customer reply')]) + result = await api.send_message('bot-1', 'person', 'openid', chain) + assert result == {'message_id': 'sent'} + adapter.send_message.assert_awaited_once_with('person', 'openid', chain) + assert isinstance(adapter.send_message.await_args.args[2], platform_message.MessageChain) + + def _dummy_for_type(annotation: typing.Any) -> typing.Any: if _is_union(annotation): args = typing.get_args(annotation) diff --git a/tests/unit_tests/api/test_plugin_permissions.py b/tests/unit_tests/api/test_plugin_permissions.py index 8edd1eafa..b397051a4 100644 --- a/tests/unit_tests/api/test_plugin_permissions.py +++ b/tests/unit_tests/api/test_plugin_permissions.py @@ -279,6 +279,29 @@ async def test_protocol_capabilities_and_cross_workspace_bot_are_enforced(app, m ) +@pytest.mark.asyncio +@pytest.mark.parametrize('granted', [True, False]) +@pytest.mark.parametrize('action', ['send_message', 'delete_message', 'call_platform_api']) +async def test_standard_send_uses_message_capability_without_generic_platform_access(app, monkeypatch, granted, action): + from langbot.pkg.api.application import plugin_permissions + + capabilities = ['bot.message.send'] if granted else [] + declaration = {'workspace_operations': [], 'capabilities': capabilities} + monkeypatch.setattr( + plugin_permissions, 'load_installation', AsyncMock(return_value=installation(declaration, declaration)) + ) + app.persistence_mgr.execute_async.return_value = SimpleNamespace(first=lambda: ('bot',)) + binding = SimpleNamespace(workspace_uuid='workspace', installation_uuid='install') + data = {'run_id': 'run', 'bot_uuid': 'bot', 'action': action} + if action == 'send_message' and granted: + await plugin_permissions.authorize_action(app, binding, PluginToRuntimeAction.CALL_PLATFORM_API.value, data) + else: + with pytest.raises(ApplicationAPIException) as error: + await plugin_permissions.authorize_action(app, binding, PluginToRuntimeAction.CALL_PLATFORM_API.value, data) + expected = 'bot.message.send' if action == 'send_message' else 'bot.platform_api' + assert error.value.error.details['denied_capabilities'] == [expected] + + @pytest.mark.asyncio async def test_platform_tool_fallback_does_not_bypass_installation_grants(app, monkeypatch): from langbot.pkg.api.application import plugin_permissions