Skip to content
Merged
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
90 changes: 90 additions & 0 deletions loopx/capabilities/native_chat/external_mention_recovery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""Recover only a selected external mention with a proved pre-dispatch failure."""

from __future__ import annotations

import re
from collections.abc import Callable
from pathlib import Path
from typing import TYPE_CHECKING, Any

from ...chat_ingress import resolve_external_admission_source
from ...chat_store import TERMINAL_TURN_STATES, _atomic_write_json
from ...file_lock import exclusive_file_lock
from .file_discovery import external_source_route_path

if TYPE_CHECKING:
from .external_conversations import ChatExternalConversations


def requeue_rejected_mention(core: ChatExternalConversations, request_ref: str, *, original_turn_id: str,
source_preflight: Callable[[dict[str, Any]], None]) -> dict[str, Any]:
"""Admit an explicitly selected, independently verified private source once."""
from ...chat import require_matching_replay
from ...chat_manager_context import manager_authorization_scope_is_current

if not re.fullmatch(r"[a-f0-9]{24}", request_ref) or not callable(source_preflight):
raise ValueError("invalid original mention replay")
path = core.root / f"{request_ref}.json"
error = "live_steering_session_not_attached"
with exclusive_file_lock(path, operation="admit_external_chat_request"):
row = core.read_request(request_ref)
replay = row.get("rejected_mention_replay")
if replay is not None:
if replay["target_turn_id"] != original_turn_id:
raise ValueError("the original mention replay target changed")
if row["status"] == "accepted":
return row # Repair transport correlation after a committed admission.
sid = row["session_id"]
capture = row.get("mention_capture") or {}
if (row["status"] != "command_completed" or row.get("delivery_verified") is not True
or row.get("origin") != "lark" or row.get("command") or row.get("agent_target")
or row.get("attachments") or row.get("native_mention") is not True
or row["source"].get("private_human_message") is not True
or row.get("mention_delivery") != {"action": "reject", "error_code": error}
or row["turn_id"] != original_turn_id or capture.get("target_turn_id") != original_turn_id
or capture.get("session_id") != sid):
raise ValueError("the original mention lacks a pre-dispatch rejection")
route_lock = external_source_route_path(core.root, row["binding_id"], row["source"]["source_ref"])
with exclusive_file_lock(route_lock, operation="route_external_chat_request"):
store = core.controller.store
client = f"external-{request_ref}"
session = store.load_session(sid)
prior = store.load_turn(sid, original_turn_id)
receipt = store.steering_receipt(sid, client) or {}
if (receipt.get("mode") != "live_steering" or receipt.get("status") != "failed"
or receipt.get("error_code") != error or receipt.get("expected_turn_id") != original_turn_id
or receipt.get("active_turn_id") is not None or receipt.get("native_steering") is not None
or receipt.get("message") != row["message"]):
raise ValueError("the original steering receipt does not prove non-delivery")
turn = store.turn_for_client(sid, client)
if turn is not None:
if replay is None:
raise ValueError("the original client identity already has a Turn")
require_matching_replay(
{**turn, "message": turn.get("_queue_original_message", turn.get("message"))},
identity="client_turn_id", request={"message": row["message"], "attachments": None,
"origin": "lark", "external_agent_target": None},
)
else:
if (not session or session.get("status") == "closed" or not session.get("steward_context")
or not prior or prior["status"] not in TERMINAL_TURN_STATES
or core._source_stop_observed(row, prior, store.events_after(sid, original_turn_id, None))):
raise ValueError("the original mention replay is not eligible")
selected = resolve_external_admission_source(
core.bindings, row["binding_id"], row["source"], source_preflight, session=session,
)
if (selected["owner_manager_audience"] is not True
or selected["channel_id"] != capture.get("channel_id")
or not manager_authorization_scope_is_current(core.controller.registry_path,
core.controller.manager_scope_resolver, session, session.get("manager_authorization_scope_id"),
runtime_root=core.controller.coordination_runtime_root)):
raise ValueError("the original steward source or authority changed")
if replay is None:
row["rejected_mention_replay"] = {"target_turn_id": original_turn_id, "original_response": row["response"]}
_atomic_write_json(path, row)
core._record_steward_ingress(row, selected, session, client)
turn, _ = core.controller.enqueue_turn(session_id=sid, client_turn_id=client,
message=row["message"], attachments=None, work_dir=Path("."), objective="", origin="lark")
row.update(status="accepted", turn_id=turn["turn_id"], response=None, delivery_verified=False)
_atomic_write_json(path, row)
return row
10 changes: 7 additions & 3 deletions loopx/extensions/lark/private_conversations.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from ...control_plane.collaboration import conversation_reply_context
from ...control_plane.effect_runtime import effect_runtime_request_scope
from ...file_lock import exclusive_file_lock
from . import private_mention_topics
from .conversation_identity import identity_ref, lark_private_source
from .event_inbox import acknowledge_lark_event_inbox, ingest_lark_event_inbox
from .event_collector_runtime import enrich_lark_event_reply_context
Expand Down Expand Up @@ -632,8 +633,8 @@ def _record_admission(path: Path, record: dict[str, Any], admitted: dict[str, An
record.update(status="captured" if admitted["status"] == "prepared" else admitted["status"],
session_id=admitted["session_id"], turn_id=admitted["turn_id"],
response=admitted.get("response"), response_code=admitted.get("response_code"))
if admitted.get("context_recovery"):
record["context_recovery"] = admitted["context_recovery"]
if recovery := admitted.get("context_recovery") or private_mention_topics.replay_presentation(admitted):
record["context_recovery"] = recovery
if admitted.get("mention_delivery"):
record["mention_delivery"] = admitted["mention_delivery"]
_atomic_write_json(path, record)
Expand Down Expand Up @@ -967,6 +968,7 @@ def verify_mention(fresh: dict[str, Any]) -> None:
raise ValueError("native mention source changed")

preflight = verify_mention
native_mention = private_mention_topics.steer_in_topic(self, path, record, binding)
admitted = self.core.admit(binding_id=binding["binding_id"], source=source,
request_ref=request, message=text, command=command, attachments=attachments,
defer_background_stop=defer_background_stop, source_preflight=preflight,
Expand Down Expand Up @@ -1613,7 +1615,7 @@ def pending_delivery_paths(self) -> list[Path]:
paths.append(path)
else:
self._record_context_recovery_noop_backoff(path, row, stagger_first=True)
return [*paths, *self._web_projection_paths()]
return [*paths, *private_mention_topics.pending_replays(self, set(paths)), *self._web_projection_paths()]

def is_recovery_path(self, path: Path) -> bool:
"""Schedule recovery of persisted attempts after fresh replies."""
Expand Down Expand Up @@ -1719,6 +1721,8 @@ def reconcile_request(self, path: Path) -> int:
row = _read_json(path)
if "triage" in row:
return triage.reconcile(self, path)
if private_mention_topics.reconcile_rejection(self, path, row):
return 0
historical_images = row.get("historical_answer_images")
if (row.get("status") == "delivered" and (
(historical_images or {}).get("status") == "pending"
Expand Down
132 changes: 132 additions & 0 deletions loopx/extensions/lark/private_mention_topics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""Keep verified private steward reply topics distinct at mention admission."""

