Repository navigation
Expand file tree
/
Copy pathui.py
More file actions
2211 lines (1966 loc) · 84.2 KB
/
Copy pathui.py
File metadata and controls
2211 lines (1966 loc) · 84.2 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
"""Feishu UI delivery helpers for Feishu bridge."""
import copy
import json
import logging
import os.path
import re
import threading
import time
import urllib.parse
import uuid
from typing import Optional
from lark_oapi.api.cardkit.v1 import (
CreateCardRequest,
CreateCardRequestBody,
ContentCardElementRequest,
ContentCardElementRequestBody,
SettingsCardRequest,
SettingsCardRequestBody,
UpdateCardRequest,
UpdateCardRequestBody,
)
from lark_oapi.api.cardkit.v1.model import Card
from lark_oapi.api.im.v1 import (
CreateMessageRequest,
CreateMessageRequestBody,
PatchMessageRequest,
PatchMessageRequestBody,
)
from feishu_bridge.runtime import ClaudeRunner
log = logging.getLogger("feishu-bridge")
MESSAGE_TERMINAL_CODES = {230011, 231003}
# ---------------------------------------------------------------------------
# Markdown style optimization for Feishu CardKit v2
# ---------------------------------------------------------------------------
# Feishu markdown renders a limited subset of standard markdown.
# This adapter handles: heading downgrade, table/code-block spacing,
# invalid image cleanup, and blank-line compression.
# Ported from openclaw-lark/src/card/markdown-style.js.
_CB_MARK = "___CB_"
_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\(([^)\s]+)\)")
def optimize_markdown_style(text: str) -> str:
"""Adapt standard markdown for Feishu CardKit v2 rendering."""
try:
r = _optimize_impl(text)
r = _strip_invalid_image_keys(r)
return r
except Exception:
return text
def _optimize_impl(text: str) -> str:
# 1. Extract code blocks → placeholders
code_blocks: list[str] = []
def _save(m):
code_blocks.append(m.group(0))
return f"{_CB_MARK}{len(code_blocks) - 1}___"
r = re.sub(r"```[\s\S]*?```", _save, text)
# 2. Heading downgrade: H1→H4, H2-H6→H5 (only when H1-H3 present)
if re.search(r"^#{1,3} ", r, re.MULTILINE):
r = re.sub(r"^#{2,6} (.+)$", r"##### \1", r, flags=re.MULTILINE)
r = re.sub(r"^# (.+)$", r"#### \1", r, flags=re.MULTILINE)
# 3. Consecutive headings: insert <br> gap
r = re.sub(
r"^(#{4,5} .+)\n{1,2}(#{4,5} )",
r"\1\n<br>\n\2", r, flags=re.MULTILINE,
)
# 4. Table spacing
# 4a. Non-table line → table: ensure blank line
r = re.sub(r"^([^|\n].*)\n(\|.+\|)", r"\1\n\n\2", r, flags=re.MULTILINE)
# 4b. Blank line before table block → insert <br>
r = re.sub(r"\n\n((?:\|.+\|[^\S\n]*\n?)+)", r"\n\n<br>\n\n\1", r)
# 4c. After table block → append <br>
r = re.sub(
r"((?:^\|.+\|[^\S\n]*\n?)+)", r"\1\n<br>\n", r, flags=re.MULTILINE,
)
# 4d. Plain text before table: tighten spacing
r = re.sub(
r"^((?!#{4,5} )(?!\*\*).+)\n\n(<br>)\n\n(\|)",
r"\1\n\2\n\3", r, flags=re.MULTILINE,
)
# 4d2. Bold line before table
r = re.sub(
r"^(\*\*.+)\n\n(<br>)\n\n(\|)",
r"\1\n\2\n\n\3", r, flags=re.MULTILINE,
)
# 4e. Table → plain text: tighten spacing
r = re.sub(
r"(\|[^\n]*\n)\n(<br>\n)((?!#{4,5} )(?!\*\*))",
r"\1\2\3", r, flags=re.MULTILINE,
)
# 5. Restore code blocks with <br> spacing
for i, block in enumerate(code_blocks):
r = r.replace(f"{_CB_MARK}{i}___", f"\n<br>\n{block}\n<br>\n")
# 6. Compress 3+ newlines → 2
r = re.sub(r"\n{3,}", "\n\n", r)
return r
def _strip_invalid_image_keys(text: str) -> str:
"""Remove  where url is not a Feishu img_xxx key."""
if "![" not in text:
return text
return _IMAGE_RE.sub(
lambda m: m.group(0) if m.group(2).startswith("img_") else "", text,
)
# ---------------------------------------------------------------------------
# P0: URL extraction + sidebar applink
# ---------------------------------------------------------------------------
_URL_RE = re.compile(r'(?<!\()\bhttps://\S+')
_IMAGE_URL_RE = re.compile(r'!\[[^\]]*\]\(([^)\s]+)\)')
SIDEBAR_APPLINK = "https://applink.feishu.cn/client/web_url/open"
_MAX_SIDEBAR_URLS = 3
_MAX_URL_LABEL_LEN = 40
def extract_urls(content: str) -> list[str]:
"""Extract unique https:// URLs from content, excluding markdown image URLs."""
image_urls = set(_IMAGE_URL_RE.findall(content))
seen: set[str] = set()
result: list[str] = []
for m in _URL_RE.finditer(content):
url = m.group().rstrip('.,;:!?)>]')
if url in seen or url in image_urls:
continue
seen.add(url)
result.append(url)
if len(result) >= _MAX_SIDEBAR_URLS:
break
return result
def _url_label(url: str) -> str:
"""Generate a short label for a URL: hostname/path_tail, max 40 chars."""
parsed = urllib.parse.urlparse(url)
host = parsed.hostname or ""
path = parsed.path.rstrip("/")
tail = path.rsplit("/", 1)[-1] if "/" in path else path
label = f"{host}/{tail}" if tail else host
if len(label) > _MAX_URL_LABEL_LEN:
label = label[:_MAX_URL_LABEL_LEN - 1] + "…"
return label
def to_sidebar_url(url: str) -> str:
"""Generate a Feishu sidebar applink URL."""
return f"{SIDEBAR_APPLINK}?mode=sidebar-semi&url={urllib.parse.quote(url, safe='')}"
def _build_url_buttons(content: str) -> list[dict]:
"""Build CardKit v2 button elements for sidebar links from content URLs."""
urls = extract_urls(content)
buttons = []
for url in urls:
sidebar = to_sidebar_url(url)
buttons.append({
"tag": "button",
"text": {"tag": "plain_text", "content": f"🔗 {_url_label(url)}"},
"type": "default",
"size": "small",
"multi_url": {
"url": sidebar,
"pc_url": sidebar,
"android_url": url,
"ios_url": url,
},
})
return buttons
# ---------------------------------------------------------------------------
# P1: Action marker protocol (strip / parse / button generation)
# ---------------------------------------------------------------------------
_MARKER_RE = re.compile(r'<!--\s*feishu:\w+\s+.*?-->', re.DOTALL)
_MARKER_PARSE_RE = re.compile(
r'<!--\s*feishu:(?P<type>confirm|ask|choices)\s+(?P<json>.*?)-->',
re.DOTALL,
)
def strip_action_markers(text: str) -> str:
"""Lightweight strip of all feishu action markers (for streaming path)."""
return _MARKER_RE.sub('', text)
def parse_action_markers(content: str) -> tuple[str, list[dict]]:
"""Parse and extract action markers from content.
Returns (clean_content, markers) where each marker is:
{"type": "confirm|ask|choices", "payload": <parsed JSON>}
"""
markers: list[dict] = []
for m in _MARKER_PARSE_RE.finditer(content):
try:
payload = json.loads(m.group("json").strip())
markers.append({"type": m.group("type"), "payload": payload})
except (json.JSONDecodeError, ValueError):
log.debug("Failed to parse action marker: %s", m.group(0)[:80])
clean = _MARKER_RE.sub('', content)
return clean, markers
def _build_action_buttons(markers: list[dict],
chat_id: str | None = None,
bot_id: str | None = None) -> list[dict]:
"""Convert parsed action markers into CardKit v2 button elements."""
if not markers or not chat_id or not bot_id:
return []
buttons: list[dict] = []
for marker in markers:
mtype = marker["type"]
payload = marker["payload"]
if mtype == "confirm":
buttons.append(_action_button(
"✅ 确认", mtype, "确认", chat_id, bot_id,
btn_type="primary_filled"))
buttons.append(_action_button(
"❌ 取消", mtype, "取消", chat_id, bot_id,
btn_type="danger"))
elif mtype == "choices":
# payload is a list of strings
if isinstance(payload, list):
for opt in payload:
buttons.append(_action_button(
str(opt), mtype, str(opt), chat_id, bot_id))
elif mtype == "ask":
# payload has "options" list with "label" keys
options = payload.get("options", [])
for opt in options:
label = opt.get("label", "") if isinstance(opt, dict) else str(opt)
buttons.append(_action_button(
label, mtype, label, chat_id, bot_id))
return buttons
def _prune_card_cache() -> None:
"""Remove expired entries; evict oldest when over capacity.
Caller must hold _card_cache_lock.
"""
now = time.time()
expired = [k for k, (exp, _) in _card_cache.items() if now > exp]
for k in expired:
del _card_cache[k]
while len(_card_cache) > _CARD_CACHE_MAX_SIZE:
oldest = min(_card_cache, key=lambda k: _card_cache[k][0])
del _card_cache[oldest]
def rebuild_card_with_selection(card_ref: str,
selected_label: str) -> dict | None:
"""Rebuild a cached card with selected button highlighted and others disabled.
Returns a v2 card dict ready for callback response, or None on cache miss.
"""
with _card_cache_lock:
entry = _card_cache.pop(card_ref, None)
if not entry:
return None
expiry, card = entry
if time.time() > expiry:
return None
card = copy.deepcopy(card)
# Walk elements to find action-button column_sets and update their state
for element in card["body"]["elements"]:
if element.get("tag") != "column_set":
continue
for col in element.get("columns", []):
buttons = col.get("elements", [])
has_action = any(
b.get("tag") == "button" and "action" in b.get("value", {})
for b in buttons
)
if not has_action:
continue
for btn in buttons:
if btn.get("tag") != "button":
continue
value = btn.get("value", {})
if "action" not in value:
continue
if value.get("label") == selected_label:
text = btn["text"]["content"]
if not text.startswith("✅"):
btn["text"]["content"] = f"✅ {text}"
btn["type"] = "primary_filled"
else:
btn["type"] = "default"
btn["disabled"] = True
# Remove callback value so disabled buttons don't trigger
btn.pop("value", None)
# Override config for callback response
card["config"] = {"update_multi": True}
return card
def _action_button(text: str, action: str, label: str,
chat_id: str, bot_id: str,
btn_type: str = "primary",
btn_size: str = "medium") -> dict:
return {
"tag": "button",
"text": {"tag": "plain_text", "content": text},
"type": btn_type,
"size": btn_size,
"value": {
"action": action,
"label": label,
"chat_id": chat_id,
"bot_id": bot_id,
},
}
_unavailable_messages: dict[str, dict] = {}
_UNAVAILABLE_TTL = 30 * 60
_UNAVAILABLE_MAX_SIZE = 512
# Card cache for preserving original content on button callbacks
_card_cache: dict[str, tuple[float, dict]] = {} # card_ref → (expiry_ts, card_dict)
_card_cache_lock = threading.Lock()
_CARD_CACHE_TTL = 2 * 3600 # 2 hours
_CARD_CACHE_MAX_SIZE = 256
MAX_DIV_CHARS = 10_000
MAX_CARD_PAYLOAD_BYTES = 28 * 1024
COMPACT_MAX_CHARS = 4_000
CARDKIT_ELEMENT_ID = "streaming_output"
CARDKIT_AGENT_ELEMENT_ID = "agent_status"
CARDKIT_THROTTLE_MS = 100
PATCH_THROTTLE_MS = 1500
GAP_THRESHOLD_MS = 2000
BATCH_AFTER_GAP_MS = 100 # 降低gap后的恢复延迟,从300ms减少到100ms
# Bot display name (fetched from Feishu API at startup)
_bot_display_name = "Claude Code"
def set_bot_display_name(name: str):
global _bot_display_name
_bot_display_name = name
def build_restart_card(message: str = "") -> dict:
"""Blue card shown when bridge is about to restart."""
text = message or "正在重启,约 10 秒后恢复..."
return {
"config": {"wide_screen_mode": True},
"header": {
"title": {"content": f"⏳ {_bot_display_name}", "tag": "plain_text"},
"template": "blue",
},
"elements": [{
"tag": "div",
"text": {"content": text, "tag": "lark_md"},
}],
}
def build_restart_complete_card(version: str = "") -> dict:
"""Green card patched after bridge restarts successfully."""
text = f"已更新到 v{version}" if version else "重启完成"
return {
"config": {"wide_screen_mode": True},
"header": {
"title": {"content": f"✅ {_bot_display_name}", "tag": "plain_text"},
"template": "green",
},
"elements": [{
"tag": "div",
"text": {"content": text, "tag": "lark_md"},
}],
}
def _prune_unavailable_cache():
now = time.monotonic()
expired = [mid for mid, state in list(_unavailable_messages.items())
if now - state["ts"] > _UNAVAILABLE_TTL]
for mid in expired:
_unavailable_messages.pop(mid, None)
def mark_message_unavailable(message_id: str, code: int):
if len(_unavailable_messages) >= _UNAVAILABLE_MAX_SIZE:
_prune_unavailable_cache()
_unavailable_messages[message_id] = {"code": code, "ts": time.monotonic()}
log.info("Message marked unavailable: %s code=%d", message_id, code)
def is_message_unavailable(message_id: str) -> bool:
state = _unavailable_messages.get(message_id)
if not state:
return False
if time.monotonic() - state["ts"] > _UNAVAILABLE_TTL:
_unavailable_messages.pop(message_id, None)
return False
return True
def _check_terminal_code(resp, message_id: str) -> bool:
if resp and not resp.success() and resp.code in MESSAGE_TERMINAL_CODES:
mark_message_unavailable(message_id, resp.code)
return True
return False
def add_queued_reaction(lark_client, message_id: str) -> str | None:
"""Add ⏳ emoji reaction to user's message."""
if is_message_unavailable(message_id):
return None
try:
from lark_oapi.api.im.v1 import (
CreateMessageReactionRequest, CreateMessageReactionRequestBody,
)
from lark_oapi.api.im.v1.model.emoji import Emoji
body = CreateMessageReactionRequestBody.builder() \
.reaction_type(Emoji.builder().emoji_type("OneSecond").build()) \
.build()
req = CreateMessageReactionRequest.builder() \
.message_id(message_id) \
.request_body(body) \
.build()
resp = lark_client.im.v1.message_reaction.create(req)
if resp.success() and resp.data:
return resp.data.reaction_id
_check_terminal_code(resp, message_id)
log.debug("Queued reaction add failed: code=%s msg=%s", resp.code, resp.msg)
except Exception:
log.debug("Queued reaction add error", exc_info=True)
return None
def remove_queued_reaction(lark_client, message_id: str,
reaction_id: str | None):
if not reaction_id:
return
if is_message_unavailable(message_id):
return
try:
from lark_oapi.api.im.v1 import DeleteMessageReactionRequest
req = DeleteMessageReactionRequest.builder() \
.message_id(message_id) \
.reaction_id(reaction_id) \
.build()
resp = lark_client.im.v1.message_reaction.delete(req)
if not resp.success():
log.debug("Queued reaction remove failed: code=%s msg=%s",
resp.code, resp.msg)
except Exception:
log.debug("Queued reaction remove error", exc_info=True)
class FlushController:
"""Non-blocking throttle for streaming card updates."""
def __init__(self, flush_fn, use_cardkit: bool):
self._lock = threading.Lock()
self._flush_fn = flush_fn
self._throttle_ms = CARDKIT_THROTTLE_MS if use_cardkit else PATCH_THROTTLE_MS
self._flush_in_progress = False
self._needs_reflush = False
self._last_flush_time = 0.0
self._pending_text = ""
self._timer: Optional[threading.Timer] = None
self._card_ready = False
self._closed = False
self._consecutive_failures = 0
self._FAILURE_THRESHOLD = 5
def set_card_ready(self):
with self._lock:
self._card_ready = True
if self._pending_text and not self._closed:
self._execute_flush()
def request_flush(self, text: str):
with self._lock:
if self._closed:
return
self._pending_text = text
if not self._card_ready:
return
if self._flush_in_progress:
self._needs_reflush = True
return
elapsed_ms = (time.time() - self._last_flush_time) * 1000
if elapsed_ms >= self._throttle_ms:
if elapsed_ms >= GAP_THRESHOLD_MS and self._last_flush_time > 0:
self._schedule_locked(BATCH_AFTER_GAP_MS / 1000)
else:
self._execute_flush()
else:
remaining = (self._throttle_ms - elapsed_ms) / 1000
self._schedule_locked(remaining)
def drain(self):
text_to_flush = None
with self._lock:
self._closed = True
self._needs_reflush = False
if self._timer:
self._timer.cancel()
self._timer = None
if (self._pending_text and self._card_ready
and not self._flush_in_progress):
text_to_flush = self._pending_text
deadline = time.time() + 3.0
while True:
with self._lock:
if not self._flush_in_progress:
break
if time.time() >= deadline:
log.warning("FlushController drain: timed out waiting for in-flight flush")
break
time.sleep(0.02)
if not text_to_flush:
with self._lock:
if (self._pending_text and self._card_ready
and not self._flush_in_progress):
text_to_flush = self._pending_text
if text_to_flush:
try:
self._flush_fn(text_to_flush)
except Exception:
log.exception("FlushController drain error")
def _schedule_locked(self, delay_sec: float):
if self._timer:
self._timer.cancel()
self._timer = threading.Timer(delay_sec, self._on_timer)
self._timer.daemon = True
self._timer.start()
def _execute_flush(self):
self._flush_in_progress = True
self._needs_reflush = False
text = self._pending_text
if self._timer:
self._timer.cancel()
self._timer = None
threading.Thread(target=self._do_flush, args=(text,), daemon=True).start()
def _on_timer(self):
with self._lock:
if self._closed or not self._card_ready or self._flush_in_progress:
if self._flush_in_progress and not self._closed:
self._needs_reflush = True
return
self._execute_flush()
def _do_flush(self, text: str):
try:
self._flush_fn(text)
self._consecutive_failures = 0 # 成功重置计数
except Exception:
self._consecutive_failures += 1
if self._consecutive_failures >= self._FAILURE_THRESHOLD:
log.error("FlushController: %d consecutive failures, streaming may be stalled",
self._consecutive_failures)
log.exception("FlushController flush error")
finally:
with self._lock:
self._last_flush_time = time.time()
self._flush_in_progress = False
if (not self._closed and self._needs_reflush
and self._pending_text and self._card_ready):
self._execute_flush()
def build_card(content: str, is_error: bool = False,
compact: bool = False) -> dict:
if compact and len(content) > COMPACT_MAX_CHARS:
content = content[:COMPACT_MAX_CHARS] + "\n\n…(已截断)"
chunks = []
remaining = content
while remaining:
if len(remaining) <= MAX_DIV_CHARS:
chunks.append(remaining)
break
split_at = MAX_DIV_CHARS
for sep in ["\n", " "]:
idx = remaining.rfind(sep, 0, split_at)
if idx > split_at // 2:
split_at = idx + 1
break
chunks.append(remaining[:split_at])
remaining = remaining[split_at:]
if not chunks:
chunks = ["(空回复)"]
elements = [
{"tag": "div", "text": {"content": chunk, "tag": "lark_md"}}
for chunk in chunks
]
# Update notification (IM patch fallback path)
from feishu_bridge.updater import get_update_banner_text
_banner = get_update_banner_text()
if _banner:
elements.append({
"tag": "div",
"text": {"content": _banner, "tag": "lark_md"},
})
title_text = "❌ 错误" if is_error else f"✅ {_bot_display_name}"
template = "red" if is_error else "green"
card = {
"config": {"wide_screen_mode": True},
"header": {
"title": {"content": title_text, "tag": "plain_text"},
"template": template,
},
"elements": elements,
}
payload = json.dumps(card, ensure_ascii=False).encode("utf-8")
if len(payload) > MAX_CARD_PAYLOAD_BYTES and not compact:
return build_card(content, is_error, compact=True)
return card
def build_processing_card() -> dict:
return {
"config": {"wide_screen_mode": True},
"header": {"title": {"content": "🤔 处理中...", "tag": "plain_text"},
"template": "blue"},
"elements": [{
"tag": "div",
"text": {"content": "正在处理你的请求,请稍候...", "tag": "lark_md"},
}],
}
def build_streaming_card(content: str) -> dict:
if len(content) > COMPACT_MAX_CHARS:
content = "…(前文已省略)\n\n" + content[-COMPACT_MAX_CHARS:]
return {
"config": {"wide_screen_mode": True},
"header": {"title": {"content": "⏳ 生成中...", "tag": "plain_text"},
"template": "blue"},
"elements": [
{"tag": "div", "text": {"content": content, "tag": "lark_md"}}
],
}
def build_cardkit_streaming_card() -> dict:
return {
"schema": "2.0",
"config": {
"streaming_mode": True,
"enable_forward": False,
"summary": {"content": "思考中..."},
},
"body": {
"elements": [
{
"tag": "markdown",
"element_id": CARDKIT_ELEMENT_ID,
"content": "",
},
{
"tag": "markdown",
"element_id": CARDKIT_AGENT_ELEMENT_ID,
"content": "",
},
],
},
}
def _format_elapsed(seconds: float) -> str:
if seconds < 60:
return f"{seconds:.1f}s"
minutes = int(seconds // 60)
secs = seconds % 60
return f"{minutes}m{secs:.0f}s"
def _format_tokens(n: int) -> str:
if n >= 1_000_000:
return f"{n / 1_000_000:.1f}M"
if n >= 1_000:
return f"{n / 1_000:.1f}k"
return str(n)
def _format_usage_footer(usage: dict) -> str:
"""Format last_call_usage into a compact footer string.
Examples:
"12.3k in (85% ⚡) · 1.2k out" — cache hit
"12.3k in · 1.2k out" — no cache / cold start
"""
inp = (usage.get("input_tokens", 0) or 0)
cache_read = (usage.get("cache_read_input_tokens", 0) or 0)
cache_create = (usage.get("cache_creation_input_tokens", 0) or 0)
out = (usage.get("output_tokens", 0) or 0)
total_in = inp + cache_read + cache_create
parts = []
if total_in > 0:
in_str = f"{_format_tokens(total_in)} in"
if cache_read > 0:
hit_pct = int(cache_read / total_in * 100)
in_str += f" ({hit_pct}% ⚡)"
parts.append(in_str)
if out > 0:
parts.append(f"{_format_tokens(out)} out")
return " · ".join(parts) if parts else ""
def _format_pi_usage_footer(data: dict, *, include_context: bool = True,
include_model: bool = True) -> str:
"""Format cumulative pi usage/context into a TUI-style footer string.
Segments are joined with two spaces. Returns empty string when no data.
Examples:
"↑12.3k ↓1.2k R4.5k CH85.1% $0.123 23.4%/200k anthropic/claude-opus-4-6"
"""
if not isinstance(data, dict):
return ""
parts: list[str] = []
# Token counts: ↑ ↓ R W
ci = int(data.get("cumulative_input", 0) or 0)
co = int(data.get("cumulative_output", 0) or 0)
cr = int(data.get("cumulative_cache_read", 0) or 0)
cw = int(data.get("cumulative_cache_write", 0) or 0)
if ci > 0:
parts.append(f"↑{_format_tokens(ci)}")
if co > 0:
parts.append(f"↓{_format_tokens(co)}")
if cr > 0:
parts.append(f"R{_format_tokens(cr)}")
if cw > 0:
parts.append(f"W{_format_tokens(cw)}")
# Cache hit rate
ch_rate = data.get("latest_cache_hit_rate")
if (cr > 0 or cw > 0) and ch_rate is not None:
try:
parts.append(f"CH{float(ch_rate):.1f}%")
except (TypeError, ValueError):
pass
# Cost
cost = float(data.get("cumulative_cost_total", 0) or 0)
is_oauth = bool(data.get("is_oauth", False))
if cost > 0 or is_oauth:
cost_str = f"${cost:.3f}"
if is_oauth:
cost_str += " (sub)"
parts.append(cost_str)
# Context window — use peak_context_tokens for per-turn utilization,
# not cumulative (which can exceed the window across turns).
if include_context:
window = int(data.get("context_window", 0) or 0)
if window > 0:
ctx_tokens = int(data.get("context_tokens", 0) or 0)
if ctx_tokens > 0:
pct = min(ctx_tokens / window * 100, 100.0)
parts.append(f"{pct:.1f}%/{_format_tokens(window)}")
else:
parts.append(f"?/{_format_tokens(window)}")
# Model string (appended as-is)
if include_model:
model = data.get("model")
if model:
parts.append(str(model))
return " ".join(parts)
def build_cardkit_final_card(content: str, is_error: bool = False,
elapsed_s: float = 0,
total_tokens: int = 0,
last_call_usage: dict | None = None,
chat_id: str | None = None,
bot_id: str | None = None,
model_name: str | None = None,
project_label: str | None = None,
todos: list[dict] | None = None,
context_alert: str | None = None,
tool_panels: list[dict] | None = None,
agents: list[dict] | None = None,
usage_footer: str | None = None,
pi_footer: str | None = None) -> dict:
# P1: parse action markers BEFORE optimize (Finding 6 ordering fix)
content, markers = parse_action_markers(content)
content = optimize_markdown_style(content)
# Single element — no chunking. openclaw-lark proves Feishu handles
# arbitrarily long markdown in one element; splitting into multiple
# elements causes rendering issues when transitioning from streaming.
elements = [
{
"tag": "markdown",
"element_id": CARDKIT_ELEMENT_ID,
"content": content or "(空回复)",
},
]
# P1: action buttons (confirm/ask/choices) — suppressed when no chat_id/bot_id
action_buttons = _build_action_buttons(markers, chat_id, bot_id)
card_ref = None
if action_buttons:
# Inject card_ref into each button for cache lookup on callback
card_ref = uuid.uuid4().hex[:12]
for btn in action_buttons:
if "value" in btn:
btn["value"]["card_ref"] = card_ref
elements.append({
"tag": "column_set",
"flex_mode": "flow",
"columns": [{
"tag": "column",
"width": "auto",
"elements": action_buttons,
}],
})
# P0: URL sidebar link buttons
url_buttons = _build_url_buttons(content)
if url_buttons:
elements.append({
"tag": "column_set",
"flex_mode": "flow",
"columns": [{
"tag": "column",
"width": "auto",
"elements": url_buttons,
}],
})
# Subagent dispatch list (rendered before tool panels). Each agent entry
# shows the subagent type + task description, struck through when completed.
if agents:
agent_md = ResponseHandle._format_agents_markdown(agents)
if agent_md:
elements.append({
"tag": "markdown",
"content": agent_md,
})
# Tool collapsible panels (from Pi runner tool history)
if tool_panels:
elements.extend(tool_panels)
# Footer: all status info in one notation-sized element
# Line 1: ✅ 9/9 tasks · model · elapsed · tokens · project
# Line 2: context alert (if any)
# Line 3: update banner (if any)
status = "❌" if is_error else "✅"
detail_parts = []
if todos:
done = sum(1 for t in todos if t.get("status") == "completed")
detail_parts.append(f"{done}/{len(todos)} tasks")
if model_name:
# Strip "claude-" prefix for brevity (e.g. "claude-opus-4-6" → "opus-4-6")
short_model = model_name.removeprefix("claude-")
detail_parts.append(short_model)
if elapsed_s > 0:
detail_parts.append(_format_elapsed(elapsed_s))
# Token usage: pi runner can pass usage_footer to override bridge's
# per-call estimate; otherwise preserve existing fallback order.
if usage_footer:
detail_parts.append(usage_footer)
elif last_call_usage:
detail_parts.append(_format_usage_footer(last_call_usage))
elif total_tokens > 0:
detail_parts.append(f"{_format_tokens(total_tokens)} tokens")
# Project workspace label (project_id when /project-bound, else the
# default workspace's directory name). Replaces the former git branch
# readout, which always reflected the global ~/.claude repo rather than
# the per-thread project binding.
if project_label:
detail_parts.append(project_label)
status_line = " · ".join([status, *detail_parts]) if detail_parts else status
footer_lines = [status_line]
if pi_footer:
footer_lines.append(pi_footer)
if context_alert:
footer_lines.append(context_alert)
from feishu_bridge.updater import get_update_banner_text
_banner = get_update_banner_text()
if _banner:
footer_lines.append(_banner)
elements.append({
"tag": "markdown",
"content": "---\n" + "\n".join(footer_lines),
"text_size": "notation",
})
summary_text = re.sub(r"[*`#>\[\]()~_]", "", content)
summary_text = re.sub(r"\s+", " ", summary_text).strip()
config = {"streaming_mode": False, "enable_forward": True}
if summary_text:
config["summary"] = {"content": summary_text[:120]}
card = {
"schema": "2.0",
"config": config,
"body": {"elements": elements},
}
# Cache the card so callbacks can rebuild with original content preserved
if card_ref:
with _card_cache_lock:
_prune_card_cache()
_card_cache[card_ref] = (time.time() + _CARD_CACHE_TTL,
copy.deepcopy(card))
return card
def add_typing_indicator(lark_client, message_id: str) -> Optional[str]:
if is_message_unavailable(message_id):
return None
try:
from lark_oapi.api.im.v1 import (
CreateMessageReactionRequest, CreateMessageReactionRequestBody,
)
from lark_oapi.api.im.v1.model.emoji import Emoji
body = CreateMessageReactionRequestBody.builder() \
.reaction_type(Emoji.builder().emoji_type("Typing").build()) \
.build()
req = CreateMessageReactionRequest.builder() \
.message_id(message_id) \
.request_body(body) \
.build()
resp = lark_client.im.v1.message_reaction.create(req)
if resp.success() and resp.data:
log.debug("Typing indicator added: msg=%s reaction=%s",
message_id, resp.data.reaction_id)
return resp.data.reaction_id
_check_terminal_code(resp, message_id)
log.warning("Typing indicator add failed: code=%s msg=%s",
resp.code, resp.msg)
except Exception:
log.warning("Typing indicator add error", exc_info=True)
return None
def remove_typing_indicator(lark_client, message_id: str,
reaction_id: Optional[str]):
if not reaction_id:
return
if is_message_unavailable(message_id):
return
try:
from lark_oapi.api.im.v1 import DeleteMessageReactionRequest
req = DeleteMessageReactionRequest.builder() \
.message_id(message_id) \
.reaction_id(reaction_id) \
.build()
resp = lark_client.im.v1.message_reaction.delete(req)
if not resp.success():
log.debug("Typing indicator remove failed: code=%s msg=%s",
resp.code, resp.msg)
except Exception: