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
22 changes: 22 additions & 0 deletions docs/architecture/rfcs/app-conversation-and-async-inbox-v0.md
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,28 @@ These commands open no Session, invoke no model and create no Goal. `/help`
shows role-specific commands and the existing Settings → Lark entry for workspace,
executor and revocation, including supported images and unavailable media/attached-host boundaries.

The bound Steward's `/triage`, `/gates`, `/todos` and `/triage all` use the
existing scoped query and durable delivery path without starting a model Turn.
Its App callback consumer dispatches both Steward query cards and typed operation
confirmation cards; it does not create another subscription. Query callbacks
retain the original Chat binding, source grants and Session. Operation callbacks
use the existing operation handler and the controller's coordination root,
including its original proposal, confirmation, claim and result-card readback.
The Chat action store is not a fallback operation authority. An unavailable or
changed App fails closed. Unknown callback shapes are ignored, and source
validation and duplicate handling remain with each protocol's existing owner.
An explicitly configured standalone operation consumer must be coordinated before
cutover; this routing slice neither stops it nor transfers a configured managed
wake policy. An unconfigured managed wake remains unauthorized.

The mixed-protocol regression uses one physical callback stream and a separate
Chat/coordination-root fixture with the real Core operation store and synthetic
provider/executor. It verifies wrong-chat rejection, one execution on replay,
original-card result readback, binding revocation and no extra query model Turn.
File and SQLite source-query regressions remain required. This is source and
packaged-path qualification; installed-service cutover and real client clicks
remain open acceptance.

Regression coverage uses the production native filesystem store, durable queue,
bound request and provider admission/reconciliation paths with a synthetic
provider and protocol executor. It qualifies queue/stop/readback and duplicate
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,20 @@ Core request 在 provider 投递前保存带时间的观测。重复事件保留
Session、调用模型或创建 Goal。`/help` 按角色列出命令、既有设置 → Lark 的工作区、
执行器与解绑入口,以及图片支持和暂不可用的媒体/原宿主边界。

本人管家的 `/triage`、`/gates`、`/todos` 与 `/triage all` 复用既有授权查询和持久
投递路径,不启动模型 Turn。同一 App 的回调消费者分发管家查询卡和 typed operation
确认卡,不另建订阅。查询回调保留原 Chat binding、来源授权与 Session;操作回调
沿用既有操作处理器和控制器的协调根,包括原提案、确认、claim 与原卡结果读回。
Chat action store 不作为备用操作权威。App 不可用或身份变化时拒绝操作;未知回调
形状忽略,各协议原有 owner 继续负责来源校验和重复处理。若已配置独立操作消费者,
切换前须协调其归属;本片段不停止该消费者,也不迁移已配置的 managed wake 策略。
未配置的 managed wake 仍无执行授权。

混合协议回归使用一条实际回调流,以及 Chat/协调根分离的 fixture,运行真实 Core
operation store,provider/执行器为合成实现。它验证错误会话拒绝、重放只执行一次、
原卡结果读回、解绑撤权及查询不增加模型 Turn;File、SQLite 来源查询回归仍须通过。
这属于源码和打包路径资格,正式服务切换与真实客户端点击仍待验收。

