Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions docs/system-specs/modules/messaging.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/system-specs/modules/subagent.md
Original file line number Diff line number Diff line change
Expand Up @@ -3767,7 +3767,7 @@ Claude Code's Workflow agents are native subagents too; a Workflow agent's card
|---|---|---|---|
| Dashboard (`dashboard:*`) | Append as user message + broadcast via WS | TUI/web re-injects via `sendMessage` → LLM round-trip | LLM's response summarizing the result |
| Slack (`slack:*`, a parent with a mapped Slack thread, or a legacy bare-ts key) | Inject into the parent ACP session (`_inject_with_retry`, up to `_MAX_INJECT_ATTEMPTS`), then post the synthesized reply into that Slack thread, in the session's stored channel or else the owner DM + dashboard notification | _(none)_ | LLM's synthesized reply in the Slack thread |
| Non-Slack channel (`telegram:*`, `discord:*`, `unified:*`, …) | Inject into the parent ACP session, then send the synthesized reply through the governed cross-surface transport ladder (`_deliver_channel_reply` → `_resolve_channel_target` → `MessagingTransport.send_message`) + dashboard notification. Target resolution: origin link (recorded by Discord's inbound dispatch) → non-Slack mirror link (e.g. Telegram `/link`) → for **direct (1:1) sessions only**, the stored `"{namespace}:{user_id}"` channel value, resolved to a postable conversation via `transport.resolve_configured_target`. Group/forum sessions without an origin/mirror link, channels whose dispatcher records neither, and denied/unsupported egress all degrade to notification-only — never a cross-conversation send. | _(none)_ | LLM's synthesized reply in the channel conversation |
| Non-Slack channel (`telegram:*`, `discord:*`, `unified:*`, …) | Inject into the parent ACP session, then send the synthesized reply through the governed cross-surface transport ladder (`_deliver_channel_reply` → `_resolve_channel_target` → `MessagingTransport.send_markdown`, since the reply is the agent's markdown) + dashboard notification. Target resolution: origin link (recorded by Discord's inbound dispatch) → non-Slack mirror link (e.g. Telegram `/link`) → for **direct (1:1) sessions only**, the stored `"{namespace}:{user_id}"` channel value, resolved to a postable conversation via `transport.resolve_configured_target`. Group/forum sessions without an origin/mirror link, channels whose dispatcher records neither, and denied/unsupported egress all degrade to notification-only — never a cross-conversation send. | _(none)_ | LLM's synthesized reply in the channel conversation |
| Other machine parent with no channel namespace or Slack thread (e.g. `taskrunner:*`) | Inject into the parent ACP session; no channel post | _(none)_ | Nothing in any channel |
| Cron/no parent | Dashboard notification only | _(none)_ | Notification panel entry |

Expand Down
9 changes: 8 additions & 1 deletion src/kiro_crew/dashboard/chat_compaction_notice.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ async def _deliver_via_transport(
if target is None:
return
resolved, transport = target
# The fixed compaction wording is markdown (its commands are code spans on the
# channels that take them); caller text is sent as written.
markdown = text is None
if text is None:
text = notice_text(resolved.channel_type, pct, success=success, outcome=outcome)
# Outside the best-effort ``try``: ``redact_via_context`` re-raises an invalid
Expand All @@ -316,7 +319,11 @@ async def _deliver_via_transport(
parts = await channel_egress_parts(text, transport.capabilities)
try:
await send_channel_parts(
transport, resolved.channel_id, parts, thread_id=resolved.thread_id
transport,
resolved.channel_id,
parts,
thread_id=resolved.thread_id,
markdown=markdown,
)
except Exception:
logger.debug(
Expand Down
9 changes: 6 additions & 3 deletions src/kiro_crew/dashboard/chat_turn/recipient.py
Original file line number Diff line number Diff line change
Expand Up @@ -984,8 +984,8 @@ async def _deliver_cross_surface_reply(
text, images, notes = await _cross_surface_images(
state, session_key, link.channel_type, assistant_text, limits
)
# Strip, display-redact, number the ``[OPTIONS:]`` choices (``send_message``
# takes none, so the mirror builds no button), chunk and send: the shared
# Strip, display-redact, number the ``[OPTIONS:]`` choices (neither send takes
# any, so the mirror builds no button), chunk and send: the shared
# unattended-egress leg, ``messaging.egress``. Chunking keeps a long reply
# whole rather than hard-truncated by the transport (Telegram caps at 4096).
# An answer that was nothing but images sends only the images.
Expand All @@ -995,7 +995,10 @@ async def _deliver_cross_surface_reply(
else []
)
try:
await send_channel_parts(transport, link.channel_id, parts, thread_id=link.thread_id)
# The reply is the agent's markdown; the image notes below are host text.
await send_channel_parts(
transport, link.channel_id, parts, thread_id=link.thread_id, markdown=True
)
await _send_mirror_images(transport, link, images, notes)
if notes:
# A follow-up rather than appended text: prose after an
Expand Down
28 changes: 22 additions & 6 deletions src/kiro_crew/messaging/egress.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""The one redact -> chunk -> send leg for unattended channel egress.

Three legs push text into a non-Slack channel conversation without passing a
renderer and redact it with the context-aware ``redact_via_context`` pair: the
reply renderer and redact it with the context-aware ``redact_via_context`` pair: the
dashboard reply mirror (``chat_runner._deliver_cross_surface_reply``),
the proactive completion leg for subagent and cron output
(``GatewayOrchestrator._deliver_channel_reply``) and the compaction notice
Expand All @@ -15,22 +15,30 @@
1. **Strip trailing control-tag lines.** These legs carry output authored under
dashboard rules to a client that renders HTML comments literally.
Strip-then-redact matches ``display_safe``.
2. **Redact in DISPLAY form** (``redact_for_display``). No renderer runs on this
path, and a renderer is where a turn normally gets that floor; a literal-only
2. **Redact in DISPLAY form** (``redact_for_display``). No reply renderer runs on
this path (Telegram's ``send_markdown`` converts a markdown part at step 5, after
this pass), and a renderer is where a turn normally gets that floor; a literal-only
scan lets a markdown-collapse credential (``AKIA**...**``, which the client
renders whole) reach the channel. ``redact_via_context`` is the redactor rather
than the neutral ``display_safe``: it is context-aware, so a loaded companion's
extra credential patterns apply, and the shared sink's default pair would drop
them.
3. **Optionally number ``[OPTIONS:]`` choices** (``render_options_as_text``):
``send_message`` takes no choices, so a leg that asks for it ships a numbered
neither send takes choices, so a leg that asks for it ships a numbered
list rather than the raw marker.
4. **Chunk in the transport's own unit** (``chunk_for_transport``: bytes for a
byte-capped channel such as Webex, chars otherwise), fence-safe, off the loop.
The seam check grades with the SAME ``redact_via_context`` pair as step 2: a
companion-contributed credential split across a seam is invisible to the
narrower default pair and would ship whole across two adjacent messages.
5. **Send each part** to the caller's conversation and thread.
5. **Send each part** to the caller's conversation and thread. A caller whose text
is markdown (the mirrored reply, an agent's cron or sub-agent result, the fixed
compaction notice) passes ``markdown=True`` and the part goes through
``send_markdown``, which a channel whose plain send shows markup literally
(Telegram) renders as its reply renderer would; every other transport's
``send_markdown`` is its ``send_message``. Host text (failure, crash and pause
alerts, task-run and approval notices, the memory-guard notice) keeps the plain
send, so a traceback or stderr arrives as written.

Resolution, governance vetting, DM-target resolution and logging stay with the
caller: they differ per leg, and each leg's SEL trail names its own producer.
Expand Down Expand Up @@ -80,9 +88,16 @@ async def send_channel_parts(
*,
thread_id: str | None,
require_confirmation: bool = False,
markdown: bool = False,
) -> bool:
"""Send *parts* in order to one vetted conversation. Step 5 of the contract.

With *markdown*, each part goes through ``send_markdown``: the caller vouches
that the text is markdown (an agent's reply or result). Without it, the plain
``send_message`` sends it as written, which host text needs: a failure alert's
traceback holds ``__init__`` and ``2**10``, and a markdown render would rewrite
them.

With *require_confirmation*, the send stops at the first part the transport
does not confirm (``delivery_confirmed`` owns which id convention it follows)
and returns False: the remaining chunks of a message whose head never landed
Expand All @@ -95,7 +110,8 @@ async def send_channel_parts(
propagate while still treating a transport failure as best-effort.
"""
for part in parts:
sent = await transport.send_message(conversation_id, part, thread_id=thread_id)
send = transport.send_markdown if markdown else transport.send_message
sent = await send(conversation_id, part, thread_id=thread_id)
if require_confirmation and not delivery_confirmed(transport.capabilities, sent):
return False
return True
1 change: 1 addition & 0 deletions src/kiro_crew/slack/gateway_runtime/cron_delivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ async def _deliver_cron_agent_result(
f"{channel_caption}\n\n{result_text}" if channel_caption else result_text,
actor_key=session_key,
pin=(job.channel_type, job.target_id),
markdown=True,
)
except Exception:
# The job SUCCEEDED. Letting a delivery error reach the
Expand Down
8 changes: 7 additions & 1 deletion src/kiro_crew/slack/gateway_runtime/delivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ async def _deliver_cron_to_channel(
*,
actor_key: str,
pin: tuple[str, str] | None = None,
markdown: bool = False,
) -> bool:
"""Deliver cron output to the non-Slack channel that owns *origin_key*.
Expand Down Expand Up @@ -300,6 +301,10 @@ async def _deliver_cron_to_channel(
*actor_key*, the job's own key. A script run passes the pair it launched with
as *pin*, so its output goes where its grant fingerprint bound it. A pin whose
job is gone delivers nothing, never to the origin.
*markdown* picks the send on either leg, the pin's or the origin's: True for an
agent's result, False for host text such as a failure alert or script output,
which must arrive as written.
"""
if not text.strip():
return False
Expand All @@ -318,6 +323,7 @@ async def _deliver_cron_to_channel(
text,
caller_session=actor_key,
request_app=app,
markdown=markdown,
)
return sent.status == 200
if not origin_key:
Expand Down Expand Up @@ -359,7 +365,7 @@ async def _deliver_cron_to_channel(
)
return False
return await self._deliver_channel_reply(
origin_key, text, resolved_link=resolved, caller="cron"
origin_key, text, resolved_link=resolved, caller="cron", markdown=markdown
)


Expand Down
8 changes: 7 additions & 1 deletion src/kiro_crew/slack/gateway_runtime/result_egress.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ async def _deliver_cron_response(
assert self.sessions is not None
# Resolved before the Slack leg so a Slack-less install still delivers.
delivered = await self._deliver_cron_to_channel(
self._cron_origin_key(parent_key), text, actor_key=parent_key
self._cron_origin_key(parent_key), text, actor_key=parent_key, markdown=True
)
# One surface per response. The channel that scheduled the job is the one
# its owner is watching, so a Slack owner DM on top of it is a duplicate
Expand Down Expand Up @@ -156,6 +156,7 @@ async def _deliver_channel_reply(
*,
resolved_link: tuple[ChannelLink, bool] | None = None,
caller: str = "subagent",
markdown: bool = False,
) -> bool:
"""Deliver unattended output to the non-Slack channel conversation behind a session.

Expand All @@ -177,6 +178,10 @@ async def _deliver_channel_reply(
allow-list decision recorded against the wrong one is an audit trail
that points at a principal which never made the send.

``markdown`` is True only for an agent's own reply or result; host text
(failure alerts, task-run and approval notices) goes out as written
(``send_channel_parts``).

Returns True when the reply reached the channel; False degrades the
caller to dashboard-notification-only. Never raises: a delivery
failure must not break completion handling for the other paths.
Expand Down Expand Up @@ -238,6 +243,7 @@ async def _deliver_channel_reply(
parts,
thread_id=resolved.thread_id,
require_confirmation=True,
markdown=markdown,
):
logger.warning(
"%s reply: %s returned no message id for %s; treating as undelivered",
Expand Down
4 changes: 3 additions & 1 deletion src/kiro_crew/slack/gateway_runtime/subagent_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -1170,7 +1170,9 @@ async def _build(text: str) -> str:
# through the governed transport ladder; on failure
# the dashboard notification below still fires.
if _via_transport and response:
await self._deliver_channel_reply(parent_key, response, resolved_link=_reply_link)
await self._deliver_channel_reply(
parent_key, response, resolved_link=_reply_link, markdown=True
)
# Post only the LLM's synthesized response to Slack
try:
if response and _via_slack and self.slack and self._owner_id:
Expand Down
5 changes: 4 additions & 1 deletion test/chat_mirror_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def _fake_transport(
session_resume=False,
capabilities=None,
):
return SimpleNamespace(
transport = SimpleNamespace(
channel_type=channel_type,
capabilities=capabilities
or SimpleNamespace(
Expand All @@ -83,6 +83,9 @@ def _fake_transport(
# test_channel_transport_outbound_authz owns the refusal path.
may_send_to=lambda conversation_id, thread_id=None, principal="": True,
)
# The base transport's ``send_markdown`` is the plain send.
transport.send_markdown = lambda *args, **kwargs: transport.send_message(*args, **kwargs)
return transport


def _real_caps_transport(channel_type: str):
Expand Down
5 changes: 5 additions & 0 deletions test/test_autonudge_firing.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,12 @@ async def test_cross_surface_ladder_still_refuses_unroutable_channels(tmp_path):
channel_type="telegram",
capabilities=TransportCapabilities(supports_proactive_send=False),
send_message=AsyncMock(return_value="mid-1"),
may_send_to=lambda conversation_id, thread_id=None, principal="": True,
)
# The base transport's ``send_markdown`` is the plain send, and the roster
# admits the peer, so the assert below sees a send only the capability
# refusal can stop.
bound.send_markdown = bound.send_message
state.register_channel_transport(bound)
state.sessions.get_mirror_link = MagicMock(
return_value=ChannelLink("telegram", channel_id="4242", thread_id=None)
Expand Down
6 changes: 6 additions & 0 deletions test/test_channel_compaction_notice.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ async def send_message(
self.sent.append((conversation_id, content, thread_id))
return "mid-1"

async def send_markdown(
self, conversation_id: str, content: str, thread_id: str | None = None
) -> str:
# The base transport's ``send_markdown`` is the plain send.
return await self.send_message(conversation_id, content, thread_id)


class _Sessions:
def __init__(
Expand Down
2 changes: 2 additions & 0 deletions test/test_chat_runner_coverage_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -646,6 +646,7 @@ async def test_reply_is_chunked_per_transport_limit(self, tmp_path):
# so chunk_for_transport cannot compare it. 0 = not byte-capped, which
# is the character path this test is about.
transport.capabilities.max_message_bytes = 0
transport.send_markdown = transport.send_message
link = MagicMock(channel_id="123", thread_id=None, channel_type="telegram")

with patch.object(chat_runner, "_resolve_channel_target", return_value=(link, transport)):
Expand All @@ -660,6 +661,7 @@ async def test_transport_failure_never_disrupts_the_turn(self, tmp_path, caplog)
transport.capabilities.max_message_chars = 4096
transport.capabilities.max_message_bytes = 0
transport.send_message.side_effect = RuntimeError("offline")
transport.send_markdown = transport.send_message
link = MagicMock(channel_id="123", thread_id=None, channel_type="telegram")

with (
Expand Down
2 changes: 2 additions & 0 deletions test/test_cron_channel_delivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ def _transport(*, proactive: bool = True, max_chars: int = 4000) -> MagicMock:
supports_proactive_send=proactive, max_message_chars=max_chars, max_message_bytes=0
)
tr.send_message = AsyncMock()
# The base transport's ``send_markdown`` is the plain send.
tr.send_markdown = lambda *args, **kwargs: tr.send_message(*args, **kwargs)
tr.resolve_configured_target = AsyncMock(return_value=(DISCORD_CONVERSATION, ""))
return tr

Expand Down
3 changes: 3 additions & 0 deletions test/test_cron_channel_target.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ def _telegram(resolved: tuple[str, str | None] | None = ("42", "7")) -> MagicMoc
tr = MagicMock()
tr.capabilities = TransportCapabilities(supports_proactive_send=True, max_message_chars=4000)
tr.send_message = AsyncMock(return_value="mid-1")
# The base transport's ``send_markdown`` is the plain send; one mock for both
# keeps an ``assert_not_awaited`` on ``send_message`` covering either send.
tr.send_markdown = tr.send_message
tr.resolve_configured_target = AsyncMock(return_value=resolved)
return tr

Expand Down
6 changes: 5 additions & 1 deletion test/test_cross_surface_mirror.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@


def _fake_transport(channel_type: str = "telegram", proactive: bool = True, may_send: bool = True):
return SimpleNamespace(
transport = SimpleNamespace(
channel_type=channel_type,
capabilities=SimpleNamespace(
supports_proactive_send=proactive,
Expand All @@ -61,6 +61,10 @@ def _fake_transport(channel_type: str = "telegram", proactive: bool = True, may_
# test_channel_transport_outbound_authz owns the refusal path.
may_send_to=lambda conversation_id, thread_id=None, principal="": may_send,
)
# The base transport's ``send_markdown`` is the plain send; a test that
# swaps ``send_message`` later is still the one the leg reaches.
transport.send_markdown = lambda *args, **kwargs: transport.send_message(*args, **kwargs)
return transport


@pytest.fixture
Expand Down
5 changes: 4 additions & 1 deletion test/test_cross_surface_mirror_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@


def _transport(*, limits: ExtractLimits | None = ExtractLimits(max_files=10)) -> SimpleNamespace:
return SimpleNamespace(
transport = SimpleNamespace(
channel_type="feishu",
capabilities=SimpleNamespace(
supports_proactive_send=True,
Expand All @@ -54,6 +54,9 @@ def _transport(*, limits: ExtractLimits | None = ExtractLimits(max_files=10)) ->
send_outbound_image=AsyncMock(return_value=True),
may_send_to=lambda conversation_id, thread_id=None, principal="": True,
)
# The base transport's ``send_markdown`` is the plain send.
transport.send_markdown = transport.send_message
return transport


def _state(tmp_path, monkeypatch, transport, *, restricted: bool = False):
Expand Down
2 changes: 2 additions & 0 deletions test/test_member_thread_owner_dm_link.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ def __init__(self, *, paired: bool) -> None:
)
self._pairings = {DM_CHANNEL: OWNER} if paired else {}
self.send_message = AsyncMock(return_value="mid-1")
# The base transport's ``send_markdown`` is the plain send.
self.send_markdown = lambda *args, **kwargs: self.send_message(*args, **kwargs)

def configured_targets(self) -> list[ConfiguredChannelTarget]:
return [ConfiguredChannelTarget(f"user:{OWNER}", f"DM · {OWNER}")]
Expand Down
3 changes: 3 additions & 0 deletions test/test_messaging_egress.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,9 @@ async def send_message(self, conversation_id: str, text: str, thread_id: Any = N
self.sent.append((conversation_id, text, thread_id))
return self._ids.pop(0) if self._ids else "MSG"

async def send_markdown(self, conversation_id: str, text: str, thread_id: Any = None) -> str:
return await self.send_message(conversation_id, text, thread_id)

async def resolve_configured_target(self, target_id: str) -> Any:
return None

Expand Down
Loading
Loading