Channels: push external events (chat, webhooks, inbox) into a running agent session

Đang mở
#6,414 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
12/100
Loại issue
Tính năng
Độ rõ ràng
Cần làm rõ
Mức độ hoạt động
Sôi nổi
Công nghệ
python
Lĩnh vực
ai, cli

Hướng nghiên cứu

This is a design proposal, not a scoped task, so start by reading the Current state and Proposed design sections and the cited files: src/praisonai-agents/praisonaiagents/agent/message_steering.py and the MCP transports in praisonaiagents/mcp/ (mcp.py:113 and siblings). Done would mean agreed scope and a maintainer-approved design for the ChannelInbox and MCP notification handling, not an implementation. Ask on the thread which phase to take first before writing code.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

bug claude documentation enhancement origin/outsider security

Summary

Add "channels": a way for an external source (a chat bot, a webhook, a local inbox) to push an event into an agent session that is already running and interactive (praisonai code, the TUI, praisonai chat, or a session on the warm runtime), so the agent reacts in that same session, with its files, history and context, and can answer back through the same channel.

This is different from three things PraisonAI already has:

  • starting a new agent run per inbound message (bots, gateway, webhook triggers);
  • steering a turn that is running right now (message_steering, praisonai attach --message);
  • an attached second client watching a session (praisonai attach).

Background and motivation

A developer has a long praisonai code session open on a repository. CI fails, an error tracker fires, or they send a message from their phone. Today each of those either starts a fresh agent with none of that session's context (bots / gateway / webhook routes), or is lost because nothing is listening. The session that already knows what they were debugging cannot be reached.

What Claude Code shipped

Claude Code shipped "Channels" as a research preview:

The contract, as documented:

  1. A channel is an MCP server (stdio, spawned by the client) that declares capabilities.experimental["claude/channel"] = {}. Presence of that key registers a notification listener.
  2. The server emits notifications/claude/channel with params: {content: string, meta?: Record<string,string>}. Meta keys must be identifiers (letters, digits, underscore); others are dropped.
  3. The event reaches the model wrapped as <channel source="<server name>" key="value" ...>content</channel>. The terminal shows a one-line ← source: ... summary.
  4. Events queue into the session and are processed in order; several events that arrive while the agent is busy are delivered together on the next turn. Notifications are not acknowledged; if the session did not opt the server in, events are dropped silently.
  5. Two-way channels expose an ordinary MCP tool (e.g. reply(chat_id, text)); the server's instructions string tells the model when to call it.
  6. Optional permission relay: a server that declares claude/channel/permission receives notifications/claude/channel/permission_request (request_id of five letters a-z without l, tool_name, description, input_preview) and sends back notifications/claude/channel/permission with {request_id, behavior: "allow" | "deny"}. The local dialog stays open; the first answer wins; a verdict with an unknown or reused id is dropped. description and input_preview are sanitised (bidi/invisible characters neutralised, whitespace folded, length capped with an elision marker, known credential tokens masked) before relay.
  7. Opt-in and security: being configured as an MCP server is not enough; the session must be started with claude --channels plugin:<name>@<marketplace> (or --dangerously-load-development-channels server:<name> for local development, after a warning dialog). Organisations have a master switch channelsEnabled and an allowedChannelPlugins allowlist. Every shipped channel gates on a sender allowlist (not room id), bootstrapped by pairing codes; the docs call an ungated channel a prompt-injection vector.