from __future__ import annotations

import json
import re
import time
from collections.abc import Iterator, Mapping
from pathlib import Path
from typing import TYPE_CHECKING, Any

from ...capabilities.native_chat.external_mention_recovery import requeue_rejected_mention
from ...chat_store import _atomic_write_json, _read_json
from ...file_lock import exclusive_file_lock
from .private_web_projection import _same_fields

if TYPE_CHECKING:
from .private_conversations import LarkPrivateConversations

_REPLAY_FOLDER = "rejected-mention-replays"


def distinct_reply_topic(transport: LarkPrivateConversations, record: dict[str, Any], binding: Mapping[str, Any]) -> bool:
if (binding.get("context_kind") != "steward" or binding.get("audience", "owner") != "owner"
or record["event"].get("chat_type") != "p2p"):
return False
root_id = record["event"].get("root_id")
capture = record.get("mention_capture") or {}
if (not root_id or record.get("reply_context_message") is None
or not capture.get("session_id") or not capture.get("target_turn_id")):
return False
turn = transport.core.controller.store.load_turn(capture["session_id"], capture["target_turn_id"])
match = re.fullmatch(r"external-([a-f0-9]{24})", str((turn or {}).get("client_turn_id") or ""))
if match is None or (turn or {}).get("origin") != "lark":
return False
try:
original = _read_json(transport.root / f"{match[1]}.json")
except (OSError, ValueError):
return False
previous = original["event"]
return (original.get("turn_id") == capture["target_turn_id"]
and original.get("session_id") == capture["session_id"]
and original.get("reply_context_message") is not None
and _same_fields(original, record, "binding_id", "profile", "source")
and previous.get("chat_id") == record["event"].get("chat_id")
and bool(previous.get("root_id"))
and previous["root_id"] != root_id)

