Repository navigation
Expand file tree
/
Copy pathworker.py
More file actions
1604 lines (1455 loc) · 71.6 KB
/
Copy pathworker.py
File metadata and controls
1604 lines (1455 loc) · 71.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Worker pipeline for Feishu bridge message processing."""
import json
import logging
import os
import re
import time
import threading
import uuid
from pathlib import Path
from feishu_bridge.bg_paths import bg_home
from feishu_bridge.parsers import (
download_file,
download_image,
fetch_card_content,
fetch_forward_messages,
fetch_quoted_message,
)
from feishu_bridge.quota import WINDOW_LABELS, fetch_codex_quota, fetch_deepseek_balance
from feishu_bridge.runtime import (
BaseRunner, SessionMap, TOOL_ACTIVE_SILENT_TIMEOUT,
build_fresh_context_prompt, pick_primary_model, resolve_dotclaude_root,
)
from feishu_bridge.session_journal import SessionJournal
from feishu_bridge.ui import ResponseHandle, _format_pi_usage_footer, remove_typing_indicator
log = logging.getLogger("feishu-bridge")
_MEDIA_MAX_AGE_SECS = 3600 # 1 hour
# Phase 6.3: bridge-owned per-turn journal. Singleton by default; tests inject
# their own instance via monkeypatch on the module attribute.
_session_journal = SessionJournal()
def _derive_runner_type(runner) -> str:
"""Map runner class name → canonical runner_type string.
BaseRunner does not expose self.runner_type in Phase 6.3 (tracked as a
separate contract change). For now we derive from class name.
"""
name = type(runner).__name__.lower()
if "claude" in name:
return "claude"
if name.startswith("pi"):
return "pi"
if "codex" in name:
return "codex"
return name.replace("runner", "") or "unknown"
# ── Stage 2: heuristic project-binding suffix + log ──────────────────────────
def _build_project_suffix(match, message: str) -> str | None:
"""Compose a one-line binding-suggestion suffix for the agent reply.
Confidence taxonomy (mirrors design.md §决策矩阵):
* ``high`` → "识别到项目 X,回复 /project X 确认绑定"
* ``medium`` / ``low``→ "未绑定项目,回复 /project <id> 指定 / clear 清除"
* ``none`` + history → "未绑定项目,建议回复 /project <id> 指定"
* ``none`` + other → no suffix (R3 narrow rule — don't pester chitchat)
"""
from feishu_bridge.project_detector import has_history_trigger
if match is not None:
conf = match.confidence
pid = match.project_id
if conf == "high":
return f"_(识别到项目 **{pid}**,回复 `/project {pid}` 确认绑定)_"
if conf in ("medium", "low"):
return ("_(未绑定项目,回复 `/project <id>` 指定 / `/project clear` "
"清除)_")
# match is None
if has_history_trigger(message):
return "_(未绑定项目,建议回复 `/project <id>` 指定,让回答更聚焦)_"
return None
def _log_heuristic_event(global_workspace, bot_id: str, tag: str,
message: str, match, history_triggered: bool) -> None:
"""Append a single line of JSON describing a heuristic decision.
Goes to ``<global_workspace>/state/feishu-bridge/heuristic-log-{bot_id}.jsonl``.
Best-effort; logging failures must never propagate.
"""
try:
path = (Path(global_workspace) / "state" / "feishu-bridge"
/ f"heuristic-log-{bot_id}.jsonl")
path.parent.mkdir(parents=True, exist_ok=True)
msg_hash = hash(message) & 0xFFFFFFFF # cheap, non-crypto fingerprint
# Spec task 4.5 schema: {ts, tag, message_hash, match, user_action}.
# `user_action` is populated by a future feedback-loop pass (Follow-up
# F7); for now write `null` so consumers see the expected key. We also
# carry `history_triggered` to support narrow-rule calibration.
record = {
"ts": int(time.time()),
"tag": tag,
"message_hash": f"{msg_hash:08x}",
"match": (
None if match is None
else {"id": match.project_id, "confidence": match.confidence,
"via": match.matched_via}
),
"user_action": None,
"history_triggered": bool(history_triggered),
}
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
except OSError as exc:
log.warning("heuristic-log append failed: %s", exc)
# ---------------------------------------------------------------------------
# Defer approval card
# ---------------------------------------------------------------------------
def _send_defer_approval_card(lark_client, chat_id, session_id,
cmd_display, cmd_prefix_base, cwd="", bot_id="",
tool_type="bash", tool_use_id=""):
"""Send an interactive approval card for a deferred tool call."""
try:
from lark_oapi.api.im.v1 import (
CreateMessageRequest, CreateMessageRequestBody,
)
action_value = {
"action": "tool_approval",
"session_id": session_id,
"cmd_prefix": cmd_prefix_base,
"chat_id": chat_id,
"bot_id": bot_id,
"tool_type": tool_type,
"tool_use_id": tool_use_id,
}
buttons = [
{"tag": "button", "text": {"tag": "plain_text", "content": "✅ 允许(仅本次)"},
"type": "primary_filled", "size": "medium",
"value": {**action_value, "decision": "allow_once"}},
{"tag": "button", "text": {"tag": "plain_text", "content": "✅ 允许(本会话)"},
"type": "primary", "size": "medium",
"value": {**action_value, "decision": "allow_session"}},
{"tag": "button", "text": {"tag": "plain_text", "content": "✅ 始终允许"},
"type": "primary", "size": "medium",
"value": {**action_value, "decision": "allow_always"}},
{"tag": "button", "text": {"tag": "plain_text", "content": "❌ 拒绝"},
"type": "danger", "size": "medium",
"value": {**action_value, "decision": "deny"}},
]
card = {
"schema": "2.0",
"config": {"enable_forward": False},
"header": {
"title": {"tag": "plain_text", "content": "\U0001f510 命令审批" if tool_type == "bash" else "\U0001f510 工具审批"},
"template": "orange",
},
"body": {
"elements": [
{
"tag": "markdown",
"content": (
(f"**命令:**\n```\n{cmd_display}\n```"
+ (f"\n**命令类型:** `{cmd_prefix_base}`" if cmd_prefix_base else ""))
if tool_type == "bash" else
f"**工具:** `{cmd_prefix_base}`\n**参数:**\n```json\n{cmd_display}\n```"
),
},
{
"tag": "column_set",
"flex_mode": "flow",
"columns": [{
"tag": "column",
"width": "auto",
"elements": buttons,
}],
},
],
},
}
body = CreateMessageRequestBody.builder() \
.receive_id(chat_id) \
.msg_type("interactive") \
.content(json.dumps(card, ensure_ascii=False)) \
.build()
req = CreateMessageRequest.builder() \
.receive_id_type("chat_id") \
.request_body(body) \
.build()
resp = lark_client.im.v1.message.create(req)
if not resp.success():
log.error("Defer approval card send failed: code=%s msg=%s",
resp.code, resp.msg)
except Exception:
log.exception("Failed to send defer approval card")
# ---------------------------------------------------------------------------
# Idle Auto-Compact: proactive compact before prompt cache TTL expires
# ---------------------------------------------------------------------------
# Anthropic prompt cache TTL is 1 hour (ephemeral_1h). If we compact while
# the cache is still warm (~50 min), the compact call pays cache_read price
# (cheap). After compact the session history shrinks, so if the cache later
# expires, the cold-start re-cache cost is much smaller.
_IDLE_COMPACT_DELAY = 50 * 60 # 50 minutes — 10 min buffer before 1h TTL
_IDLE_COMPACT_MIN_CTX = 50_000 # Don't compact small sessions
class IdleCompactManager:
"""Schedule a proactive /compact when a session goes idle.
After each successful interaction, a per-session timer is (re)started.
When the timer fires, the manager submits a silent compact command
through the ChatTaskQueue so it serialises with user messages.
"""
def __init__(self):
# Keyed by session_key (chat tuple string), not session_id,
# so session-id rotation (auto-heal) doesn't orphan timers.
self._timers: dict[str, threading.Timer] = {}
self._generation: dict[str, int] = {} # session_key → monotonic counter
self._lock = threading.Lock()
# Set by FeishuBot.start() after queue is ready.
self._enqueue_fn = None # ChatTaskQueue.enqueue
def bind(self, enqueue_fn):
"""Bind the queue reference once the bot is running."""
self._enqueue_fn = enqueue_fn
def touch(self, session_id: str, session_key: str,
total_ctx: int, bot_id: str, chat_id: str,
thread_id: str | None):
"""Register or reset the idle timer for a session."""
with self._lock:
old = self._timers.pop(session_key, None)
if old:
old.cancel()
# Bump generation so any in-flight _fire() for an older timer
# will see a stale generation and skip the enqueue.
gen = self._generation.get(session_key, 0) + 1
self._generation[session_key] = gen
if total_ctx < _IDLE_COMPACT_MIN_CTX:
return
timer = threading.Timer(
_IDLE_COMPACT_DELAY,
self._fire,
args=(session_id, session_key, total_ctx,
bot_id, chat_id, thread_id, gen),
)
timer.daemon = True
timer.start()
self._timers[session_key] = timer
def cancel(self, session_key: str):
"""Cancel the timer for a session (e.g. on /new)."""
with self._lock:
old = self._timers.pop(session_key, None)
if old:
old.cancel()
self._generation.pop(session_key, None)
def _fire(self, session_id: str, session_key: str, total_ctx: int,
bot_id: str, chat_id: str, thread_id: str | None,
gen: int = 0):
with self._lock:
self._timers.pop(session_key, None)
# If generation has advanced (touch() was called after this timer
# was created), this compact is stale — skip it.
if self._generation.get(session_key, 0) != gen:
log.debug("Idle compact skipped (stale generation): key=%s",
session_key)
return
if not self._enqueue_fn:
return
log.info("Idle auto-compact firing: sid=%s ctx=%d tokens",
session_id[:8], total_ctx)
item = {
"_bridge_command": "idle-compact",
"_cmd_arg": "",
"_session_id": session_id,
"bot_id": bot_id,
"chat_id": chat_id,
"thread_id": thread_id,
"message_id": None,
"sender_id": None,
"_queued_reaction_id": None,
"_queue_key": session_key,
}
try:
self._enqueue_fn(session_key, item)
except Exception:
log.warning("Idle auto-compact enqueue failed: sid=%s",
session_id[:8], exc_info=True)
idle_compact_mgr = IdleCompactManager()
def cleanup_stale_media(workspace: str, max_age: int = _MEDIA_MAX_AGE_SECS):
"""Delete media files older than *max_age* seconds from temp dirs."""
cutoff = time.time() - max_age
dirs = [
Path(workspace) / ".tmp" / "feishu_imgs",
Path(workspace) / ".tmp" / "feishu_files",
]
removed = 0
for d in dirs:
if not d.is_dir():
continue
for f in d.iterdir():
if f.is_file():
try:
if f.stat().st_mtime < cutoff:
f.unlink()
removed += 1
except OSError:
pass
if removed:
log.info("Cleaned up %d stale media file(s)", removed)
def start_media_cleanup_timer(workspace: str, interval: int = 600):
"""Run cleanup_stale_media every *interval* seconds in a daemon thread."""
def _loop():
while True:
time.sleep(interval)
try:
cleanup_stale_media(workspace)
except Exception:
log.exception("Media cleanup error")
t = threading.Thread(target=_loop, daemon=True, name="media-cleanup")
t.start()
log.info("Media cleanup timer started (interval=%ds, max_age=%ds)",
interval, _MEDIA_MAX_AGE_SECS)
# ponytail: module-level caches, TTL matches Claude poll interval
_codex_quota_cache: dict = {"snap": None, "ts": 0}
_deepseek_balance_cache: dict = {"snap": None, "ts": 0}
_CODEX_CACHE_TTL = 300
def _get_codex_quota_cached():
now = time.time()
if _codex_quota_cache["snap"] and (now - _codex_quota_cache["ts"]) < _CODEX_CACHE_TTL:
return _codex_quota_cache["snap"]
snap = fetch_codex_quota()
_codex_quota_cache["snap"] = snap
_codex_quota_cache["ts"] = now
return snap
def _get_deepseek_balance_cached():
now = time.time()
if _deepseek_balance_cache["snap"] and (now - _deepseek_balance_cache["ts"]) < _CODEX_CACHE_TTL:
return _deepseek_balance_cache["snap"]
snap = fetch_deepseek_balance()
_deepseek_balance_cache["snap"] = snap
_deepseek_balance_cache["ts"] = now
return snap
def _build_quota_alert(result: dict, quota_snapshot=None, runner=None,
primary_model: str | None = None) -> str:
"""Build quota alert string from stream event + API snapshot.
Priority: stream event ``status=rejected`` is authoritative (real-time).
For utilization percentages, prefer API snapshot (stream event lacks them).
Routes API snapshot by runner type:
- codex → Codex quota (cached 5min one-shot)
- claude → Claude QuotaPoller snapshot
- pi → route by primary model name (claude vs gpt/codex)
"""
import time as _time
parts = []
covered_windows: set[str] = set()
# 1. Stream event: rejected status (real-time, highest priority)
rli = result.get("rate_limit_info")
if rli and rli.get("status") == "rejected":
utilization = rli.get("utilization", 0)
resets_at = rli.get("resetsAt", 0)
limit_type = rli.get("rateLimitType", "")
label = "7 天" if "seven_day" in limit_type else "5 小时"
reset_str = ""
if resets_at:
remaining = max(0, resets_at - _time.time())
hours, mins = divmod(int(remaining) // 60, 60)
if remaining > 0:
reset_str = f",约 {hours}h{mins:02d}m 后重置"
parts.append(f"🚫 {label}配额已用尽({utilization:.0%}){reset_str}")
return "\n".join(parts)
# 2. Stream event: allowed_warning with utilization (if present)
if rli and rli.get("status") == "allowed_warning":
util = rli.get("utilization", 0)
if util >= 0.75:
limit_type = rli.get("rateLimitType", "")
win_key = "seven_day" if "seven_day" in limit_type else "five_hour"
label = "7 天" if win_key == "seven_day" else "5 小时"
resets_at = rli.get("resetsAt", 0)
reset_str = ""
if resets_at:
remaining = max(0, resets_at - _time.time())
hours, mins = divmod(int(remaining) // 60, 60)
if remaining > 0:
reset_str = f",约 {hours}h{mins:02d}m 后重置"
parts.append(f"⚠️ {label}配额 {util:.0%}{reset_str}")
covered_windows.add(win_key)
# 3. API snapshot — route by runner type
rt = _derive_runner_type(runner) if runner else "unknown"
is_deepseek = bool(primary_model and "deepseek" in primary_model.lower())
is_codex_model = bool(primary_model and ("codex" in primary_model.lower()
or "gpt" in primary_model.lower()))
if rt == "codex" or (rt == "pi" and is_codex_model):
# Codex path
codex_snap = _get_codex_quota_cached()
if codex_snap and codex_snap.available:
for key, label, pct, reset_epoch in [
("five_hour", "5h", codex_snap.primary_used_pct,
codex_snap.primary_resets_at),
("seven_day", "7d", codex_snap.secondary_used_pct,
codex_snap.secondary_resets_at),
]:
if key in covered_windows:
continue
if pct >= 50:
icon = "🔴" if pct >= 80 else "🟡"
remaining = max(0, reset_epoch - _time.time())
hours, mins = divmod(int(remaining) // 60, 60)
reset_str = f" 重置 {hours}h{mins:02d}m" if remaining > 0 else ""
parts.append(f"{icon} {label}: {pct:.0f}%{reset_str}")
elif is_deepseek:
# DeepSeek path — prepaid balance, warn when low
ds = _get_deepseek_balance_cached()
if ds and ds.available:
if ds.balance <= 0:
parts.append("🔴 DeepSeek 余额已耗尽")
elif ds.balance < 50:
parts.append(f"⚠️ DeepSeek 余额 ¥{ds.balance:.2f},建议充值")
else:
# Claude path — default / pi / unknown / backward-compat
if quota_snapshot and quota_snapshot.available and not quota_snapshot.stale:
for key, label in WINDOW_LABELS.items():
if key in covered_windows:
continue
w = quota_snapshot.windows.get(key)
if not w:
continue
util_pct = w.utilization # already in percentage (e.g. 18.0)
if util_pct >= 50:
icon = "🔴" if util_pct >= 80 else "🟡"
remaining = max(0, w.resets_at_epoch - _time.time())
hours, mins = divmod(int(remaining) // 60, 60)
reset_str = f" 重置 {hours}h{mins:02d}m" if remaining > 0 else ""
parts.append(f"{icon} {label}: {util_pct:.0f}%{reset_str}")
# 4. Cookie expiry warning (skip for codex/deepseek routes)
if rt not in ("codex",) and not is_deepseek and quota_snapshot:
cookie_warn = quota_snapshot.cookie_expiry_warning
if cookie_warn:
parts.append(cookie_warn)
return "\n".join(parts)
def _context_health_alert(result: dict, quota_snapshot=None, runner=None) -> str | None:
"""Check context utilization and return a plain alert string, or None.
Returns clean text (no ``---`` divider or leading newlines) suitable
for embedding in a card footer. The caller is responsible for
presentation formatting.
Uses ``peak_context_tokens`` (high-water mark before auto-compact)
when available, falling back to ``last_call_usage`` or ``usage``.
Also reports when auto-compact was detected so the user knows
earlier conversation turns may have been summarised.
Args:
quota_snapshot: Optional QuotaSnapshot from the API poller.
"""
# Determine context window size from provider-reported modelUsage only.
# max_ctx == 0 means "unknown, CLI owns this" — skip percentage-based alerts.
model_usage = result.get("modelUsage", {})
configured = getattr(runner, "model", None)
primary = pick_primary_model(model_usage, configured)
max_ctx = int(model_usage.get(primary, {}).get("contextWindow", 0) or 0) if primary else 0
rate_alert = _build_quota_alert(result, quota_snapshot, runner=runner,
primary_model=primary)
if max_ctx == 0:
return rate_alert or None
# If auto-compact was detected, alert with pre-compact peak usage
compact_detected = result.get("compact_detected", False)
peak_tokens = result.get("peak_context_tokens", 0)
if compact_detected and peak_tokens > 0:
peak_pct = peak_tokens / max_ctx * 100
return (
f"⚠️ 上下文已自动压缩(压缩前 {peak_pct:.0f}%)"
"— 早期对话可能被概括,建议关注上下文完整性"
)
# No compact — check current usage against thresholds
usage = result.get("last_call_usage") or result.get("usage")
if not usage:
return rate_alert or None
total_ctx = ((usage.get("input_tokens", 0) or 0)
+ (usage.get("cache_read_input_tokens", 0) or 0)
+ (usage.get("cache_creation_input_tokens", 0) or 0))
if total_ctx == 0:
return rate_alert or None
pct = total_ctx / max_ctx * 100
supports_compact = runner is None or runner.supports_compact()
tail_red = "`/compact` 压缩" if supports_compact else "`/new` 开始新会话"
tail_yellow = "`/compact` 压缩上下文" if supports_compact else "`/new` 开始新会话"
# Alert bands are relative to Claude Code's auto-compact threshold so
# the warning always fires *before* auto-compact kicks in, giving the
# user a window to run a directed /compact (which produces a better
# summary than auto-compact). CLAUDE_AUTOCOMPACT_PCT_OVERRIDE is the
# user's configured threshold (default 92); red = threshold-7,
# yellow = threshold-22. With default 92 → 70/85. With override=85
# (common tightened setting) → 63/78.
red_pct, yellow_pct = _compact_alert_thresholds()
if pct >= red_pct:
alert = f"🔴 Context {pct:.0f}% — 建议 `/new` 新会话或 {tail_red}"
return "\n".join(filter(None, [alert, rate_alert]))
if pct >= yellow_pct:
alert = f"🟡 Context {pct:.0f}% — 可考虑 {tail_yellow}"
return "\n".join(filter(None, [alert, rate_alert]))
return rate_alert or None
def _compact_alert_thresholds() -> tuple[int, int]:
"""Return (red_pct, yellow_pct) for context alerts.
Reads CLAUDE_AUTOCOMPACT_PCT_OVERRIDE env var (same name Claude CLI
uses) to stay in sync with the user's auto-compact trigger. Invalid
values fall back to Claude Code's default of 92.
"""
raw = os.environ.get("CLAUDE_AUTOCOMPACT_PCT_OVERRIDE")
threshold = 92
if raw:
try:
parsed = int(raw)
if 40 <= parsed <= 99:
threshold = parsed
except ValueError:
pass
return (threshold - 7, threshold - 22)
def format_task_detail_bridge(task: dict) -> str:
"""Format task detail for bridge-level display (completed tasks)."""
import datetime as _dt
lines = []
lines.append(f"**{task.get('summary', '未命名任务')}**")
lines.append("状态: ✅ 已完成")
guid = task.get("guid", "?")
lines.append(f"GUID: `{guid}`")
desc = task.get("description", "")
if desc:
lines.append(f"描述: {desc[:200]}")
due = task.get("due")
if due and due.get("timestamp"):
ts = int(str(due["timestamp"])[:10])
due_dt = _dt.datetime.fromtimestamp(ts)
lines.append(f"截止: {due_dt.strftime('%Y-%m-%d %H:%M')}")
return "\n".join(lines)
def _write_auth_file(chat_id: str, sender_id: str, user_token: str | None) -> str:
"""Write a temporary auth file for feishu_cli.py.
Returns the file path. Caller must clean up in finally block.
"""
auth_path = f"/tmp/feishu_auth_{uuid.uuid4()}.json"
fd = os.open(auth_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
try:
with os.fdopen(fd, "w") as f:
json.dump({
"user_access_token": user_token,
"chat_id": chat_id,
"sender_id": sender_id,
}, f)
except BaseException:
try:
os.unlink(auth_path)
except OSError:
pass
raise
return auth_path
_SESSION_ENV_PATH = os.path.expanduser("~/.feishu-bridge/session.env")
def _write_session_env(env_extra: dict[str, str]) -> None:
"""Persist hook-visible env vars to a file.
Claude Code's SUBPROCESS_ENV_SCRUB strips env from hook subprocesses.
Hooks source this file to recover FEISHU_CHAT_ID etc.
"""
lines = [f"{k}={v}" for k, v in env_extra.items() if v]
tmp = _SESSION_ENV_PATH + ".tmp"
try:
with open(tmp, "w") as f:
f.write("\n".join(lines) + "\n")
os.replace(tmp, _SESSION_ENV_PATH)
except OSError:
pass
def _cleanup_auth_card(feishu_mod, sender_id: str):
"""Best-effort cleanup of the OAuth auth card after result delivery."""
if not feishu_mod or not sender_id:
return
try:
feishu_mod.cleanup_auth_card(sender_id)
except Exception:
log.warning("Failed to cleanup auth card for %s", sender_id[:8],
exc_info=True)
def _bg_mark_dequeued(item: dict) -> None:
"""Stamp bg_runs.enqueued_at at worker pickup time, not watcher CAS time.
Scopes the watcher's 5-min stuck-rollback (design.md:391) to "worker
picked up but never ack'd" — i.e. genuine bridge-crash recovery — rather
than bounding total queue-wait + turn-processing time. Without this,
long turns (backlog + Claude latency >5 min) race the rollback and cause
duplicate delivery.
Idempotent: the CAS guard requires delivery_state='enqueued' AND
enqueued_at IS NULL, so a re-fire on the same item (or a worker that
already stamped then failed to ack) is a silent no-op.
"""
run_id = item.get("_bg_run_id")
db_path = item.get("_bg_db_path")
if run_id is None or not db_path:
return
try:
from feishu_bridge.bg_tasks_db import connect
except Exception:
log.warning("_bg_mark_dequeued: bg_tasks_db import failed", exc_info=True)
return
try:
conn = connect(str(db_path))
except Exception:
log.warning("_bg_mark_dequeued: DB connect failed for run=%s",
run_id, exc_info=True)
return
try:
now_ms = int(time.time() * 1000)
conn.execute(
"UPDATE bg_runs SET enqueued_at=? "
"WHERE id=? AND delivery_state='enqueued' AND enqueued_at IS NULL",
(now_ms, run_id),
)
except Exception:
log.warning("_bg_mark_dequeued: UPDATE failed for run=%s",
run_id, exc_info=True)
finally:
try:
conn.close()
except Exception:
pass
def _bg_mark_delivery_outcome(item: dict, delivered: bool,
*, error: str | None = None) -> None:
"""Mark the bg-task outbox row after worker hand-off to Feishu.
No-op when the item is not a bg_task_completion (``_bg_run_id`` missing)
or the bridge has no bg_tasks DB path wired yet. Failures are swallowed
with a warning — the stuck_enqueued rollback (5 min) reclaims orphaned
rows, so a crash here only delays retry, it doesn't strand the task.
"""
run_id = item.get("_bg_run_id")
db_path = item.get("_bg_db_path")
if run_id is None or not db_path:
return
try:
from feishu_bridge.bg_tasks_db import BgTaskRepo, connect
except Exception:
log.warning("_bg_mark_delivery_outcome: bg_tasks_db import failed",
exc_info=True)
return
new_state = "sent" if delivered else "delivery_failed"
err_msg = None if delivered else (error or "deliver_returned_false")
now_ms = int(time.time() * 1000)
try:
conn = connect(str(db_path))
except Exception:
log.warning("_bg_mark_delivery_outcome: DB connect failed for run=%s",
run_id, exc_info=True)
return
try:
repo = BgTaskRepo(conn)
# CAS on 'enqueued' — the watcher flipped the row there before
# enqueuing us; a double-fire (e.g. duplicate queue item) on the
# same run_id finds delivery_state already 'sent' and no-ops.
ok = repo.mark_delivery_state(
run_id,
new_state,
error=err_msg,
bump_attempt=not delivered,
sent_at=now_ms if delivered else None,
expected_from="enqueued",
)
if not ok:
log.info("_bg_mark_delivery_outcome: CAS lost for run=%s "
"(state not 'enqueued'); skipping", run_id)
except Exception:
log.warning("_bg_mark_delivery_outcome: mark_delivery_state failed "
"for run=%s", run_id, exc_info=True)
finally:
try:
conn.close()
except Exception:
pass
def _footer_project_label(bound: dict | None, resolved_workspace: str) -> str:
"""Footer project label for the final card.
Returns the ``/project``-bound ``project_id`` when this thread is bound,
else the directory name of the workspace the turn actually ran in. Mirrors
the old git-branch readout's "empty → omitted" behaviour: an empty/blank
workspace yields ``""``, which the footer builder drops.
"""
if bound:
return bound["project_id"]
return Path(resolved_workspace).name if resolved_workspace else ""
def process_message(
item: dict,
bot_config: dict,
lark_client,
session_map: SessionMap,
runner: BaseRunner,
feishu_tasks=None,
feishu_docs=None,
feishu_sheets=None,
feishu_api_error_cls=None,
response_handle_cls=ResponseHandle,
download_image_fn=download_image,
download_file_fn=download_file,
fetch_card_content_fn=fetch_card_content,
fetch_forward_messages_fn=fetch_forward_messages,
fetch_quoted_message_fn=fetch_quoted_message,
remove_typing_indicator_fn=remove_typing_indicator,
session_not_found_signatures=None,
thread_projects=None,
):
"""Process a single message from the work queue."""
bot_id = item["bot_id"]
chat_id = item["chat_id"]
thread_id = item.get("thread_id")
parent_id = item.get("parent_id")
sender_id = item.get("sender_id", "")
text = item.get("text", "")
original_text = text # [R3 code-review M1] Heuristic decisions MUST use
# the user's raw message, not the post-enrichment
# text (quoted message / card / attachment notices
# would otherwise leak history-trigger words).
image_key = item.get("image_key")
file_key = item.get("file_key")
file_name = item.get("file_name")
message_id = item.get("message_id")
key = (bot_id, chat_id, thread_id)
tag = SessionMap.format_key(key)
# ── Stage 2: thread→project binding + heuristic project intent ──
# bound != None → user explicitly /project'd this thread
# bound == None → fall back to default workspace; record heuristic match
# (if any) so the worker can append a binding-suggestion
# suffix to the reply without writing the table (D6).
bound = thread_projects.get(tag) if thread_projects is not None else None
resolved_workspace = bound["workspace"] if bound else bot_config["workspace"]
project_workspace = bound["workspace"] if bound else None
global_workspace = bot_config["workspace"] # [R2] source 1/2 恒走 ~/.claude
heuristic_match = None
if bound is None and thread_projects is not None and (original_text or "").strip():
try:
from feishu_bridge.project_detector import detect_project_intent
from feishu_bridge.state_thread_projects import parse_projects_registry
registry_path = (
resolve_dotclaude_root(global_workspace) / "memory" / "projects.md"
)
if registry_path.exists():
_registry = parse_projects_registry(
registry_path.read_text(encoding="utf-8")
)
heuristic_match = detect_project_intent(original_text, _registry)
except (OSError, UnicodeError) as exc:
log.warning("project detector failed: %s", exc)
handle = response_handle_cls(lark_client, chat_id, thread_id, message_id,
bot_id=bot_id)
image_path = None
file_path = None
auth_file_path = None
# Prefer runner's own signatures; fall back to caller-provided list for compat
session_not_found_signatures = (
runner.get_session_not_found_signatures()
if hasattr(runner, 'get_session_not_found_signatures')
else session_not_found_signatures or []
)
try:
handle._runner = runner
handle._runner_tag = tag
if image_key and message_id:
image_path = download_image_fn(
lark_client, message_id, image_key, resolved_workspace
)
if image_path:
text = (
f"{text}\n\n[用户发送了一张图片,"
f"已保存到 {image_path},请查看并回复]"
)
else:
text = f"{text}\n\n[用户发送了一张图片,但下载失败]"
if file_key and message_id:
display_name = file_name or "attachment"
file_path = download_file_fn(
lark_client, message_id, file_key, display_name,
resolved_workspace,
)
if file_path:
text = (
f"{text}\n\n[用户发送了文件: {display_name},"
f"已保存到 {file_path},请查看并回复]"
)
else:
text = f"{text}\n\n[用户发送了文件: {display_name},但下载失败]"
should_fetch_quote = (
(parent_id and not thread_id)
or (parent_id and thread_id and not session_map.get(key))
)
if should_fetch_quote:
quoted = fetch_quoted_message_fn(lark_client, parent_id)
if quoted:
st = quoted["sender_type"]
sender_label = "Bot" if st == "app" else ("User" if st == "user" else "Unknown")
quote_header = f"[引用消息 message_id={parent_id} from={sender_label}]"
text = f"{quote_header}\n{quoted['content']}\n[/引用消息]\n\n{text}"
# --- Re-fetch degraded card content via API ---
# Replace the placeholder (always at the end of text, after any quote prefix).
# Use rfind to target the last occurrence — avoids replacing identical text
# that might appear inside a prepended quote block.
card_mid = item.get("_card_message_id")
if card_mid and fetch_card_content_fn:
card_text = fetch_card_content_fn(lark_client, card_mid)
if card_text:
original_text = item.get("text", "")
if original_text:
pos = text.rfind(original_text)
if pos >= 0:
text = text[:pos] + card_text + text[pos + len(original_text):]
else:
text = card_text
else:
text = card_text
log.info("Re-fetched card content for %s", card_mid)
# --- Expand merge_forward sub-messages via API ---
forward_mid = item.get("_merge_forward_message_id")
if forward_mid and fetch_forward_messages_fn:
forward_text = fetch_forward_messages_fn(lark_client, forward_mid)
if forward_text:
original_text = item.get("text", "")
if original_text:
pos = text.rfind(original_text)
if pos >= 0:
text = text[:pos] + forward_text + text[pos + len(original_text):]
else:
text = forward_text
else:
text = forward_text
log.info("Expanded merge_forward for %s", forward_mid)
# --- Auto-fetch Feishu doc/wiki/sheet content from URLs in message ---
feishu_urls = item.get("_feishu_urls") or []
if feishu_urls and (feishu_docs or feishu_sheets) and feishu_api_error_cls:
import requests as _requests
# Silent per-service token check: auto-fetch must NOT trigger OAuth.
# get_cached_token() returns None without sending auth cards.
_doc_token = feishu_docs.get_cached_token(sender_id) if feishu_docs else None
_sheet_token = feishu_sheets.get_cached_token(sender_id) if feishu_sheets else None
fetched_parts = []
# Count doc-type URLs for adaptive fetch strategy:
# single short doc → full content; single long / multi → preview only
_doc_url_count = sum(1 for t, _ in feishu_urls
if t in ("doc", "docx", "wiki"))
for url_type, url_token in feishu_urls:
try:
if url_type == "wiki":
# Wiki links need doc token for node resolution
if not feishu_docs or not _doc_token:
fetched_parts.append(
f"[飞书链接 wiki/{url_token}: 未授权,使用 lark docs +fetch --doc {url_token} 查看]"
)
continue
try:
node_data = feishu_docs.request(
"GET", "/open-apis/wiki/v2/spaces/get_node",
_doc_token, params={"token": url_token})
node = node_data.get("node", {})
obj_type = node.get("obj_type", "doc")
obj_token = node.get("obj_token", url_token)
except feishu_api_error_cls:
# Fallback: treat as doc
obj_type = "doc"
obj_token = url_token
if obj_type not in ("doc", "docx", "wiki", "sheet"):
fetched_parts.append(
f"[飞书wiki {url_token}: 不支持的节点类型 {obj_type},请直接在飞书中打开]"
)
continue
if obj_type == "sheet":
# Redirect to sheets handler
if not feishu_sheets or not _sheet_token:
fetched_parts.append(
f"[飞书表格 {url_token}: 未授权,使用 lark sheets +read --token {url_token} 查看]"
)
continue
result = feishu_sheets.info(
chat_id, sender_id, obj_token, prefetched_token=_sheet_token)
if result is None:
continue
spreadsheet = result.get("spreadsheet", result)
title = spreadsheet.get("title", url_token)
sheets_list = result.get("sheets", [])
sheet_names = [s.get("title", "?") for s in sheets_list[:10]]
fetched_parts.append(
f"[飞书表格: {title}]\n"
f"工作表: {', '.join(sheet_names)}\n"
f"(使用 `/feishu-sheet read {obj_token} <sheet>!<range>` 读取具体数据)\n"
f"[/飞书表格]"
)
continue
# doc/docx/wiki doc — fetch via MCP
result = feishu_docs.fetch(
chat_id, sender_id, doc_id=obj_token, prefetched_token=_doc_token)
if result is None:
continue
title = result.get("title", "")
md = result.get("markdown", "")
if not md:
md = result.get("text", str(result))
header = f"[飞书文档: {title}]" if title else f"[飞书文档 {url_token}]"
cli_hint = f"lark docs +fetch --doc {obj_token}"
if _doc_url_count >= 2 and len(md) > 200:
preview = md[:200].rstrip()
fetched_parts.append(
f"{header}\n{preview}...\n"
f"(共 {len(md)} 字,使用 `{cli_hint}` 获取全文)\n[/飞书文档]")
elif len(md) >= 2000:
preview = md[:500].rstrip()
fetched_parts.append(
f"{header}\n{preview}...\n"
f"(共 {len(md)} 字,使用 `{cli_hint}` 获取全文)\n[/飞书文档]")
else:
fetched_parts.append(f"{header}\n{md}\n[/飞书文档]")
continue
if url_type in ("doc", "docx"):
if not feishu_docs or not _doc_token:
fetched_parts.append(
f"[飞书链接 {url_type}/{url_token}: 未授权,使用 lark docs +fetch --doc {url_token} 查看]"
)
continue
result = feishu_docs.fetch(
chat_id, sender_id, doc_id=url_token, prefetched_token=_doc_token)
if result is None:
continue