1212import json
1313import re
1414from functools import partial
15- from collections .abc import Mapping
15+ from collections .abc import Mapping , Sequence
1616from pathlib import Path
1717from typing import Any
1818
3939 bindings_for_goal ,
4040 goal_channel_connection_id ,
4141 GOAL_CHANNEL_CONNECTION_SET_SCHEMA_VERSION ,
42- LarkTopicEventDecisionReason ,
4342 goal_from_registry ,
4443 goal_objective ,
4544 now_iso ,
9392 ReplyMode ,
9493 _routing_value ,
9594 _connection_routing_modes ,
96- decide_lark_topic_route_event ,
95+ decide_worker_topic_event ,
9796)
9897from .cli_transport import (
9998 DEFAULT_CLI_BIN ,
@@ -1179,6 +1178,7 @@ def decide_lark_topic_event(
11791178 binding_payloads : Mapping [str , Mapping [str , Any ]],
11801179 event : Mapping [str , Any ],
11811180 runtime_root : str | Path | None = None ,
1181+ peer_worker_identities : Sequence [Mapping [str , Any ]] | None = None ,
11821182) -> dict [str , Any ]:
11831183 """Return a content-free routing decision for one provider event."""
11841184
@@ -1187,174 +1187,15 @@ def decide_lark_topic_event(
11871187 binding_payloads = binding_payloads ,
11881188 event = event ,
11891189 runtime_root = runtime_root ,
1190+ peer_worker_identities = peer_worker_identities ,
11901191 )
11911192 if manager_decision is not None :
11921193 return manager_decision
1193- chat_id = str (event .get ("chat_id" ) or "" )
1194- root_id = str (event .get ("root_id" ) or "" )
1195- message_id = str (event .get ("message_id" ) or "" )
1196- if not (
1197- CHAT_ID_PATTERN .fullmatch (chat_id )
1198- and MESSAGE_ID_PATTERN .fullmatch (root_id )
1199- and MESSAGE_ID_PATTERN .fullmatch (message_id )
1200- ):
1201- return {
1202- "matched" : False ,
1203- "reason" : LarkTopicEventDecisionReason .INVALID_EVENT .value ,
1204- "route" : None ,
1205- }
1206- has_binding = False
1207- matched_chat = False
1208- candidates : list [dict [str , Any ]] = []
1209- for goal_id , payload in binding_payloads .items ():
1210- for binding in bindings_for_goal (payload , goal_id ):
1211- if binding .get ("enabled" ) is not True :
1212- continue
1213- has_binding = True
1214- target_ref = str (binding .get ("target_ref" ) or "" )
1215- target = goal_channel_target_for_name (target_payload , target_ref )
1216- if target is None :
1217- continue
1218- channel = (
1219- target .get ("channel" )
1220- if isinstance (target .get ("channel" ), Mapping )
1221- else {}
1222- )
1223- if str (channel .get ("chat_id" ) or "" ) != chat_id :
1224- continue
1225- matched_chat = True
1226- identity = (
1227- target .get ("identity" )
1228- if isinstance (target .get ("identity" ), Mapping )
1229- else {}
1230- )
1231- raw_topic = binding .get ("topic" )
1232- topic = raw_topic if isinstance (raw_topic , Mapping ) else {}
1233- raw_binding_channel = binding .get ("channel" )
1234- binding_channel = raw_binding_channel if isinstance (raw_binding_channel , Mapping ) else {}
1235- topic_root = str (
1236- topic .get ("root_message_id" )
1237- or binding_channel .get ("pinned_message_id" )
1238- or ""
1239- )
1240- raw_routing = binding .get ("routing" )
1241- routing = raw_routing if isinstance (raw_routing , Mapping ) else {}
1242- try :
1243- capture_scope , ingress_mode , reply_mode = _connection_routing_modes (routing )
1244- connector = binding .get ("connector" )
1245- if connector is not None :
1246- if not isinstance (connector , Mapping ):
1247- raise ValueError ("connector binding must be an object" )
1248- connector_status = project_external_connector_status (connector )
1249- if (
1250- connector_status ["goal_ref" ] != goal_id
1251- or connector_status ["agent_ref" ]
1252- != str (binding .get ("agent_id" ) or "" )
1253- or connector_status ["ingress_policy" ] != ingress_mode
1254- ):
1255- raise ValueError (
1256- "connector binding does not match the Lark route"
1257- )
1258- except ValueError :
1259- return {
1260- "matched" : False ,
1261- "reason" : LarkTopicEventDecisionReason .INVALID_ROUTING_STATE .value ,
1262- "route" : None ,
1263- }
1264- candidates .append (
1265- {
1266- "goal_id" : goal_id ,
1267- "connection_id" : str (binding .get ("connection_id" ) or "" ),
1268- "binding" : binding ,
1269- "identity" : identity ,
1270- "target_ref" : target_ref ,
1271- "topic_root" : topic_root ,
1272- "capture_scope" : capture_scope ,
1273- "ingress_mode" : ingress_mode ,
1274- "reply_mode" : reply_mode ,
1275- "routing" : routing ,
1276- "connector" : connector ,
1277- }
1278- )
1279-
1280- exact_topic_candidates = [
1281- candidate for candidate in candidates if candidate ["topic_root" ] == root_id
1282- ]
1283- eligible = exact_topic_candidates or [
1284- candidate
1285- for candidate in candidates
1286- if candidate ["capture_scope" ] == CaptureScope .CONFIGURED_CHAT_ALL .value
1287- ]
1288- if len (eligible ) > 1 :
1289- return {
1290- "matched" : False ,
1291- "reason" : LarkTopicEventDecisionReason .ROUTE_AMBIGUOUS .value ,
1292- "route" : None ,
1293- }
1294- if not eligible :
1295- reason = (
1296- LarkTopicEventDecisionReason .BINDING_UNAVAILABLE
1297- if not has_binding
1298- else LarkTopicEventDecisionReason .CHAT_MISMATCH
1299- if not matched_chat
1300- else LarkTopicEventDecisionReason .TOPIC_MISMATCH
1301- )
1302- return {"matched" : False , "reason" : reason .value , "route" : None }
1303-
1304- selected = eligible [0 ]
1305- identity = selected ["identity" ]
1306- capture_scope = str (selected ["capture_scope" ])
1307- route_decision = decide_lark_topic_route_event (
1194+ return decide_worker_topic_event (
1195+ target_payload = target_payload ,
1196+ binding_payloads = binding_payloads ,
13081197 event = event ,
1309- chat_id = chat_id ,
1310- topic_root_message_id = str (selected ["topic_root" ]),
1311- capture_scope = capture_scope ,
1312- identity = identity ,
13131198 )
1314- if route_decision is not LarkTopicEventDecisionReason .MATCHED :
1315- return {
1316- "matched" : False ,
1317- "reason" : route_decision .value ,
1318- "route" : None ,
1319- }
1320- binding = selected ["binding" ]
1321- ingress_mode = str (selected ["ingress_mode" ])
1322- routing = selected ["routing" ]
1323- connector = selected ["connector" ]
1324- route = {
1325- "app_ref" : str (identity .get ("sender_profile" ) or "default" ),
1326- "goal_id" : str (selected ["goal_id" ]),
1327- "connection_id" : str (selected ["connection_id" ]),
1328- "message_id" : message_id ,
1329- "reply_mode" : str (selected ["reply_mode" ]),
1330- "target_ref" : str (selected ["target_ref" ]),
1331- "topic_root_message_id" : str (selected ["topic_root" ]),
1332- }
1333- if ingress_mode != IngressMode .DIRECT_SESSION .value or binding .get ("agent_id" ):
1334- route .update (
1335- {
1336- "agent_id" : str (binding .get ("agent_id" ) or "" ),
1337- "session_id" : str (binding .get ("session_id" ) or "" ),
1338- "capture_scope" : capture_scope ,
1339- "ingress_mode" : ingress_mode ,
1340- "inbox_config_ref" : str (routing .get ("inbox_config_ref" ) or "" ),
1341- ** (
1342- {"connector" : dict (connector )}
1343- if isinstance (connector , Mapping )
1344- else {}
1345- ),
1346- ** (
1347- {"event_id" : str (event .get ("event_id" ) or message_id )}
1348- if isinstance (connector , Mapping )
1349- else {}
1350- ),
1351- }
1352- )
1353- return {
1354- "matched" : True ,
1355- "reason" : LarkTopicEventDecisionReason .MATCHED .value ,
1356- "route" : route ,
1357- }
13581199
13591200
13601201def route_lark_topic_event (
@@ -1395,26 +1236,50 @@ def reply_lark_goal_topic(
13951236 reply_text ,
13961237 )
13971238 )
1239+ reply_in_thread = bool (
1240+ str (route .get ("topic_root_message_id" ) or "" ).strip ()
1241+ or str (route .get ("thread_id" ) or "" ).strip ()
1242+ or str (route .get ("chat_mode" ) or "" ).strip ().lower () == "topic"
1243+ )
1244+ chat_id = str (route .get ("chat_id" ) or "" ).strip ()
1245+ tail = (
1246+ [
1247+ "im" ,
1248+ "+messages-reply" ,
1249+ "--message-id" ,
1250+ message_id ,
1251+ "--text" ,
1252+ reply_text ,
1253+ * (["--reply-in-thread" ] if reply_in_thread else []),
1254+ "--idempotency-key" ,
1255+ key ,
1256+ "--as" ,
1257+ "bot" ,
1258+ "--format" ,
1259+ "json" ,
1260+ ]
1261+ if reply_in_thread or not CHAT_ID_PATTERN .fullmatch (chat_id )
1262+ else [
1263+ "im" ,
1264+ "+messages-send" ,
1265+ "--chat-id" ,
1266+ chat_id ,
1267+ "--text" ,
1268+ reply_text ,
1269+ "--idempotency-key" ,
1270+ key ,
1271+ "--as" ,
1272+ "bot" ,
1273+ "--format" ,
1274+ "json" ,
1275+ ]
1276+ )
13981277 result = call (
13991278 runner ,
14001279 lark_args (
14011280 cli_bin = cli_bin ,
14021281 profile = profile ,
1403- tail = [
1404- "im" ,
1405- "+messages-reply" ,
1406- "--message-id" ,
1407- message_id ,
1408- "--text" ,
1409- reply_text ,
1410- "--reply-in-thread" ,
1411- "--idempotency-key" ,
1412- key ,
1413- "--as" ,
1414- "bot" ,
1415- "--format" ,
1416- "json" ,
1417- ],
1282+ tail = tail ,
14181283 ),
14191284 )
14201285 reply_id = find_first_string (
0 commit comments