For contrast: Codex CLI has open requests for the same thing (openai/codex#15299, #17543, #18056, #33556); Gemini CLI has outbound hooks only; Cursor wakes cloud agents from webhooks and Slack (Cursor Automations) rather than injecting into a local running session.

Current state in PraisonAI (checked on main at e41a23e040)

What exists and can be reused
Piece Where What it does
Mid-run steering src/praisonai-agents/praisonaiagents/agent/message_steering.py:21 (MessageSteering), :190 (steer()), :282 (_drain_steering_messages); drained between tool iterations via steering_drain in agent/chat_mixin.py:4218-4221 and :4957-4960 Queues text into a turn that is running and folds it in at the next iteration.
Warm runtime live control src/praisonai-code/praisonai_code/runtime/server.py:118-127 (_enable_live_control), :312-330 (WarmRuntime.steer), :526-556 (POST /sessions/{id}/steer and /interrupt), :474-477 (bearer-token auth), SSE events at GET /sessions/{id}/events Lets a second client steer or interrupt a live turn of a praisonai run --attach <id> session on the daemon.
Attach CLI src/praisonai-code/praisonai_code/cli/commands/attach.py:1-17, :78 praisonai attach --message "..." <id> (from #5846).
Bot busy-mode steer src/praisonai-bot/praisonai_bot/bots/_run_control.py:246-263; wired only in bots/telegram.py:160-168 A follow-up chat message during a bot's own run is injected into that bot-owned agent (falls back to queue).
Gateway / bots src/praisonai-bot/praisonai_bot/gateway/server.py:4881 (agent.chat(content, ...)), :10634-10640 (bot._session.chat(...)) Every inbound message runs a turn on a gateway- or bot-hosted agent session.
Webhook triggers src/praisonai-bot/praisonai_bot/bots/webhook.py:130-180 Renders a POSTed payload into a prompt and starts an agent run (from #2281); payload is fenced as untrusted via praisonaiagents/tools/trust.py:131 (wrap_request_payload) and :159 (request_payload_notice).
Signatures and replay src/praisonai-bot/praisonai_bot/bots/webhook_security.py:53 (verify_hmac), :160 (enforce_webhook_verification); src/praisonai-agents/praisonaiagents/gateway/hooks.py:219 (verify_webhook_signature, schemes incl. hmac_timestamped, tolerance_seconds) HMAC verification with timestamp tolerance (from #5866).
Sender allowlist / pairing src/praisonai-agents/praisonaiagents/bots/config.py:22,42,120 (allowed_users, owner for pairing); src/praisonai-bot/praisonai_bot/bots/_config_schema.py:515,597,766; gateway/pairing.py Per-bot allowlist and pairing.
Rate limit src/praisonai-bot/praisonai_bot/bots/_rate_limit.py:29,51; gateway/rate_limiter.py:30 Per-sender and auth rate limits.
Untrusted route down-scoping src/praisonai-bot/praisonai_bot/gateway/server.py:9185-9200 Per-route trust / allow_tools / deny_tools; dangerous tools are not advertised on untrusted routes (#2298).
Kill switch src/praisonai-bot/praisonai_bot/bots/_config_schema.py:952-953 Gateway emergency-stop / pause brake (#4220).
Approval bridges bots/_slack_approval.py:40, bots/_telegram_approval.py:45, bots/_discord_approval.py, bots/_http_approval.py:42, gateway/exec_approval.py, gateway/gateway_approval.py Remote approve/deny of risky tool calls for gateway/bot runs.
What is missing
  1. The interactive session cannot be reached from outside. praisonai code / the TUI (src/praisonai-code/praisonai_code/cli/interactive/async_tui.py) has an in-process prompt queue (:390, drained at :2438-2440) fed only by the local keyboard and slash commands. It does not enable message_steering and does not register with the warm runtime, so neither attach --message nor any bot or webhook can deliver into it.
  2. Steering only works while a turn is running. WarmRuntime.steer returns False when no turn is live (runtime/server.py:312-317; the HTTP endpoint answers "no live run for session", :554). An idle session cannot be woken by an event; there is no "queue for the next turn and start it" behaviour.
  3. The MCP client drops server-initiated notifications. Every client constructs ClientSession(read, write) with no message_handler: src/praisonai-agents/praisonaiagents/mcp/mcp.py:113 (stdio), mcp_sse.py:150, mcp_http_stream.py:603, mcp_websocket.py:430. Nothing in praisonaiagents/mcp/ handles notifications or experimental capabilities, so an MCP server cannot push anything into an agent, and the existing Claude Code channel servers cannot be reused.
  4. Pushed text is labelled as the user. Steering notes are formatted as [USER GUIDANCE] / [URGENT USER GUIDANCE] / [INTERRUPT USER GUIDANCE] ... follow this guidance immediately (agent/message_steering.py:243-256). If a bot or webhook were wired into steering as it stands, remote content would arrive with user authority and no source, sender or untrusted label. The webhook trigger path fences content (webhook.py:138-180), the steering path does not.
  5. Bots and gateway never inject into a session they do not host. They run their own agents (gateway/server.py:4881, :10634-10640); the one steer path (_run_control.py:246-263) only targets the bot's own in-flight run and is wired for Telegram only.
  6. No per-session opt-in, reply tool, or remote approval for the interactive session. The approval bridges serve gateway/bot runs; there is no relay of the TUI's approval prompt to a channel.

Proposed design

1. Core: a channel event and an inbox on the agent session

In praisonai-agents (protocols only; no heavy imports):

@dataclass(frozen=True)
class ChannelEvent:
    source: str                 # channel name, set by the host, never by the sender
    content: str
    meta: dict[str, str]        # identifier keys only; others dropped
    sender_id: str | None       # verified sender, set by the adapter
    received_at: float
    trust: Literal["untrusted", "operator"] = "untrusted"

class ChannelInbox(Protocol):
    def push(self, event: ChannelEvent) -> bool: ...     # False when rejected
    def drain(self) -> list[ChannelEvent]: ...
  • While a turn runs, events are drained through the existing steering_drain seam (chat_mixin.py:4218), but rendered by a new formatter, not _format_steering_note.
  • When the session is idle, the host starts a turn from the queued events (batched, in order), matching the "delivered together on the next turn" behaviour.
  • Rendering (fixed, outside any fence):
    <channel source="telegram" sender="12345" chat_id="..." trust="untrusted">...</channel> plus a one-line notice that the content is remote input to be treated as data, reusing tools/trust.py (wrap_request_payload, request_payload_notice).
2. MCP notification handling (compatible with Claude Code channel servers)
  • Pass a message_handler to ClientSession in all four transports (mcp.py:113, mcp_sse.py:150, mcp_http_stream.py:603, mcp_websocket.py:430).
  • After initialize(), read the server's capabilities.experimental. If it declares claude/channel (accept a neutral alias such as praisonai/channel too) and the session opted that server in, route notifications/claude/channel {content, meta} to the session's ChannelInbox with source = the configured server name.
  • Deliver the server's instructions string to the model as context, as for any MCP server.
  • Optional, later: claude/channel/permission relay (see Security).
  • Result: the published Telegram / Discord / iMessage / fakechat channel servers would work unchanged with praisonai code.
3. Channel adapters that reuse what exists
  • Webhook / inbox: the existing webhook route machinery (bots/webhook.py, webhook_security.py) gains a target session:<id> alongside "start a run": a verified POST becomes a ChannelEvent pushed into a live session instead of a new run.
  • Bots / gateway: a bot binding can target a running session (deliver_to: session:<id>) instead of its own agent. The bot keeps doing sender gating, pairing, rate limiting and outbound delivery; the gateway forwards the event to the session's inbox over the runtime's authenticated local API.
  • Local inbox: praisonai channel send <session> "text" and a local file/socket inbox for scripts, using the same path.
4. Reply tool

Each two-way channel exposes channel_reply(chat_id, text) (an MCP tool for MCP channels; a built-in tool for bot/gateway channels that calls the existing outbound delivery, bots/_delivery.py, delivery.py). It may only reply to a chat_id that arrived in an event during this session (no arbitrary destinations; consistent with the egress attestation of #6084). The terminal shows that a reply was sent.

5. Session wiring
  • TUI / praisonai code / praisonai chat: --channels <name> [<name>...] opts channels in for this session only. The TUI registers its session with the warm runtime (or opens its own local authenticated endpoint) so adapters can reach it, enables the inbox, shows each inbound event as ← telegram (12345): ..., and adds /channels (list, pause, resume, mute one).
  • Warm runtime: POST /sessions/{id}/channel (bearer auth as today, server.py:474-477) accepts a ChannelEvent; unlike /steer it queues when idle and starts the next turn.
  • Python API: Agent(..., channels=[...]) / agent.channel_inbox.push(event) for embedders.
6. Config example
# .praisonai/channels.yaml  (nothing runs unless named with --channels)
channels:
  enabled: true                    # master switch; false blocks every channel
  ci:
    type: webhook
    listen: 127.0.0.1:8788
    verify: { hmac: { header: X-Signature-256, secret: ${CI_WEBHOOK_SECRET}, scheme: hmac_timestamped, max_age_seconds: 300 } }
    rate_limit: { per_minute: 10, burst: 3 }
    trust: untrusted
  phone:
    type: telegram                  # reuses praisonai-bot's Telegram adapter
    token: ${TELEGRAM_BOT_TOKEN}
    allowed_senders: ["123456789"]  # sender ids, not chat ids; pairing adds to this
    reply: true
    approvals: relay                # remote approve/deny via the existing bridge
  claude-compatible:
    type: mcp                       # any MCP server declaring claude/channel
    server: telegram                # name from the MCP config
praisonai code --channels ci phone

Security

Channel content is remote input in front of an agent that has shell and file tools, so this must be safe by default.

  1. Per-session opt-in. Configuration alone never delivers anything; a channel must be named with --channels (or the API equivalent) for that session. A master switch (channels.enabled: false, and an env override) blocks all channels.
  2. Sender allowlist. Gate on the verified sender id, never the room or chat id (in a group, gating on the room lets anyone in it inject). Bootstrap with the existing pairing flow (gateway/pairing.py, bots/config.py:120). Unknown senders are dropped and logged; no reply that confirms the bot exists beyond the pairing code.
  3. Message signing and max age. Webhook and inbox channels require HMAC verification (reuse verify_hmac / verify_webhook_signature with hmac_timestamped) and reject events older than max_age_seconds (default 300) or with a seen nonce/id (reuse the ingress idempotency store, bots/_idempotency.py). Unsigned webhooks are refused unless the listener is bound to 127.0.0.1 and the user sets an explicit allow_unsigned_localhost: true.
  4. Kill switch. /channels pause, praisonai channel stop <session>, and the existing gateway emergency stop (_config_schema.py:952) stop delivery immediately; events received while paused are dropped, not queued for later.
  5. Rate limit. Per channel and per sender, reusing bots/_rate_limit.py; burst coalescing as in #5867. Over-limit events are dropped with one notice to the session, not one per event.
  6. Untrusted labelling. Every event is rendered with its source, sender and trust="untrusted", inside the existing data fence (tools/trust.py), never as [USER GUIDANCE]. Channel text cannot carry slash commands or @file mentions (same rule as the TUI's untrusted prompts, async_tui.py:391, and #5019). Meta keys are restricted to identifiers and values are neutralised (praisonaiagents.session.context.neutralize_untrusted_text).
  7. Channel content never authorises a risky tool on its own. A tool call made in a turn that contains channel content is treated as originating from untrusted input: approval-required tools still require approval, and the "allow always" / auto-approve modes do not apply to such turns unless the user sets an explicit per-channel trust: operator. Per-channel allow_tools / deny_tools reuse the route down-scoping of gateway/server.py:9185-9200.
  8. Approvals. Risky actions go to the local approval prompt and, if the channel opts in, to the remote approver through the existing bridges (_telegram_approval.py, _slack_approval.py, _discord_approval.py, _http_approval.py). Use short random request ids, first answer wins, unknown or reused ids are dropped, and the relayed description/preview is sanitised and credential-masked (as Claude Code does). Only allowlisted senders can answer.
  9. Audit log. Every event (accepted or dropped, with the reason), every reply, and every remote verdict is appended to the session's audit trail (see #5975) with channel, sender, time, hash of content, and the resulting turn id.

Acceptance criteria

  • praisonai code --channels ci with a webhook channel: a signed POST arrives in the open TUI session, is shown as ← ci: ..., and the agent acts on it with the session's existing history.
  • An event sent while the session is idle starts a turn; events sent during a turn are folded in at the next tool iteration; several events are delivered in order.
  • An MCP server that declares claude/channel and emits notifications/claude/channel delivers into the session when opted in, and is ignored when not opted in (and the tools still work).
  • The Claude Code fakechat server works unchanged against praisonai code --channels.
  • Reply tool sends to a chat_id seen in this session only; any other chat_id is refused.
  • Remote approval: a risky tool call triggered from a channel event waits for approval, can be answered locally or remotely; a forged or reused request id has no effect.
  • Security defaults hold: an unlisted sender, a bad signature, an expired timestamp, a replayed id, a paused channel and an over-limit burst are each dropped and logged, and none reaches the model.
  • Channel content is rendered with trust="untrusted" and never as [USER GUIDANCE].

Tests

  • Unit: ChannelEvent rendering (meta key filtering, value neutralisation, fence present); inbox ordering and batching; idle vs live delivery.
  • MCP: an in-process stdio test server that declares claude/channel and emits notifications; assert delivery with opt-in, silent drop without opt-in, and that message_handler is wired in all four transports.
  • Security (each must fail without the guard): unknown sender, room-id spoof in a group, bad HMAC, expired timestamp, replayed id, rate-limit burst, kill switch, auto-approve not applied to a channel-originated risky tool call, reply to an unseen chat_id.
  • Integration: webhook → running praisonai code session (headless TUI harness) → agent edits a file → reply delivered; Telegram adapter with a mocked Bot API.

Related

Ngôn ngữ chính
Python
Star
9.3k
Fork
1.5k
Merge trung bình
1 ngày 5 giờ
Pull request đã merge (30 ngày)
520

Chuẩn bị môi trường

Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của MervinPraison/PraisonAI

Tất cả issue của MervinPraison/PraisonAI

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.