def steer_in_topic(transport: LarkPrivateConversations, path: Path, record: dict[str, Any],
binding: Mapping[str, Any]) -> bool:
# Freeze this decision before Core admission so redelivery can restore a
# missing transport projection with the same request identity and mode.
if record.get("mention_topic_queue"):
return False
if (transport.core.root / path.name).exists() or not distinct_reply_topic(transport, record, binding):
return True
record["mention_topic_queue"] = True
_atomic_write_json(path, record)
return False


def replay_presentation(admitted: Mapping[str, Any]) -> dict[str, str] | None:
if admitted["status"] == "accepted" and admitted.get("rejected_mention_replay"):
return {"presentation_key": "rejected-mention.1"}
return None


def pending_replays(transport: LarkPrivateConversations, scheduled: set[Path]) -> Iterator[Path]:
folder = transport.root / _REPLAY_FOLDER
if folder.is_symlink():
return
for plan in sorted(folder.glob("*.json")):
path = transport.root / plan.name
if path in scheduled or not re.fullmatch(r"[a-f0-9]{24}", path.stem) or plan.is_symlink() or not plan.is_file():
continue
if time.monotonic() < transport._context_recovery_probe_at.get(plan, 0):
continue
try:
row = _read_json(path)
except (OSError, ValueError):
continue
if (row.get("status") == "delivered" and not row.get("context_recovery")
and row.get("mention_delivery", {}).get("action") == "reject"):
yield path

def reconcile_rejection(transport: LarkPrivateConversations, path: Path, row: dict[str, Any]) -> bool:
if (row.get("status") != "delivered" or row.get("context_recovery")
or row.get("mention_delivery", {}).get("action") != "reject"):
return False
plan_path = transport.root / _REPLAY_FOLDER / path.name
if plan_path.parent.is_symlink() or plan_path.is_symlink() or not plan_path.is_file():
return False
_apply_replay(transport, path, plan_path)
return True


def _apply_replay(transport: LarkPrivateConversations, path: Path, plan_path: Path) -> None:
transport._context_recovery_probe_at[plan_path] = time.monotonic() + 60
with exclusive_file_lock(path, operation="deliver_private_chat_request"):
record = _read_json(path)
if record.get("status") != "delivered" or record.get("context_recovery"):
return
terminal = record["deliveries"].get("terminal") or {}
try:
with plan_path.open("rb") as handle:
raw = handle.read(4097)
if len(raw) > 4096:
return
plan = json.loads(raw)
event = record["event"]
if (terminal.get("verified") is not True or plan != {
"message_id": event["message_id"],
"rejection_message_id": (terminal.get("attempt") or {}).get("message_ref"),
"target_turn_id": record["turn_id"],
} or not plan["rejection_message_id"] or record["request_ref"] != path.stem):
return

def verify_source(selected: dict[str, Any]) -> None:
source = transport._recovery_source_observation(record, selected)
if (source is None or source.get("_native_mention") is not True
or any(str(source.get(key) or "") != str(event.get(key) or "") for key in ("root_id", "parent_id"))
or (event.get("thread_id") and source.get("thread_id") != event["thread_id"])
or not distinct_reply_topic(transport, record, selected["binding"])):
raise ValueError("the original distinct topic could not be verified")

recovered = requeue_rejected_mention(transport.core, record["request_ref"],
original_turn_id=plan["target_turn_id"], source_preflight=verify_source)
transport._record_admission(path, record, recovered)
except (KeyError, ValueError, OSError, RuntimeError):
# An unavailable plan or uncertain source stays beside the
# original failure for a later independent observation.
return
Loading
Loading