回归使用生产原生文件 store、持久队列、bound request 与 provider 受理/投递路径,
provider 和协议执行器为合成 fixture。它验证排队、停止、读回和重复投递,不证明
本增量的真实 provider、手机或正式安装验收。注册 Agent 选择及更广协调仍开放。
Expand Down
23 changes: 20 additions & 3 deletions loopx/extensions/lark/goal_topic_runtime_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from ..background_runtime import HostedWorker
from .cli_resolution import LarkCliUnavailableError
from .goal_channel_contracts import bindings_for_goal
from .goal_channel_operation import OPERATION_CARD_ACTION_SCHEMA_VERSION, handle_goal_channel_operation_callback
from .manager_context import session_turn_effect
from .private_steward_triage import TRIAGE_CARD_ACTION, capture_callback, profile_supports_cards
from .team_plan_confirmation import (
Expand Down Expand Up @@ -577,13 +578,29 @@ def handle_review_callback(
action = event.get("action_value")
if isinstance(action, Mapping) and action.get("schema_version") == TRIAGE_CARD_ACTION:
return self._handle_private_steward_callback(profile, event, action)
profile_config = runtime._active_profile_configs(
self.snapshot_provider()
).get(profile)
if isinstance(action, Mapping) and action.get("schema_version") == OPERATION_CARD_ACTION_SCHEMA_VERSION:
if not profile_config or profile_config.get("bot_app_id") != expected_app:
raise ValueError("Lark operation callback App changed")
# Operation proposals belong to the coordination
# owner, independently of the private Chat root.
owner_root = getattr(self.runtime_controller, "coordination_runtime_root", None)
if not isinstance(owner_root, Path):
raise ValueError("Lark operation callback coordination owner is unavailable")
return handle_goal_channel_operation_callback(
event, runtime_root=owner_root,
action_store_root=owner_root / "chat" / "actions",
profile_app_id=expected_app, profile=profile,
cli_bin=profile_config.get("cli_bin") or "lark-cli",
**({"runner": self.private_conversations.runner}
if self.private_conversations is not None else {}),
)
if self.action_service is None:
raise ValueError(
"Lark manager review callbacks require Chat actions"
)
profile_config = runtime._active_profile_configs(
self.snapshot_provider()
).get(profile)
return handle_lark_review_callback_for_profile(
event,
action_service=self.action_service,
Expand Down
13 changes: 10 additions & 3 deletions loopx/extensions/lark/team_plan_confirmation.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
build_team_plan_review_card,
)
from .private_steward_triage import TRIAGE_CARD_ACTION, profile_supports_cards
from .goal_channel_operation import OPERATION_CARD_ACTION_SCHEMA_VERSION


TEAM_PLAN_CALLBACK_RECEIPT_SCHEMA_VERSION = "lark_team_plan_callback_receipt_v0"
Expand Down Expand Up @@ -269,12 +270,14 @@ def start_team_plan_review_callback_stream(
chat_filter = " or ".join(
f".chat_id == {json.dumps(chat_id)}" for chat_id in chat_ids
)
# Private cards match a locally recorded message and chat. This source
# only forwards the Steward action shape alongside existing group chats.
# The App has one callback subscription. Each private/operation handler
# independently verifies its own recorded message, chat and authority.
if private_steward:
steward_filter = (
"((.action_value | if type == \"string\" then (fromjson? // {}) else . end "
f"| .schema_version) == {json.dumps(TRIAGE_CARD_ACTION)})"
"| if type == \"object\" then .schema_version else null end) as $schema | "
f"($schema == {json.dumps(TRIAGE_CARD_ACTION)} or "
f"$schema == {json.dumps(OPERATION_CARD_ACTION_SCHEMA_VERSION)}))"
)
chat_filter = f"{chat_filter} or {steward_filter}" if chat_filter else steward_filter

Expand All @@ -291,6 +294,10 @@ def dispatch(callback_event: Mapping[str, Any]) -> None:
if not private_steward:
return
callback_event = {**callback_event, "action_value": action}
elif schema == OPERATION_CARD_ACTION_SCHEMA_VERSION:
if not private_steward and callback_event.get("chat_id") not in chat_ids:
return
callback_event = {**callback_event, "action_value": action}
elif schema != TEAM_PLAN_CARD_ACTION_SCHEMA_VERSION or callback_event.get("chat_id") not in chat_ids:
return
try:
Expand Down
182 changes: 182 additions & 0 deletions tests/extensions/test_lark_private_steward_triage.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import hashlib
import json
import queue
import shutil
import subprocess
import threading
import time
from pathlib import Path
Expand All @@ -14,6 +16,7 @@
from test_native_steward_private import finish, steward as steward

from loopx.capabilities.native_chat import steward_triage
from loopx.chat_action_store import ActionConflictError
from loopx.extensions.lark import private_steward_triage
from loopx.extensions.lark.conversation_identity import identity_ref
from loopx.extensions.lark.goal_topic_runtime import stream_lark_goal_topic_profile
Expand Down Expand Up @@ -368,6 +371,185 @@ def process_factory(argv):
assert observed == [{**event, "action_value": action}]


def test_one_callback_consumer_dispatches_both_card_protocols(tmp_path: Path):
from loopx.extensions.lark.goal_channel_operation import OPERATION_CARD_ACTION_SCHEMA_VERSION

actions = [
{"schema_version": private_steward_triage.TRIAGE_CARD_ACTION, "operation": "menu"},
{"schema_version": OPERATION_CARD_ACTION_SCHEMA_VERSION, "action": "confirm"},
]
events = [event_for("om_fixture", json.dumps(action) if index == 0 else action, suffix=str(index))
for index, action in enumerate(actions)]
unknowns = [event_for("om_unknown", value) for value in
({"schema_version": "unknown"}, [], 7, None, "broken-json")]
seen, observed, sources = threading.Event(), [], []
snapshot = {"private_profiles": {"steward-app": {
"cli_bin": "fixture-cli", "audience": "owner", "context_kind": "steward",
}}}

class Consumer:
def __init__(self, stdout):
self.stdout = stdout

def poll(self):
return 0

def wait(self, timeout=None):
return 0

def handler(payload):
observed.append(payload)
if len(observed) == 2:
seen.set()
return {"ok": True}

def messages():
yield "[event] ready event_key=im.message.receive_v1\n"
assert seen.wait(2)
yield "[event] exited — received 0 event(s) in 1s (reason: timeout)\n"

def process_factory(argv):
sources.append(argv[argv.index("consume") + 1])
if "card.action.trigger" in argv:
# Exercise the actual jq program, including its string/object
# normalization, rather than merely matching its schema literals.
lines = [json.dumps(event) for event in events]
if jq := shutil.which("jq"):
filtered = subprocess.run(
[jq, "-c", argv[argv.index("--jq") + 1]],
input="\n".join([*lines, *(json.dumps(event) for event in unknowns)]),
capture_output=True, text=True, check=True,
)
lines = filtered.stdout.splitlines()
assert [json.loads(line) for line in lines] == events
# The dispatcher must also reject an unknown event if a provider
# delivers it despite the source filter.
return Consumer(iter([*lines, *(json.dumps(event) for event in unknowns)]))
return Consumer(messages())

result = stream_lark_goal_topic_profile(
profile="steward-app", snapshot_provider=lambda: snapshot, stop=threading.Event(),
runtime_root=tmp_path, answer=lambda *_: pytest.fail("ordinary turn started"),
process_factory=process_factory, review_callback_handler=handler,
)
assert result["ok"] is True
assert sorted(sources) == ["card.action.trigger", "im.message.receive_v1"]
assert observed == [{**event, "action_value": action} for event, action in zip(events, actions)]


def test_chat_callback_service_preserves_operation_owner_and_private_session(steward, monkeypatch, tmp_path):
import test_lark_goal_channel_operation as operation_fixture
from datetime import datetime, timezone
from loopx.capabilities.native_chat.project_context import coordination_runtime_root
from loopx.extensions.lark import goal_channel_operation, goal_topic_runtime, goal_topic_runtime_service

store, runtime, provider, transport, binding, capture, _ = steward
profile = "steward-app"
transport.steward_callback_streams[(profile, provider.profile_apps[profile])] = SimpleNamespace(ready=lambda: True)
ordinary = provider.event(profile, "original-session", "Keep the original conversation.")
assert transport.admit(profile, ordinary)["status"] == "durably_accepted"
original = transport.core.read_request(identity_ref(binding["provider_ref"], ordinary["message_id"]))
assert finish(runtime, original)["status"] == "completed"
assert transport.reconcile() == 1
before = capture.read_bytes(), store.messages(original["session_id"])
writes, _ = fixture_card_provider(provider, transport, monkeypatch)
private_runner = transport.runner
assert transport.admit(profile, provider.event(profile, "menu", "/triage"))["status"] == "triage_queued"
assert transport.reconcile() == 1
menu_id = writes[-1]
action = buttons(json.loads(provider.messages[menu_id]["body"]["content"]))["总览"]
click = event_for(menu_id, action)

for name, value in (("APP_ID", "cli_steward_app"), ("CHAT_ID", "oc_steward_app"), ("OPERATOR_ID", "ou_steward_app")):
monkeypatch.setattr(operation_fixture, name, value)
operation_dir = tmp_path / "coordination-owner"
operation_dir.mkdir()
actions, registry, owner_root, channel_binding, target = operation_fixture._fixture(operation_dir)
runtime.coordination_runtime_root = coordination_runtime_root(registry, store.root.parent)
assert runtime.coordination_runtime_root == owner_root and owner_root != store.root
proposal = operation_fixture._prepare(actions, registry)
sent_cards, calls = {}, []
operation_runner = operation_fixture._runner(calls, sent_cards)

def run(argv, cwd=None, timeout=None):
operation_io = (
any("om_operation_card_fixture" in arg or "interactive/v1/card/update" in arg for arg in argv)
or ("--profile" in argv and argv[argv.index("--profile") + 1] == "operation-bot")
or "+chat-members-list" in argv or ("chats" in argv and "get" in argv)
or ("+messages-send" in argv and json.loads(argv[argv.index("--content") + 1]).get("schema") == "2.0")
)
return (operation_runner if operation_io else private_runner)(argv, cwd, timeout)

monkeypatch.setattr(transport, "runner", run)
delivered = goal_channel_operation.deliver_goal_channel_operation_card(
proposal_id=proposal["proposal_id"], action_store_root=actions.root, runtime_root=owner_root,
binding_path=channel_binding, target_path=target, execute=True, runner=run,
executor_binding_resolver=lambda *_: {"revision": "simulator-v0"},
)
assert delivered["status"] == "awaiting_confirmation" and delivered["readback_verified"] is True
durable = actions.load(proposal["proposal_id"])
operation_event = operation_fixture._event(durable, sent_cards[durable["operation"]["delivery"]["message_id"]])
operation_event["action_value"] = json.loads(operation_event["action_value"])
executed = []

def execute(claimed, *, runtime_root):
assert runtime_root == owner_root
executed.append(claimed["proposal_id"])
operation = claimed["operation"]
return {
"schema_version": "loopx_operation_outcome_v0", "outcome": "simulated_filled",
"projection_verified": True, "operation_id": operation["operation_id"],
"payload_digest": operation["payload_digest"], "claim_id": operation["claim"]["claim_id"],
"executor_revision": operation["executor_revision"], "summary": "Synthetic operation completed.",
"simulation": True, "external_write_performed": False,
"observed_at": datetime.now(timezone.utc).isoformat(),
}

monkeypatch.setattr(goal_channel_operation, "_execute_claimed_operation", execute)
handlers, entered = [], threading.Event()

def stream(**kwargs):
handlers.append(kwargs["review_callback_handler"])
entered.set()
assert kwargs["stop"].wait(10)
return {"ok": True}

monkeypatch.setattr(goal_topic_runtime, "stream_lark_goal_topic_profile", stream)
monkeypatch.setattr(goal_topic_runtime_service, "try_exclusive_file_lock",
lambda path, **kwargs: try_exclusive_file_lock(tmp_path / "consumer-locks" / path.name, **kwargs))
service = LarkGoalTopicRuntimeService(
snapshot_provider=lambda: {"private_profiles": {
name: config for name, config in transport.profiles().items() if name == profile
}},
runtime_root=transport.runtime_root, runtime_controller=runtime, private_conversations=transport,
)
try:
service.refresh()
assert entered.wait(3) and len(handlers) == 1
callback = handlers[0]
with pytest.raises(ActionConflictError):
callback({**operation_event, "chat_id": "oc_forwarded"})
assert not executed
first = callback(operation_event)
replay = callback(operation_event)
assert first["outcome"] == replay["outcome"] == "simulated_filled"
assert first["card_update_verified"] is True and replay["external_write_performed"] is False
assert executed == [proposal["proposal_id"]]
assert actions.load(proposal["proposal_id"])["operation"]["lifecycle_state"] == "outcome_observed"
assert transport.core.actions.store.load(proposal["proposal_id"]) is None
assert callback(click)["status"] == "triage_callback_queued"
assert transport.reconcile() == 1
assert callback(click)["status"] == "triage_callback_already_captured"
assert before == (capture.read_bytes(), store.messages(original["session_id"]))
snapshot = transport.bindings.read()
transport.bindings.disconnect(binding["binding_id"], expected_revision=snapshot["revision"])
with pytest.raises(ValueError):
callback({**operation_event, "event_id": "after-revoke"})
assert executed == [proposal["proposal_id"]]
finally:
service.close()


@pytest.mark.parametrize("authority_provider", ["file", "sqlite"])
def test_triage_reads_declared_source_before_shared_runtime(steward, monkeypatch, authority_provider):
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[1] / "control_plane"))
Expand Down
Loading