-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathfeishu_codex_bridge.py
More file actions
2418 lines (2164 loc) · 97.1 KB
/
Copy pathfeishu_codex_bridge.py
File metadata and controls
2418 lines (2164 loc) · 97.1 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
#!/usr/bin/env python3
"""Feishu to Codex bridge.
This bridge intentionally stays small: it connects Feishu messages to Codex,
returns Codex's own final text, and manages lightweight topic boundaries for a
long-running main bot.
"""
from __future__ import annotations
import argparse
from contextlib import contextmanager
import json
import os
import re
import sqlite3
import subprocess
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from dataclasses import dataclass, replace as dataclass_replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
DEFAULT_RUNTIME_DIR = Path.home() / "Library" / "Application Support" / "FeishuCodexBridge"
DEFAULT_WORKDIR = Path.home()
VERSION = "0.5.0"
DEFAULT_CODEX_BACKEND = "exec"
DEFAULT_TOPIC_IDLE_SECONDS = 2 * 60 * 60
DEFAULT_TASK_PROGRESS_SECONDS = 2 * 60 * 60
DEFAULT_TOPIC_NOTICE_POLL_SECONDS = 60
DEFAULT_GROUP_MEMBER_CACHE_SECONDS = 10 * 60
DEFAULT_ACK_TEXT = "收到,我要开始干活了,稍等我"
CARD_ACK_TEXT = "已收到你的提交。"
CARD_PROCESSING_TEXT = "已收到你的提交,正在继续处理。"
MOBILE_REPLY_CONTEXT = (
"你正在通过手机通信软件回复用户。请使用移动端可读格式:\n"
"先给结论/摘要/判断;短段落;根据消息类型组织内容;\n"
"不要输出大段长文;如果内容较长,只回复第一层结论/摘要/判断,用户要求详细答复时再展开。"
)
CARD_REPLY_CONTEXT = (
"如果需要给用户发送飞书交互卡片,请在最终回复中放一个 ```feishu-card 代码块,内容是飞书卡片 JSON。\n"
"Bridge 会发送卡片,并从普通文本回复里移除这段 JSON。\n"
"优先生成飞书 CardKit JSON 2.0:根字段使用 schema=\"2.0\"、header、body.elements。\n"
"需要表单、多选或提交时,必须使用 body.elements 里的 form 容器;多选使用 multi_select_static,不能使用 checkbox_group。\n"
"提交按钮放在 form 内,设置 form_action_type=\"submit\" 和 name,并用 behaviors 的 callback.value 放业务字段。\n"
"Bridge 会自动补充回调标记;用户点击提交后,你会收到形如 [card-click] {...} 的后续消息。\n"
"默认情况下卡片提交会继续交给 Codex 处理并回发结果;如果只需要确认收到,"
"请在 callback.value 中设置 requires_codex=false 或 feedback_mode=\"ack\"。"
)
READING_CONFIRMATION_CONTEXT = (
"当用户通过飞书给出一篇或多篇文章、链接或资料时,即使没有额外说明,也默认是让你读一下;"
"如果用户用非固定表达要求你读、看、总结、理解、拆解、提炼重点或帮他判断价值,"
"由你判断是否适合生成飞书阅读确认卡片;Bridge 不做这类意图识别。\n"
"飞书阅读确认卡片是网页阅读确认的飞书通道版本:先理解文章,再把值得用户确认、追问或排除的内容拆成若干确认项。\n"
"在飞书通道处理读文章任务时,默认用飞书卡片返回结果;最终回复里必须包含 ```feishu-card 代码块,"
"不要只发纯文本摘要,除非内容获取失败或用户明确不要卡片。\n"
"处理链接时优先使用知识库里的内容阅读/内容获取工具;微信公众号 mp.weixin.qq.com 链接先走本地微信正文解析,"
"如果微信返回访问验证页,就明确请用户复制正文或提供已保存文件,不要尝试用 Computer Use 操作该 URL。\n"
"确认项数量不要写死;根据文章长度、信息密度和可讨论价值决定,短文可以很少,长文可以更多,但每条都要有明确增量价值。\n"
"卡片顶部先放文章标题、来源和整体逻辑概览;卡片里每个确认项应提供必要上下文,并给出“知道了”“不感兴趣”“展开讲讲”等反馈入口;也可以用表单收集文本反馈。\n"
"每个按钮或表单提交的 callback.value 应包含可回溯字段,例如 reading_session_id、item_id、choice、article_url 或 article_index;"
"Bridge 会把点击内容以 [card-click] 形式送回同一个 Codex 会话,你再继续用文本回答或二次拆解。"
)
DOC_REPLY_CONTEXT = (
"如果复杂内容更适合用飞书文档承载,请在最终回复中放 <feishu_doc title=\"标题\">正文</feishu_doc>。\n"
"Bridge 会创建飞书文档、写入正文,并把文档链接发给用户。"
)
CARD_ACTION_NAME = "codex_card"
@dataclass(frozen=True)
class BridgeConfig:
app_id: str
app_secret: str
workdir: Path = DEFAULT_WORKDIR
runtime_dir: Path = DEFAULT_RUNTIME_DIR
codex_bin: str = "codex"
node_bin: str = ""
codex_backend: str = DEFAULT_CODEX_BACKEND
codex_model: str = ""
bot_aliases: tuple[str, ...] = ("Codex", "codex", "机器人")
ignore_older_than_seconds: int = 600
reply_max_chars: int = 3500
ack_text: str = DEFAULT_ACK_TEXT
topic_idle_seconds: int = DEFAULT_TOPIC_IDLE_SECONDS
topic_notice_enabled: bool = True
topic_notice_poll_seconds: float = DEFAULT_TOPIC_NOTICE_POLL_SECONDS
task_progress_seconds: float = DEFAULT_TASK_PROGRESS_SECONDS
group_auto_reply_enabled: bool = True
group_auto_reply_max_human_members: int = 1
group_auto_reply_chat_ids: tuple[str, ...] = ()
group_member_cache_seconds: float = DEFAULT_GROUP_MEMBER_CACHE_SECONDS
codex_cards_enabled: bool = True
cardkit_enabled: bool = True
docs_enabled: bool = False
docs_folder_token: str = ""
docs_domain: str = "https://feishu.cn"
docs_auto_min_chars: int = 4500
docs_block_chars: int = 1500
@classmethod
def from_env(cls) -> "BridgeConfig":
runtime_dir = Path(os.getenv("FEISHU_CODEX_RUNTIME_DIR", str(DEFAULT_RUNTIME_DIR))).expanduser()
return cls(
app_id=os.getenv("FEISHU_APP_ID", "").strip(),
app_secret=os.getenv("FEISHU_APP_SECRET", "").strip(),
workdir=Path(os.getenv("FEISHU_CODEX_WORKDIR", str(DEFAULT_WORKDIR))).expanduser(),
runtime_dir=runtime_dir,
codex_bin=os.getenv("CODEX_BIN", "codex").strip() or "codex",
node_bin=os.getenv("NODE_BIN", "").strip(),
codex_backend=os.getenv("FEISHU_CODEX_BACKEND", DEFAULT_CODEX_BACKEND).strip().lower()
or DEFAULT_CODEX_BACKEND,
codex_model=os.getenv("FEISHU_CODEX_MODEL", "").strip(),
bot_aliases=tuple(_csv_env("FEISHU_BOT_ALIASES") or ["Codex", "codex", "机器人"]),
ignore_older_than_seconds=_int_env("FEISHU_IGNORE_OLD_MESSAGE_SECONDS", 600),
reply_max_chars=_int_env("FEISHU_REPLY_MAX_CHARS", 3500),
ack_text=os.getenv("FEISHU_ACK_TEXT", DEFAULT_ACK_TEXT).strip(),
topic_idle_seconds=_int_env("FEISHU_TOPIC_IDLE_SECONDS", DEFAULT_TOPIC_IDLE_SECONDS),
topic_notice_enabled=_bool_env("FEISHU_TOPIC_NOTICE_ENABLED", True),
topic_notice_poll_seconds=_float_env("FEISHU_TOPIC_NOTICE_POLL_SECONDS", DEFAULT_TOPIC_NOTICE_POLL_SECONDS),
task_progress_seconds=_float_env("FEISHU_TASK_PROGRESS_SECONDS", DEFAULT_TASK_PROGRESS_SECONDS),
group_auto_reply_enabled=_bool_env("FEISHU_GROUP_AUTO_REPLY_ENABLED", True),
group_auto_reply_max_human_members=_int_env("FEISHU_GROUP_AUTO_REPLY_MAX_HUMAN_MEMBERS", 1),
group_auto_reply_chat_ids=tuple(_csv_env("FEISHU_GROUP_AUTO_REPLY_CHAT_IDS")),
group_member_cache_seconds=_float_env(
"FEISHU_GROUP_MEMBER_CACHE_SECONDS",
DEFAULT_GROUP_MEMBER_CACHE_SECONDS,
),
codex_cards_enabled=_bool_env("FEISHU_CODEX_CARDS_ENABLED", True),
cardkit_enabled=_bool_env("FEISHU_CARDKIT_ENABLED", True),
docs_enabled=_bool_env("FEISHU_DOCS_ENABLED", False),
docs_folder_token=os.getenv("FEISHU_DOCS_FOLDER_TOKEN", "").strip(),
docs_domain=os.getenv("FEISHU_DOCS_DOMAIN", "https://feishu.cn").strip() or "https://feishu.cn",
docs_auto_min_chars=_int_env("FEISHU_DOCS_AUTO_MIN_CHARS", 4500),
docs_block_chars=_int_env("FEISHU_DOCS_BLOCK_CHARS", 1500),
)
@property
def db_path(self) -> Path:
return self.runtime_dir / "state.sqlite"
@dataclass(frozen=True)
class MessageEnvelope:
message_id: str
chat_id: str
chat_type: str
message_type: str
text: str
root_id: str
parent_id: str
thread_id: str
create_time_ms: int | None
addressed: bool
sender_id: str = ""
sender_name: str = ""
group_auto_reply: bool = False
@dataclass(frozen=True)
class RouteDecision:
session_key: str
should_handle: bool
reason: str
starts_new_container: bool = False
@dataclass(frozen=True)
class TopicNotice:
base_session_key: str
previous_session_key: str
active_session_key: str
idle_seconds: int
@dataclass(frozen=True)
class TopicResolution:
route: RouteDecision
notice: TopicNotice | None = None
@dataclass(frozen=True)
class PendingTopicNotice:
chat_id: str
notice: TopicNotice
@dataclass(frozen=True)
class FeishuDocRequest:
title: str
content: str
@dataclass(frozen=True)
class FeishuDocumentResult:
title: str
document_id: str
url: str
@dataclass(frozen=True)
class FeishuGroupChatResult:
name: str
chat_id: str
class StateStore:
def __init__(self, db_path: Path) -> None:
self.db_path = db_path
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self._init()
@contextmanager
def connect(self) -> Any:
con = sqlite3.connect(self.db_path)
con.row_factory = sqlite3.Row
try:
yield con
con.commit()
finally:
con.close()
def _init(self) -> None:
with self.connect() as con:
con.executescript(
"""
create table if not exists sessions (
session_key text primary key,
codex_thread_id text,
title text,
source text not null,
created_at text not null,
updated_at text not null
);
create table if not exists messages (
id integer primary key autoincrement,
session_key text not null,
feishu_message_id text not null unique,
role text not null,
text text not null,
reply_text text,
create_time_ms integer,
created_at text not null
);
create table if not exists topic_states (
base_session_key text primary key,
active_session_key text not null,
previous_session_key text,
topic_seq integer not null default 1,
last_message_ms integer,
active_task_count integer not null default 0,
last_task_completed_ms integer,
idle_notice_sent_ms integer,
idle_notice_session_key text,
topic_started_at text not null,
updated_at text not null
);
"""
)
self._ensure_column(con, "topic_states", "active_task_count", "integer not null default 0")
self._ensure_column(con, "topic_states", "last_task_completed_ms", "integer")
self._ensure_column(con, "topic_states", "idle_notice_sent_ms", "integer")
self._ensure_column(con, "topic_states", "idle_notice_session_key", "text")
def has_seen(self, message_id: str) -> bool:
if not message_id:
return False
with self.connect() as con:
row = con.execute("select 1 from messages where feishu_message_id = ?", (message_id,)).fetchone()
return row is not None
def get_thread_id(self, session_key: str) -> str | None:
with self.connect() as con:
row = con.execute(
"select codex_thread_id from sessions where session_key = ?",
(session_key,),
).fetchone()
return str(row["codex_thread_id"]) if row and row["codex_thread_id"] else None
def upsert_session(self, session_key: str, source: str, title: str = "") -> None:
now = now_iso()
with self.connect() as con:
con.execute(
"""
insert into sessions(session_key, codex_thread_id, title, source, created_at, updated_at)
values(?, null, ?, ?, ?, ?)
on conflict(session_key) do update set updated_at = excluded.updated_at
""",
(session_key, title, source, now, now),
)
def set_thread_id(self, session_key: str, thread_id: str) -> None:
with self.connect() as con:
con.execute(
"update sessions set codex_thread_id = ?, updated_at = ? where session_key = ?",
(thread_id, now_iso(), session_key),
)
def reset_session(self, session_key: str) -> None:
with self.connect() as con:
con.execute(
"update sessions set codex_thread_id = null, updated_at = ? where session_key = ?",
(now_iso(), session_key),
)
def record_user_message(self, session_key: str, envelope: MessageEnvelope) -> None:
with self.connect() as con:
con.execute(
"""
insert or ignore into messages(
session_key, feishu_message_id, role, text, create_time_ms, created_at
)
values(?, ?, 'user', ?, ?, ?)
""",
(session_key, envelope.message_id, envelope.text, envelope.create_time_ms, now_iso()),
)
def record_reply(self, message_id: str, reply_text: str) -> None:
with self.connect() as con:
con.execute(
"update messages set reply_text = ? where feishu_message_id = ?",
(reply_text, message_id),
)
def resolve_topic(self, route: RouteDecision, envelope: MessageEnvelope, idle_seconds: int) -> TopicResolution:
if route.reason != "direct-chat" or idle_seconds <= 0:
return TopicResolution(route)
now_ms = envelope.create_time_ms or int(time.time() * 1000)
now = now_iso()
with self.connect() as con:
row = con.execute(
"select * from topic_states where base_session_key = ?",
(route.session_key,),
).fetchone()
if row is None:
con.execute(
"""
insert into topic_states(
base_session_key, active_session_key, previous_session_key,
topic_seq, last_message_ms, topic_started_at, updated_at
)
values(?, ?, null, 1, ?, ?, ?)
""",
(route.session_key, route.session_key, now_ms, now, now),
)
return TopicResolution(route)
active_key = str(row["active_session_key"] or route.session_key)
last_message_ms = int(row["last_message_ms"] or 0)
active_task_count = int(row["active_task_count"] or 0)
if active_task_count > 0:
con.execute(
"""
update topic_states
set last_message_ms = ?,
idle_notice_sent_ms = null,
idle_notice_session_key = null,
updated_at = ?
where base_session_key = ?
""",
(now_ms, now, route.session_key),
)
return TopicResolution(replace_route(route, active_key, "active-task"))
con.execute(
"""
update topic_states
set last_message_ms = ?,
idle_notice_sent_ms = null,
idle_notice_session_key = null,
updated_at = ?
where base_session_key = ?
""",
(now_ms, now, route.session_key),
)
return TopicResolution(replace_route(route, active_key, route.reason))
def claim_due_topic_notices(
self,
idle_seconds: int,
now_ms: int | None = None,
limit: int = 20,
) -> list[PendingTopicNotice]:
if idle_seconds <= 0:
return []
now_ms = now_ms or int(time.time() * 1000)
cutoff_ms = now_ms - idle_seconds * 1000
now = now_iso()
notices: list[PendingTopicNotice] = []
with self.connect() as con:
rows = con.execute(
"""
select * from topic_states
where active_task_count = 0
and last_message_ms is not null
and last_message_ms <= ?
and (
idle_notice_sent_ms is null
or idle_notice_session_key is null
or idle_notice_session_key != active_session_key
)
order by last_message_ms asc
limit ?
""",
(cutoff_ms, limit),
).fetchall()
for row in rows:
base_key = str(row["base_session_key"] or "")
chat_id = p2p_chat_id_from_session_key(base_key)
if not chat_id:
continue
active_key = str(row["active_session_key"] or base_key)
topic_seq = int(row["topic_seq"] or 1) + 1
new_key = f"{base_key}:topic:{topic_seq}"
cursor = con.execute(
"""
update topic_states
set active_session_key = ?,
previous_session_key = ?,
topic_seq = ?,
idle_notice_sent_ms = ?,
idle_notice_session_key = ?,
topic_started_at = ?,
updated_at = ?
where base_session_key = ?
and active_session_key = ?
and active_task_count = 0
""",
(new_key, active_key, topic_seq, now_ms, new_key, now, now, base_key, active_key),
)
if cursor.rowcount <= 0:
continue
self._upsert_session_on_connection(con, new_key, "idle-notice-new-topic", "空闲后自动开启新话题")
notices.append(
PendingTopicNotice(
chat_id=chat_id,
notice=TopicNotice(
base_session_key=base_key,
previous_session_key=active_key,
active_session_key=new_key,
idle_seconds=idle_seconds,
),
)
)
return notices
def restore_previous_topic(
self,
base_session_key: str,
expected_active_session_key: str | None = None,
now_ms: int | None = None,
) -> str | None:
with self.connect() as con:
row = con.execute(
"select active_session_key, previous_session_key from topic_states where base_session_key = ?",
(base_session_key,),
).fetchone()
if row is None:
return None
active_key = str(row["active_session_key"] or "")
previous_key = str(row["previous_session_key"] or "")
if expected_active_session_key and active_key != expected_active_session_key:
return None
if not previous_key:
return active_key or None
con.execute(
"""
update topic_states
set active_session_key = ?,
previous_session_key = ?,
last_message_ms = ?,
idle_notice_sent_ms = null,
idle_notice_session_key = null,
updated_at = ?
where base_session_key = ?
""",
(previous_key, active_key or None, now_ms or int(time.time() * 1000), now_iso(), base_session_key),
)
return previous_key
def begin_task(self, session_key: str, started_ms: int | None = None) -> None:
now_ms = started_ms or int(time.time() * 1000)
now = now_iso()
with self.connect() as con:
con.execute(
"""
update topic_states
set active_task_count = active_task_count + 1,
last_message_ms = ?,
idle_notice_sent_ms = null,
idle_notice_session_key = null,
updated_at = ?
where active_session_key = ? or base_session_key = ?
""",
(now_ms, now, session_key, session_key),
)
def finish_task(self, session_key: str, completed_ms: int | None = None) -> None:
now_ms = completed_ms or int(time.time() * 1000)
now = now_iso()
with self.connect() as con:
con.execute(
"""
update topic_states
set active_task_count = max(active_task_count - 1, 0),
last_task_completed_ms = ?,
last_message_ms = ?,
idle_notice_sent_ms = null,
idle_notice_session_key = null,
updated_at = ?
where active_session_key = ? or base_session_key = ?
""",
(now_ms, now_ms, now, session_key, session_key),
)
def keep_current_topic(self, base_session_key: str) -> str | None:
now_ms = int(time.time() * 1000)
with self.connect() as con:
row = con.execute(
"select active_session_key from topic_states where base_session_key = ?",
(base_session_key,),
).fetchone()
if not row or not row["active_session_key"]:
return None
active_key = str(row["active_session_key"])
con.execute(
"""
update topic_states
set previous_session_key = null,
last_message_ms = ?,
idle_notice_sent_ms = null,
idle_notice_session_key = null,
updated_at = ?
where base_session_key = ?
""",
(now_ms, now_iso(), base_session_key),
)
return active_key
def _ensure_column(self, con: sqlite3.Connection, table: str, column: str, definition: str) -> None:
rows = con.execute(f"pragma table_info({table})").fetchall()
if column in {str(row["name"]) for row in rows}:
return
con.execute(f"alter table {table} add column {column} {definition}")
def _upsert_session_on_connection(self, con: sqlite3.Connection, session_key: str, source: str, title: str = "") -> None:
now = now_iso()
con.execute(
"""
insert into sessions(session_key, codex_thread_id, title, source, created_at, updated_at)
values(?, null, ?, ?, ?, ?)
on conflict(session_key) do update set updated_at = excluded.updated_at
""",
(session_key, title, source, now, now),
)
class CodexRunner:
def __init__(self, config: BridgeConfig) -> None:
self.config = config
def run(self, prompt: str, thread_id: str | None) -> tuple[str | None, str]:
with tempfile.NamedTemporaryFile("w+", encoding="utf-8", delete=False) as output_file:
output_path = Path(output_file.name)
try:
codex_command = self._codex_command()
if thread_id:
command = [
*codex_command,
"exec",
"resume",
"--json",
"--skip-git-repo-check",
"-o",
str(output_path),
thread_id,
"-",
]
else:
command = [
*codex_command,
"exec",
"--json",
"--skip-git-repo-check",
"-C",
str(self.config.workdir),
"-o",
str(output_path),
"-",
]
completed = subprocess.run(
command,
input=prompt,
text=True,
capture_output=True,
cwd=str(self.config.workdir),
check=False,
)
new_thread_id = thread_id or parse_thread_id(completed.stdout)
reply = output_path.read_text(encoding="utf-8").strip()
if not reply:
reply = parse_last_agent_message(completed.stdout) or completed.stderr.strip()
if completed.returncode != 0:
detail = reply or f"退出码 {completed.returncode}。"
reply = f"Codex 执行异常终止,退出码 {completed.returncode}。\n\n{detail}".strip()
return new_thread_id, reply.strip()
finally:
output_path.unlink(missing_ok=True)
def _codex_command(self) -> list[str]:
if self.config.node_bin:
codex_path = Path(self.config.codex_bin).expanduser()
resolved_path = codex_path.resolve() if codex_path.exists() else codex_path
if str(codex_path).endswith(".js") or str(resolved_path).endswith(".js"):
return [self.config.node_bin, str(resolved_path)]
return [self.config.codex_bin]
class CodexAppServerRunner:
def __init__(self, config: BridgeConfig) -> None:
self.config = config
self._next_id = 0
def run(self, prompt: str, thread_id: str | None) -> tuple[str | None, str]:
command = [*CodexRunner(self.config)._codex_command(), "app-server"]
process = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
cwd=str(self.config.workdir),
bufsize=1,
)
stderr_lines: list[str] = []
stderr_thread = threading.Thread(target=self._drain_stderr, args=(process, stderr_lines), daemon=True)
stderr_thread.start()
agent_parts: list[str] = []
completed_agent_messages: list[str] = []
errors: list[str] = []
active_thread_id = thread_id
try:
init_id = self._send_request(
process,
"initialize",
{
"clientInfo": {
"name": "feishu_codex_bridge",
"title": "FeishuCodexBridge",
"version": VERSION,
},
"capabilities": {"experimentalApi": True},
},
)
self._read_until_response(process, init_id, agent_parts, completed_agent_messages, errors)
self._send_notification(process, "initialized", {})
active_thread_id = self._start_or_resume_thread(
process,
active_thread_id,
agent_parts,
completed_agent_messages,
errors,
)
turn_params: dict[str, Any] = {
"threadId": active_thread_id,
"cwd": str(self.config.workdir),
"input": [{"type": "text", "text": prompt}],
}
if self.config.codex_model:
turn_params["model"] = self.config.codex_model
turn_id = self._send_request(process, "turn/start", turn_params)
self._read_until_response(process, turn_id, agent_parts, completed_agent_messages, errors)
self._read_until_turn_completed(process, active_thread_id, agent_parts, completed_agent_messages, errors)
reply = "".join(agent_parts).strip()
if not reply and completed_agent_messages:
reply = completed_agent_messages[-1].strip()
if not reply and errors:
reply = "Codex app-server 执行过程中出现错误:\n" + "\n".join(errors[-3:])
return active_thread_id, reply
finally:
self._stop_process(process)
stderr_thread.join(timeout=0.5)
def _start_or_resume_thread(
self,
process: subprocess.Popen,
thread_id: str | None,
agent_parts: list[str],
completed_agent_messages: list[str],
errors: list[str],
) -> str:
params: dict[str, Any] = {
"cwd": str(self.config.workdir),
"threadSource": "user",
}
if self.config.codex_model:
params["model"] = self.config.codex_model
if thread_id:
resume_params = {key: value for key, value in params.items() if key != "threadSource"}
resume_params["threadId"] = thread_id
request_id = self._send_request(process, "thread/resume", resume_params)
response = self._read_until_response(
process,
request_id,
agent_parts,
completed_agent_messages,
errors,
raise_for_error=False,
)
if "error" not in response:
return self._thread_id_from_response(response) or thread_id
errors.append(f"thread/resume 失败,已改为新会话:{response['error'].get('message', '')}")
request_id = self._send_request(process, "thread/start", params)
response = self._read_until_response(process, request_id, agent_parts, completed_agent_messages, errors)
new_thread_id = self._thread_id_from_response(response)
if not new_thread_id:
raise RuntimeError(f"app-server thread/start 未返回 thread id:{json.dumps(response, ensure_ascii=False)[:500]}")
return new_thread_id
def _send_request(self, process: subprocess.Popen, method: str, params: dict[str, Any]) -> int:
request_id = self._next_id
self._next_id += 1
self._send(process, {"method": method, "id": request_id, "params": params})
return request_id
def _send_notification(self, process: subprocess.Popen, method: str, params: dict[str, Any]) -> None:
self._send(process, {"method": method, "params": params})
def _send(self, process: subprocess.Popen, message: dict[str, Any]) -> None:
if not process.stdin:
raise RuntimeError("codex app-server stdin 不可用。")
process.stdin.write(json.dumps(message, ensure_ascii=False) + "\n")
process.stdin.flush()
def _read_until_response(
self,
process: subprocess.Popen,
request_id: int,
agent_parts: list[str],
completed_agent_messages: list[str],
errors: list[str],
*,
raise_for_error: bool = True,
) -> dict[str, Any]:
while True:
message = self._read_message(process)
if message.get("id") == request_id:
if "error" in message and raise_for_error:
error = message["error"]
raise RuntimeError(str(error.get("message") or error))
return message
self._handle_server_message(process, message, agent_parts, completed_agent_messages, errors)
def _read_until_turn_completed(
self,
process: subprocess.Popen,
thread_id: str,
agent_parts: list[str],
completed_agent_messages: list[str],
errors: list[str],
) -> None:
while True:
message = self._read_message(process)
method = str(message.get("method") or "")
params = message.get("params") if isinstance(message.get("params"), dict) else {}
self._handle_server_message(process, message, agent_parts, completed_agent_messages, errors)
if method == "turn/completed" and params.get("threadId") == thread_id:
turn = params.get("turn") if isinstance(params.get("turn"), dict) else {}
status = str(turn.get("status") or "")
if status and status not in {"completed", "submitted"}:
errors.append(f"turn/completed status={status}")
return
def _read_message(self, process: subprocess.Popen) -> dict[str, Any]:
if not process.stdout:
raise RuntimeError("codex app-server stdout 不可用。")
line = process.stdout.readline()
if not line:
code = process.poll()
raise RuntimeError(f"codex app-server 已退出,退出码 {code}。")
try:
message = json.loads(line)
except json.JSONDecodeError as exc:
raise RuntimeError(f"codex app-server 返回了非 JSON 行:{line[:300]}") from exc
if not isinstance(message, dict):
raise RuntimeError(f"codex app-server 返回了非对象消息:{message!r}")
return message
def _handle_server_message(
self,
process: subprocess.Popen,
message: dict[str, Any],
agent_parts: list[str],
completed_agent_messages: list[str],
errors: list[str],
) -> None:
method = str(message.get("method") or "")
params = message.get("params") if isinstance(message.get("params"), dict) else {}
if method == "item/agentMessage/delta":
agent_parts.append(str(params.get("delta") or ""))
return
if method == "item/completed":
item = params.get("item") if isinstance(params.get("item"), dict) else {}
text = extract_app_server_agent_message_text(item)
if text:
completed_agent_messages.append(text)
return
if method == "error":
error = params.get("error") if isinstance(params.get("error"), dict) else params
errors.append(str(error))
return
if "id" in message and method:
self._reply_to_server_request(process, message)
def _reply_to_server_request(self, process: subprocess.Popen, message: dict[str, Any]) -> None:
method = str(message.get("method") or "")
request_id = message.get("id")
if method in {"item/commandExecution/requestApproval", "item/fileChange/requestApproval"}:
self._send(process, {"id": request_id, "result": {"decision": "decline"}})
return
if method == "item/permissions/requestApproval":
self._send(process, {"id": request_id, "result": {"decision": "decline"}})
return
if method == "item/tool/requestUserInput":
self._send(process, {"id": request_id, "result": {"answers": {}}})
return
if method == "mcpServer/elicitation/request":
self._send(process, {"id": request_id, "result": {"action": "decline", "content": None}})
return
self._send(process, {"id": request_id, "error": {"code": -32601, "message": f"Unsupported request: {method}"}})
def _thread_id_from_response(self, response: dict[str, Any]) -> str | None:
result = response.get("result") if isinstance(response.get("result"), dict) else {}
thread = result.get("thread") if isinstance(result.get("thread"), dict) else {}
thread_id = thread.get("id")
return str(thread_id) if thread_id else None
def _drain_stderr(self, process: subprocess.Popen, stderr_lines: list[str]) -> None:
if not process.stderr:
return
for line in process.stderr:
if len(stderr_lines) < 20:
stderr_lines.append(line.rstrip())
def _stop_process(self, process: subprocess.Popen) -> None:
if process.poll() is not None:
return
process.terminate()
try:
process.wait(timeout=2)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=2)
def create_codex_runner(config: BridgeConfig) -> Any:
if config.codex_backend == "app-server":
return CodexAppServerRunner(config)
if config.codex_backend == "exec":
return CodexRunner(config)
raise ValueError("FEISHU_CODEX_BACKEND 只支持 exec 或 app-server。")
def extract_app_server_agent_message_text(item: dict[str, Any]) -> str | None:
item_type = str(item.get("type") or "")
if item_type not in {"agentMessage", "agent_message", "message"}:
return None
text = item.get("text")
if isinstance(text, str):
return text
content = item.get("content")
if isinstance(content, str):
return content
if isinstance(content, list):
parts: list[str] = []
for part in content:
if isinstance(part, dict) and isinstance(part.get("text"), str):
parts.append(part["text"])
if parts:
return "".join(parts)
return None
class FeishuOpenAPIClient:
def __init__(self, config: BridgeConfig) -> None:
self.config = config
self._tenant_access_token = ""
self._token_expires_at = 0.0
def request(
self,
method: str,
path: str,
body: dict[str, Any] | None = None,
query: dict[str, Any] | None = None,
) -> dict[str, Any]:
encoded_query = urllib.parse.urlencode({k: v for k, v in (query or {}).items() if v is not None})
url = f"https://open.feishu.cn/open-apis{path}"
if encoded_query:
url = f"{url}?{encoded_query}"
headers = {
"Authorization": f"Bearer {self.tenant_access_token()}",
"Content-Type": "application/json; charset=utf-8",
}
payload = self._request_json(method, url, body or {}, headers)
code = payload.get("code", 0)
if code not in {0, "0"}:
raise RuntimeError(f"Feishu OpenAPI failed: code={code} msg={payload.get('msg', '')}")
data = payload.get("data")
return data if isinstance(data, dict) else payload
def tenant_access_token(self) -> str:
if self._tenant_access_token and time.time() < self._token_expires_at - 60:
return self._tenant_access_token
payload = self._request_json(
"POST",
"https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
{"app_id": self.config.app_id, "app_secret": self.config.app_secret},
{"Content-Type": "application/json; charset=utf-8"},
)
code = payload.get("code", 0)
if code not in {0, "0"}:
raise RuntimeError(f"Feishu token request failed: code={code} msg={payload.get('msg', '')}")
token = str(payload.get("tenant_access_token", "") or "")
if not token:
raise RuntimeError("Feishu token request returned no tenant_access_token.")
self._tenant_access_token = token
self._token_expires_at = time.time() + int(payload.get("expire", 7200) or 7200)
return token
def create_card_id(self, card: dict[str, Any]) -> str:
data = self.request(
"POST",
"/cardkit/v1/cards",
{"type": "card_json", "data": json.dumps(card, ensure_ascii=False)},
)
card_id = str(data.get("card_id") or data.get("card", {}).get("card_id") or "")
if not card_id:
raise RuntimeError(f"cardkit create returned no card_id: {json.dumps(data, ensure_ascii=False)[:200]}")
return card_id
def chat_human_member_count(self, chat_id: str) -> int:
count = 0
page_token = ""
while True:
query: dict[str, Any] = {"member_id_type": "open_id", "page_size": 100}
if page_token:
query["page_token"] = page_token
data = self.request(
"GET",
f"/im/v1/chats/{urllib.parse.quote(chat_id, safe='')}/members",
query=query,
)
items = data.get("items") if isinstance(data.get("items"), list) else []
count += sum(1 for item in items if isinstance(item, dict) and not is_bot_member(item))
if not data.get("has_more"):
return count
page_token = str(data.get("page_token") or "")
if not page_token:
return count
def create_group_chat(self, name: str, user_open_id: str) -> FeishuGroupChatResult:
body = {
"name": name,
"description": "FeishuCodexBridge 创建的测试群",
"owner_id": user_open_id,
"user_id_list": [user_open_id],
"bot_id_list": [self.config.app_id],
"chat_mode": "group",
"chat_type": "private",
"external": False,
}
data = self.request(
"POST",
"/im/v1/chats",
body,
{"user_id_type": "open_id"},
)
chat = data.get("chat") if isinstance(data.get("chat"), dict) else data
chat_id = str(chat.get("chat_id") or data.get("chat_id") or "")
if not chat_id:
raise RuntimeError(f"chat create returned no chat_id: {json.dumps(data, ensure_ascii=False)[:200]}")
return FeishuGroupChatResult(name=str(chat.get("name") or name), chat_id=chat_id)
def _request_json(self, method: str, url: str, body: dict[str, Any], headers: dict[str, str]) -> dict[str, Any]:
method = method.upper()
data = None if method == "GET" and not body else json.dumps(body, ensure_ascii=False).encode("utf-8")
request = urllib.request.Request(url, data=data, headers=headers, method=method.upper())
try:
with urllib.request.urlopen(request, timeout=20) as response: