This commit is contained in:
gr
2026-11-02 14:05:03 +08:00
parent f21b191429
commit 85c8330030
69 changed files with 7478 additions and 403 deletions
+60 -3
View File
@@ -105,6 +105,9 @@ class ProtocolBot:
self.progress_cb=progress;self._progress_text=''
self._completed_polls=0;self._last_poll_log=time.monotonic()
self._contact_scan_at=0.;self._contact_scan_offset=0;self._contact_logs={}
self._proactive_scan_at=0.
self._assistant_skip_log = {}
self._inbound_recovery_done = set()
self.identity=identity or discover();self.account=self.identity['accountId'];self.pid=self.identity['pid']
self.path=Path(path) if path else protocol_queue_path();self.path.parent.mkdir(parents=True,exist_ok=True)
self._lock=threading.RLock();self._owned_db=db is None
@@ -134,6 +137,7 @@ class ProtocolBot:
self._contact_blocked=raw.get('contactBlocked',{})
if not isinstance(self._contact_blocked,dict):raise NativeUnavailable('联系人跳过记录格式错误')
self._seen=raw.get('seen',{})
self._inbound_recovery_done=set(raw.get('inbound_recovery_done',[]))
if not isinstance(self._seen,dict):raise NativeUnavailable('协议去重记录格式错误')
for key,state in list(self._pending.items()):
# Filtering old drafts must never erase an attempted send's evidence.
@@ -199,7 +203,12 @@ class ProtocolBot:
for item in self._assistant_cancellations.values())
def _assistant_recipient(self,conv_id):
return bool(self._assistant_call('is_recipient',conv_id))
if not self._assistant_call('is_recipient',conv_id):return False
from proactive_replies import is_proactive_customer_turn
# The same person can receive review notifications and be a bound
# customer. A confirmed proactive conversation must not vanish here.
# Read errors propagate so an event isn't marked seen without routing it.
return not is_proactive_customer_turn(self.db,self.account,conv_id,self.path.parent)
def _assistant_pending(self,state):
# Preserve an already-registered review if coordination storage is
@@ -311,7 +320,7 @@ class ProtocolBot:
with self._lock:
temp=self.path.with_suffix('.tmp')
with temp.open('w',encoding='utf-8') as f:
json.dump({'schemaVersion':1,'transport':'protocol','pending':self._pending,'seen':self._seen,'contactBlocked':self._contact_blocked,'manual_handoffs':self._manual_handoffs,'assistant_cancellations':self._assistant_cancellations},f,ensure_ascii=False,indent=2);f.flush();os.fsync(f.fileno())
json.dump({'schemaVersion':1,'transport':'protocol','pending':self._pending,'seen':self._seen,'contactBlocked':self._contact_blocked,'manual_handoffs':self._manual_handoffs,'assistant_cancellations':self._assistant_cancellations,'inbound_recovery_done':sorted(getattr(self,'_inbound_recovery_done',()))},f,ensure_ascii=False,indent=2);f.flush();os.fsync(f.fileno())
os.replace(temp,self.path)
def _progress(self,text):
if self.stop_event.is_set() or text==self._progress_text:return
@@ -509,6 +518,9 @@ class ProtocolBot:
self._pending.pop(key,None)
if event:self._seen[key]=event
self._save()
if event and not message.get('is_self') and self._assistant_skip_log.get(key)!=event:
self._assistant_skip_log[key]=event
self.log(f"[协议跳过] {message.get('display_name') or message['conv_id']} · 当前为医疗助理提醒会话,本条不自动回复")
return
if old and self._assistant_attention(old):
from review_state import task_review_state
@@ -598,6 +610,50 @@ class ProtocolBot:
with self._lock:
if self._pending.get(key) is state:self._pending.pop(key,None)
self._save()
def _recover_proactive_replies(self):
# Backfill only recent, exact proactive recipients when a reply arrived
# before listening started. Feed the normal queue: dedup, patient checks,
# review requirements and protected attempts remain authoritative.
if self.stop_event.is_set() or time.monotonic() < getattr(self, '_proactive_scan_at', 0):
return
self._proactive_scan_at = time.monotonic() + 30
try:
from proactive_replies import incoming_after_proactive
messages = incoming_after_proactive(self.db, self.account, self.path.parent,
on_error=lambda exc: self.log('[主动联系] 客户回复检查暂不可用:' + type(exc).__name__))
for message in messages:
if self.stop_event.is_set():
return
self._restore_filtered_proactive_reply(message)
self._upsert(message)
except Exception as exc:
self.log('[主动联系] 客户回复检查暂不可用,下轮重试:' + type(exc).__name__)
def _restore_filtered_proactive_reply(self, message):
from proactive_replies import has_filtered_reply_recovery
event=message.get('dedup_key')
if (not event or event in self._inbound_recovery_done
or not has_filtered_reply_recovery(self.path.parent,message)):
return
key=session_key(self.account,message['conv_id'])
with self._lock:
handoff=(self._manual_handoffs.get(key) or {}).get('state') or {}
if (message.get('account')!=self.account or key in self._pending or self._seen.get(key)!=event
or handoff.get('dedup_key')==event or self._assistant_recipient(message['conv_id'])):
return
# A receipt or even an uncertain attempt must never be replayed.
lookup=getattr(self.sender,'lookup',None)
if not callable(lookup) or lookup(event) is not None:
return
self._seen.pop(key,None)
try:
self._upsert(message)
self._inbound_recovery_done.add(event)
self._save()
except Exception:
self._seen[key]=event
raise
def poll_once(self):
if self.stop_event.is_set():return
try:self._flush_assistant_cancellations()
@@ -620,6 +676,7 @@ class ProtocolBot:
try:self._upsert(message)
except Exception as exc:self._isolate_task_error(key,exc)
self._recover_blocked_contacts()
self._recover_proactive_replies()
def created_at(state):
try:return float(state.get('created_at',0) or 0)
except (TypeError,ValueError):return 0
@@ -1016,4 +1073,4 @@ class ProtocolBot:
try:self._review_assistant.close()
except Exception:pass
self.sender.close()
if self._owned_db:self.db.close()
if self._owned_db:self.db.close()