-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaun_cli.py
More file actions
5709 lines (5220 loc) · 236 KB
/
aun_cli.py
File metadata and controls
5709 lines (5220 loc) · 236 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
"""AUN CLI 工具 — 交互式命令行客户端"""
import asyncio
import base64
import hashlib
import json
import mimetypes
import os
import re
import signal
import sqlite3
import sys
import time
import uuid
from datetime import datetime
from importlib.metadata import PackageNotFoundError, version
from io import StringIO
from pathlib import Path
from packaging.requirements import Requirement
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
# ── 依赖自检 ──────────────────────────────────────────────────────────────
# SDK 包名:PyPI 包名是 fastaun,导入名仍为 aun_core。
# 旧版叫 aunp(已废弃),会自动卸载并替换为 fastaun。
_SDK_PKG = "fastaun"
_SDK_MIN = "0.2.14"
_LEGACY_SDK_PKGS = ["aunp"]
_REQUIRED_PACKAGES = [
{"import": "aun_core", "requirement": f"{_SDK_PKG}>={_SDK_MIN}"},
{"import": "prompt_toolkit", "requirement": "prompt-toolkit>=3.0.0"},
{"import": "rich", "requirement": "rich>=13.0.0"},
]
def _pip_install(pkgs, action="安装"):
"""用镜像/默认源重试安装 pkgs。成功返回 True。"""
import subprocess
sources = [
["-i", "https://pypi.tuna.tsinghua.edu.cn/simple", "--trusted-host", "pypi.tuna.tsinghua.edu.cn"],
[],
]
for i, src_args in enumerate(sources):
try:
subprocess.check_call(
[sys.executable, "-m", "pip", "install", "-U", "-q", *src_args, *pkgs],
stdout=sys.stdout, stderr=sys.stderr,
)
return True
except subprocess.CalledProcessError:
if i < len(sources) - 1:
print(f"[aun] 镜像源{action}失败,尝试默认源 ...")
return False
def _remove_legacy_sdk():
"""若检测到 aunp 等旧包,静默卸载(避免与 fastaun 冲突)。"""
import subprocess
for legacy in _LEGACY_SDK_PKGS:
try:
version(legacy)
except PackageNotFoundError:
continue
print(f"[aun] 检测到旧 SDK 包 {legacy},正在卸载 ...")
try:
subprocess.check_call(
[sys.executable, "-m", "pip", "uninstall", "-y", "-q", legacy],
stdout=sys.stdout, stderr=sys.stderr,
)
except subprocess.CalledProcessError:
print(f"[aun] 卸载 {legacy} 失败,请手动运行: pip uninstall {legacy}")
def _ensure_deps():
"""检查第三方依赖,缺失或版本过低时自动升级,完成后重启进程。"""
_remove_legacy_sdk()
pending = []
for item in _REQUIRED_PACKAGES:
import_name = item["import"]
requirement_text = item["requirement"]
requirement = Requirement(requirement_text)
try:
__import__(import_name)
installed = version(requirement.name)
except (ImportError, PackageNotFoundError):
pending.append(requirement_text)
continue
if installed not in requirement.specifier:
pending.append(requirement_text)
if not pending:
return
print(f"[aun] 正在安装或升级依赖: {', '.join(pending)} ...")
if not _pip_install(pending, action="安装"):
print("[aun] 依赖安装失败,请手动安装:", " ".join(pending))
raise SystemExit(1)
print("[aun] 依赖安装完成,正在重启 ...")
os.execv(sys.executable, [sys.executable] + sys.argv)
def _check_sdk_update():
"""启动时查询 PyPI 上的 fastaun 最新版本,发现新版则升级并重启。
- 每 24 小时最多查询一次(缓存在 ~/.aun/aun-cli/.sdk-check)
- 离线/超时/失败一律静默跳过
- 设 AUN_SKIP_UPDATE_CHECK=1 可完全禁用
"""
if os.environ.get("AUN_SKIP_UPDATE_CHECK", "").strip() in ("1", "true", "yes"):
return
try:
installed = version(_SDK_PKG)
except PackageNotFoundError:
return # _ensure_deps 会处理
# 节流:24h 内只查一次
base = Path(os.environ.get("AUN_CLI_DATA", "") or (Path.home() / ".aun"))
cache = base / "aun-cli" / ".sdk-check"
try:
if cache.exists() and (time.time() - cache.stat().st_mtime) < 86400:
return
except OSError:
pass
latest = _fetch_latest_pypi_version(_SDK_PKG, timeout=3.0)
try:
cache.parent.mkdir(parents=True, exist_ok=True)
cache.touch()
except OSError:
pass
if not latest:
return
try:
from packaging.version import Version
if Version(latest) <= Version(installed):
return
except Exception:
return
print(f"[aun] 发现新版 {_SDK_PKG}: {installed} → {latest},正在升级 ...")
if not _pip_install([f"{_SDK_PKG}=={latest}"], action="升级"):
print(f"[aun] 升级失败,继续使用 {installed}(可手动: pip install -U {_SDK_PKG})")
return
print("[aun] 升级完成,正在重启 ...")
os.execv(sys.executable, [sys.executable] + sys.argv)
def _fetch_latest_pypi_version(pkg: str, timeout: float = 3.0) -> str | None:
"""查询 PyPI JSON API 获取最新版本号。失败返回 None。"""
import json as _json
import urllib.request
import urllib.error
sources = [
f"https://pypi.org/pypi/{pkg}/json",
f"https://pypi.tuna.tsinghua.edu.cn/pypi/{pkg}/json",
]
for url in sources:
try:
req = urllib.request.Request(url, headers={"Accept": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as resp:
data = _json.loads(resp.read().decode("utf-8"))
v = (data.get("info") or {}).get("version")
if v:
return str(v)
except (urllib.error.URLError, TimeoutError, OSError, ValueError):
continue
return None
def _ensure_ssl_certs():
"""macOS 上无条件使用 certifi 证书,避免系统证书缺失问题。"""
if sys.platform != "darwin":
return
try:
import certifi
except ImportError:
# certifi 还没装,先用 pip 内置的证书保证 pip install 能跑
pip_certifi = os.path.join(
os.path.dirname(os.__file__),
"site-packages", "pip", "_vendor", "certifi", "cacert.pem",
)
if os.path.exists(pip_certifi):
os.environ["SSL_CERT_FILE"] = pip_certifi
return
cert_path = certifi.where()
os.environ["SSL_CERT_FILE"] = cert_path
os.environ["REQUESTS_CA_BUNDLE"] = cert_path
import ssl
_orig = ssl.create_default_context
def _patched(purpose=ssl.Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None):
if cafile is None and capath is None and cadata is None:
cafile = cert_path
return _orig(purpose, cafile=cafile, capath=capath, cadata=cadata)
ssl.create_default_context = _patched
# 先修 SSL(否则 pip install 可能也连不上),再装依赖,再用完整 certifi 重新修
_ensure_ssl_certs()
_ensure_deps()
_check_sdk_update()
_ensure_ssl_certs()
from aun_core import AUNClient
from aun_core.keystore.file import FileKeyStore
from prompt_toolkit import Application, PromptSession
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.document import Document
from prompt_toolkit.formatted_text import ANSI, HTML
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout.containers import HSplit, Window
from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
from prompt_toolkit.layout.layout import Layout
from prompt_toolkit.output import ColorDepth
from prompt_toolkit.validation import Validator, ValidationError
from prompt_toolkit.patch_stdout import patch_stdout
from prompt_toolkit.shortcuts import print_formatted_text
from prompt_toolkit.styles import Style
from rich.console import Console as RichConsole
from rich.markdown import Markdown as RichMarkdown
from rich.theme import Theme as RichTheme
# ── 配置 ──────────────────────────────────────────────────────────────────
def _gateway_cert_url(gateway_url: str, aid: str) -> str:
"""从已连接的 gateway_url 构造证书查询 URL。"""
from urllib.parse import quote, urlparse, urlunparse
parsed = urlparse(gateway_url)
scheme = "https" if parsed.scheme == "wss" else "http"
return urlunparse((scheme, parsed.netloc, f"/pki/cert/{quote(aid, safe='')}", "", "", ""))
async def _aid_exists(gateway_url: str, aid: str) -> bool:
"""向 Gateway 查询 AID 是否存在(HTTP GET /pki/cert/{aid})。"""
import aiohttp
url = _gateway_cert_url(gateway_url, aid)
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=5)) as resp:
return resp.status == 200
except Exception:
return False
# 全局变量(运行时初始化)
AUN_PATH = None # SDK 数据根目录(~/.aun),AIDs 在 {AUN_PATH}/AIDs/ 下
DATA_DIR = None # CLI 私有数据(~/.aun/aun-cli),存 history、config
DOWNLOADS_DIR = None # 文件下载目录(~/.aun/aun-cli/downloads)
HISTORY_FILE = None
_CONFIG_FILE = None
_silent = False # -s 模式:抑制所有非正文输出
_real_stderr = sys.stderr # error() 始终使用真实 stderr
_error_file = None # -s 模式下 dup'd stderr(fd 级别独立于重定向)
def _init_globals():
"""初始化全局配置变量。"""
global AUN_PATH, DATA_DIR, DOWNLOADS_DIR, HISTORY_FILE, _CONFIG_FILE
env = os.environ.get("AUN_CLI_DATA", "").strip()
base = Path(env) if env else Path.home() / ".aun"
AUN_PATH = base
DATA_DIR = base / "aun-cli"
DATA_DIR.mkdir(parents=True, exist_ok=True)
DOWNLOADS_DIR = DATA_DIR / "downloads"
DOWNLOADS_DIR.mkdir(parents=True, exist_ok=True)
HISTORY_FILE = DATA_DIR / ".history"
_CONFIG_FILE = DATA_DIR / "config.json"
def _load_config() -> dict:
"""加载 CLI 配置。"""
if _CONFIG_FILE and _CONFIG_FILE.exists():
try:
return json.loads(_CONFIG_FILE.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
pass
return {}
def _save_config(cfg: dict):
"""保存 CLI 配置。"""
if _CONFIG_FILE:
_CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
_CONFIG_FILE.write_text(json.dumps(cfg, ensure_ascii=False, indent=2), encoding="utf-8")
# ── 数据日志查看(aun --log N)────────────────────────────────────────────
_LOG_LINE_PREFIX_RE = re.compile(r'^(\[[^\]]+\] \[[^\]]+\])\s*(.*)')
_LOG_LINE_PARSE_RE = re.compile(r'^\[([^\]]+)\]\s+\[([^\]]+)\]\s*(.*)$')
def _highlight_json(compact: str) -> str:
"""渲染紧凑 JSON:key 蓝色、字符串值绿色、数字/布尔/null 黄色。"""
KEY, STR, NUM = '\x1b[94m', '\x1b[92m', '\x1b[93m'
RESET = '\x1b[0m'
out = []
i, n = 0, len(compact)
expect_key = False # 进入对象后,下一个字符串是 key
def read_string(start: int) -> int:
j = start + 1
while j < n:
c = compact[j]
if c == '\\' and j + 1 < n:
j += 2
continue
if c == '"':
return j + 1
j += 1
return n
while i < n:
c = compact[i]
if c == '{':
out.append(c)
expect_key = True
i += 1
elif c == '}':
out.append(c)
i += 1
elif c == '[':
out.append(c)
expect_key = False
i += 1
elif c == ']':
out.append(c)
i += 1
elif c == ':':
out.append(c)
expect_key = False
i += 1
elif c == ',':
out.append(c)
# 逗号后的位置:若最近的容器是对象则下一项是 key。简单启发:找到最近未闭合的 {
depth = 0
j = len(out) - 1
in_obj = False
while j >= 0:
tok = out[j]
if tok == ']':
depth += 1
elif tok == '[':
if depth == 0:
break
depth -= 1
elif tok == '}':
depth += 1
elif tok == '{':
if depth == 0:
in_obj = True
break
depth -= 1
j -= 1
expect_key = in_obj
i += 1
elif c == '"':
end = read_string(i)
token = compact[i:end]
color = KEY if expect_key else STR
out.append(f"{color}{token}{RESET}")
i = end
elif c.isspace():
out.append(c)
i += 1
else:
# number / true / false / null
j = i
while j < n and compact[j] not in ',]}:':
j += 1
token = compact[i:j]
out.append(f"{NUM}{token}{RESET}")
i = j
return ''.join(out)
def _current_log_path(now: "datetime | None" = None) -> Path:
"""返回当天数据日志文件路径。"""
current = now or datetime.now()
return DATA_DIR / "logs" / f"aun-{current.strftime('%Y%m%d')}.log"
def _render_log_line(line: str) -> str:
"""将日志行渲染为带 ANSI 颜色的终端输出。"""
line = _format_log_line(line)
m = _LOG_LINE_PARSE_RE.match(line)
if not m:
return line
ts, direction, payload = m.group(1), m.group(2), m.group(3)
stripped = payload.lstrip()
if stripped.startswith('{') or stripped.startswith('['):
try:
obj = json.loads(stripped)
compact = json.dumps(obj, ensure_ascii=False, separators=(',', ':'))
rendered_payload = _highlight_json(compact)
except Exception:
rendered_payload = _render_md(_replace_emoji(payload))
else:
rendered_payload = _render_md(_replace_emoji(payload))
return f"{C.DIM}{ts}\033[22m {C.WHITE}[{direction}]\033[39m {rendered_payload}"
def _emit_log_line(line: str):
"""TTY 下走 ANSI 渲染,非 TTY 下输出纯文本,便于管道处理。"""
rendered = _render_log_line(line)
if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
_p(rendered)
else:
print(_format_log_line(line), flush=True)
def _format_log_line(line: str) -> str:
"""保留 [时间] [方向] 前缀,将后半段的 JSON payload 压缩成单行。"""
line = line.rstrip('\n')
m = _LOG_LINE_PREFIX_RE.match(line)
if not m:
return line
prefix, rest = m.group(1), m.group(2)
try:
obj = json.loads(rest)
except Exception:
return line
return f"{prefix} {json.dumps(obj, ensure_ascii=False, separators=(',', ':'))}"
def _tail_last_lines(path: Path, count: int) -> list[str]:
"""返回日志文件的最后 count 行(不含换行符)。"""
try:
lines = path.read_text(encoding='utf-8').splitlines()
except FileNotFoundError:
return []
if count <= 0:
return []
return lines[-count:]
def _stat_identity(path: Path) -> "dict | None":
"""采集文件身份信息,用于检测轮转。"""
try:
st = path.stat()
except OSError:
return None
return {
'st_ino': getattr(st, 'st_ino', 0),
'st_mtime_ns': getattr(st, 'st_mtime_ns', int(st.st_mtime * 1_000_000_000)),
'st_size': st.st_size,
}
def _same_file_identity(left: "dict | None", right: "dict | None") -> bool:
"""判断两个 stat 结果是否来自同一文件(跨平台回退)。"""
if not left or not right:
return False
left_ino = left.get('st_ino') or 0
right_ino = right.get('st_ino') or 0
if left_ino and right_ino:
return left_ino == right_ino
return (
left.get('st_mtime_ns') == right.get('st_mtime_ns')
and left.get('st_size') == right.get('st_size')
)
def _should_reopen_for_truncation(position: int, size: int) -> bool:
"""当前读取偏移大于文件大小时,说明文件被截断/重建。"""
return position > size
def _validate_log_mode_args(argv: list, log_value: "int | None", subcmd: "str | None"):
"""`--log` 模式必须单独使用,任何混用都以退出码 2 拒绝。"""
if log_value is None:
return
if log_value <= 0 or subcmd:
raise SystemExit(2)
args = list(argv[1:])
i = 0
seen_log = False
while i < len(args):
arg = args[i]
if arg in ('--log', '-L'):
if seen_log or i + 1 >= len(args):
raise SystemExit(2)
seen_log = True
i += 2
continue
if arg.startswith('--log='):
if seen_log:
raise SystemExit(2)
seen_log = True
i += 1
continue
raise SystemExit(2)
if not seen_log:
raise SystemExit(2)
async def _follow_log_output(count: int) -> None:
"""打印当天日志最后 count 行后持续跟随,支持跨天轮转。"""
path = _current_log_path()
if not path.exists():
error('未找到当天日志文件,请先开启日志写入')
raise SystemExit(1)
for line in _tail_last_lines(path, count):
_emit_log_line(line)
current_path = path
handle = current_path.open('r', encoding='utf-8')
handle.seek(0, os.SEEK_END)
identity = _stat_identity(current_path)
try:
while True:
line = handle.readline()
if line:
_emit_log_line(line)
continue
await asyncio.sleep(0.2)
latest_path = _current_log_path()
if latest_path != current_path:
if latest_path.exists():
handle.close()
current_path = latest_path
handle = current_path.open('r', encoding='utf-8')
identity = _stat_identity(current_path)
continue
latest_identity = _stat_identity(current_path)
if latest_identity is None:
continue
if _should_reopen_for_truncation(handle.tell(), latest_identity['st_size']):
handle.close()
handle = current_path.open('r', encoding='utf-8')
identity = _stat_identity(current_path)
continue
if identity is not None and not _same_file_identity(identity, latest_identity):
handle.close()
handle = current_path.open('r', encoding='utf-8')
identity = _stat_identity(current_path)
except KeyboardInterrupt:
pass
finally:
try:
handle.close()
except Exception:
pass
# AID 合法性:域名格式,每段只允许字母、数字、连字符,至少三段(name.domain.tld)
_AID_LABEL_RE = re.compile(r'^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$')
def _is_valid_aid(name: str) -> bool:
"""检查 AID 是否为合法域名(至少三级,如 alice.agentid.pub)。"""
labels = name.split('.')
return len(labels) >= 3 and all(_AID_LABEL_RE.match(label) for label in labels)
def _validate_aid(name: str) -> bool:
"""校验 AID 格式,无效时打印错误。返回是否有效。"""
if _is_valid_aid(name):
return True
error(f"无效 AID: {name}(需要合法域名格式)")
return False
def _short_name(aid: str) -> str:
"""AID → 首段短名(如 alice.agentid.pub → alice)。"""
return aid.split(".")[0] if aid else "?"
def _strip_send_result(result):
"""精简 SDK send 返回值:剔除 E2EE 密文 payload 和重复的 event 块。"""
if not isinstance(result, dict):
return result
stripped = {}
for k, v in result.items():
if k == "event":
# event 和 message 信息重复,跳过
continue
if k == "message" and isinstance(v, dict):
# 保留 message 但剔除 payload(E2EE 密文材料)
stripped[k] = {mk: mv for mk, mv in v.items() if mk != "payload"}
else:
stripped[k] = v
return stripped
MAX_RECENT_TARGETS = 10
_last_recorded_target = None # 避免对同一 target 连续写磁盘
_targets_cache = None # 内存缓存,避免补全时每次按键读磁盘
# ── Target 模型 ───────────────────────────────────────────────────────────
# target 统一结构:{"type": "peer"|"group", "id": str, "name": str}
def _is_peer_target(target) -> bool:
return isinstance(target, dict) and target.get("type") == "peer"
def _is_group_target(target) -> bool:
return isinstance(target, dict) and target.get("type") == "group"
def _is_group_id(value: str) -> bool:
"""判断字符串是否为 group_id(g-xxx.agentid.pub 或 grp_ 开头)。"""
if not value:
return False
if value.startswith("grp_"):
return True
# g-xxx.agentid.pub 格式
if value.startswith("g-") and value.endswith(".agentid.pub"):
return True
return False
_MENTION_RE = re.compile(r'@([a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?){2,})')
def _extract_message_id(result) -> str:
"""从 SDK 返回值提取 message_id(兼容 0.2.6 / 0.2.7 嵌套格式)。"""
if not isinstance(result, dict):
return ""
mid = result.get("message_id") or ""
if not mid:
msg = result.get("message")
if isinstance(msg, dict):
mid = msg.get("message_id") or ""
return mid
def _extract_mentions(text: str) -> list[str]:
"""从文本中提取所有 @aid mention(不含行首 @)。"""
return _MENTION_RE.findall(text)
def _normalize_target(value) -> dict | None:
"""将各种输入格式规范化为 target dict。"""
if isinstance(value, dict) and value.get("type") in ("peer", "group"):
return value
if isinstance(value, str) and value:
if _is_group_id(value):
return {"type": "group", "id": value, "name": value}
if _is_valid_aid(value):
return {"type": "peer", "id": value, "name": _short_name(value)}
return None
def _normalize_recent_targets(cfg: dict) -> list[dict]:
"""从配置加载 recent_targets,并过滤掉结构无效的条目。"""
targets = cfg.get("recent_targets", [])
if not isinstance(targets, list):
return []
normalized: list[dict] = []
for t in targets:
if not isinstance(t, dict):
continue
ttype = t.get("type")
tid = str(t.get("id") or "")
name = str(t.get("name") or tid)
if ttype == "peer" and _is_valid_aid(tid):
normalized.append({"type": "peer", "id": tid, "name": name})
elif ttype == "group" and _is_group_id(tid):
normalized.append({"type": "group", "id": tid, "name": name})
return normalized
def _target_label(target) -> str:
"""返回 target 的显示标签。peer: AID, group: [群名]"""
if not isinstance(target, dict):
return str(target) if target else "未设置"
if target.get("type") == "group":
return f'[{target.get("name", target.get("id", "?"))}]'
return target.get("id", "?")
def _target_short_name(target) -> str:
"""返回 target 的短名。peer: 首段, group: 群名"""
if not isinstance(target, dict):
return _short_name(str(target)) if target else "?"
if target.get("type") == "group":
return target.get("name", target.get("id", "?"))
return _short_name(target.get("id", "?"))
def _record_target(target: dict):
"""记录成功通信过的 target(最近 10 个,最新在前)。"""
global _last_recorded_target, _targets_cache
if not target or not isinstance(target, dict):
return
tid = target.get("id")
if not tid or tid == "?" or (isinstance(_last_recorded_target, dict) and _last_recorded_target.get("id") == tid):
return
_last_recorded_target = target
cfg = _load_config()
targets = _normalize_recent_targets(cfg)
if targets and targets[0].get("id") == tid:
# 可能 name 有更新,覆盖
targets[0] = target
cfg["recent_targets"] = targets
_save_config(cfg)
_targets_cache = targets
return
targets = [t for t in targets if t.get("id") != tid]
targets.insert(0, target)
cfg["recent_targets"] = targets[:MAX_RECENT_TARGETS]
_save_config(cfg)
_targets_cache = cfg["recent_targets"]
def _get_recent_targets() -> list[dict]:
"""返回最近目标列表(优先内存缓存)。"""
global _targets_cache
if _targets_cache is None:
_targets_cache = _normalize_recent_targets(_load_config())
return _targets_cache
def _find_group_in_targets(value: str) -> dict | None:
"""在 recent_targets 中按 group_id 或群名查找 group target。"""
for t in _get_recent_targets():
if t.get("type") != "group":
continue
if t.get("id") == value or t.get("name") == value:
return t
return None
def _is_group_not_joined_error(exc: Exception | str | None) -> bool:
if not exc:
return False
text = str(exc).lower()
return "no group secret" in text or "not a member" in text
def _is_group_banned_error(exc: Exception | str | None) -> bool:
if not exc:
return False
text = str(exc).lower()
return "banned" in text
def _join_mode_from_requirements(result: dict | None, error: Exception | None = None) -> str:
reqs = result.get("join_requirements", {}) if isinstance(result, dict) else {}
mode = reqs.get("mode", "")
if mode == "closed":
return "closed"
if mode == "invite_only":
return "invite_only"
if mode in ("open", "approval"):
return mode
if _is_not_member_error(error):
return "unknown"
return mode or "unknown"
def _should_handle_join_as_target_switch(line: str, current_target=None) -> bool:
if not line.startswith("@"):
return False
# 群聊下 @aid 统一作为 @mention 消息处理,不视为切目标
if _is_group_target(current_target):
return False
parts = line[1:].split(None, 1)
if not parts:
return False
target = parts[0]
return _is_group_id(target) or _is_valid_aid(target)
def _split_target_switch_input(line: str) -> tuple[str, str]:
parts = line[1:].split(None, 1)
target = parts[0] if parts else ""
message = parts[1] if len(parts) > 1 else ""
return target, message
def _make_client(debug: bool = False) -> "AUNClient":
"""构造 AUNClient,统一 aun_path 配置。"""
return AUNClient({"aun_path": str(AUN_PATH)}, debug=debug)
def _get_keystore() -> "FileKeyStore":
"""获取与 _make_client 同路径的 FileKeyStore 实例。"""
return FileKeyStore(AUN_PATH)
# ── 样式 ──────────────────────────────────────────────────────────────────
STYLE = Style.from_dict({
"prompt": "#ffff00 bold",
"": "#ffff00",
"spinner": "#888888 nobold",
"bottom-toolbar": "bg:#1a1a2e #aaaaaa",
"validation-toolbar": "bg:#1a1a2e #ff6666",
})
_LOCAL_CMDS = [
("//debug", "", "toggle 调试模式"),
("//sdk_debug", "", "toggle SDK debug 日志"),
("//log", "", "toggle 数据日志(写入文件)"),
("//history", "N", "查看历史消息(默认20条)"),
("//plain", "", "切换 明文/E2EE"),
("//target", "aid", "设置目标(或用 @)"),
("//agentmd", "[aid]", "查看/管理 agent.md(不填 aid 为本地)"),
("//file", "cmd", "文件管理(输入 //file 查看帮助)"),
("//ping", "", "Ping 网关"),
("//processing", "", "当前处理状态"),
("//rawdata", "", "最后消息原始内容"),
("//e2ee", "", "E2EE 状态"),
("//status", "", "连接状态"),
("//local", "name", "切换本地 AID"),
("//aid", "cmd", "AID 管理"),
("//qid", "cmd", "群组管理"),
("//help", "", "帮助"),
("//quit", "", "退出"),
]
# 群命令表: (命令名, 别名列表, 描述, 需要当前群, 菜单可见)
_GROUP_COMMANDS = [
("list", [], "成员列表", True, True),
("info", [], "群组信息(含公告)", True, True),
("user", ["u"], "成员管理(+ 添加,- 踢出,ban/unban)", True, True),
("join", [], "入群管理(inv 邀请码,req 申请)", True, True),
("setup", ["set"], "群设置(name/desc/notice/mode/role)", True, True),
("group", ["g"], "群组信息与管理(info/transfer/suspend/resume/dissolve)", True, True),
("quit", [], "退出群组", True, True),
]
_OWNER_ONLY_GROUP_COMMANDS = {"user", "join", "setup", "group"}
def _filter_group_commands_for_owner(is_owner: bool | str | None, is_banned: bool = False):
if is_banned:
return [cmd for cmd in _GROUP_COMMANDS if cmd[0] in ("list", "info", "quit")]
if is_owner in (True, "owner"):
return list(_GROUP_COMMANDS)
if is_owner == "admin":
return [cmd for cmd in _GROUP_COMMANDS if cmd[0] != "group"]
return [cmd for cmd in _GROUP_COMMANDS if cmd[0] not in _OWNER_ONLY_GROUP_COMMANDS]
# 构建命令查找表: name/alias → (cmd_name, need_group)
_GROUP_CMD_LOOKUP = {}
for _cn, _aliases, _desc, _ng, _vis in _GROUP_COMMANDS:
_GROUP_CMD_LOOKUP[_cn] = (_cn, _ng)
for _a in _aliases:
_GROUP_CMD_LOOKUP[_a] = (_cn, _ng)
async def _async_input(prompt_text: str) -> str:
"""在 asyncio 环境中异步读取用户输入(使用 prompt_toolkit)。"""
session = PromptSession()
try:
result = await session.prompt_async(prompt_text)
return result
except (EOFError, KeyboardInterrupt):
raise
class AUNValidator(Validator):
"""输入验证:@ 后的目标格式检查(AID / group_id / 群名)。"""
def validate(self, document):
text = document.text.strip()
if text.startswith("@"):
parts = text[1:].split(None, 1)
name = parts[0] if parts else ""
# 空值、AID、group_id、群名都放行
if name and not _is_valid_aid(name) and not _is_group_id(name):
# 可能是群名,不强校验
pass
# / 前缀的群命令通过 repl 分发,不做强约束
class AUNCompleter(Completer):
"""补全菜单:/ 远端命令,// 本地命令,@ 目标切换(peer+group),# 群命令。"""
def __init__(self, cli_ref=None):
self.cli_ref = cli_ref # AUNCli 实例引用,用于读取 _pending_menu
@staticmethod
def _meta(node: dict) -> str:
"""有 desc 则显示,无则空。"""
return node.get('desc', '')
def get_completions(self, document, complete_event):
raw = document.text_before_cursor
text = raw.lstrip()
if not text:
return
# @ 补全:任意位置触发,统一弹出联系人/成员列表
# 行首 @ 和行中 @ 都触发;选中后补全为 //target(切换)或 @aid(mention)
at_pos = -1
if text[0] == '@':
at_pos = 0
else:
last_space = text.rfind(' ')
if last_space >= 0 and last_space + 1 < len(text) and text[last_space + 1] == '@':
at_pos = last_space + 1
if at_pos >= 0:
is_in_group = self.cli_ref and self.cli_ref.target and _is_group_target(self.cli_ref.target)
after_at = text[at_pos + 1:]
at_len = len(text) - at_pos
if ' ' in after_at:
pass # 已选目标/成员,不再补全 — fall through
elif is_in_group:
# 群聊:群成员(mention)+ 所有目标(切换,补全为 //target)
filter_text = after_at.lower()
# 群成员(缓存为空时触发后台加载)
group_id = self.cli_ref.target.get("id", "")
members = self.cli_ref._get_members(group_id)
if not members and self.cli_ref.connected:
asyncio.ensure_future(self.cli_ref._ensure_members_cache(group_id, force=True))
for m in members:
mid = m.get("aid", "")
if not mid or mid == self.cli_ref.my_aid:
continue
online = m.get("online", False)
online_tag = f" {C.BLUE}[在线]{C.RESET}" if online else ""
short = _short_name(mid)
display = f"{short}{online_tag}"
if filter_text and not (short.lower().startswith(filter_text) or mid.lower().startswith(filter_text)):
continue
yield Completion(f"@{mid} ", start_position=-at_len,
display=display, display_meta=mid)
# 切换目标列表
targets = _get_recent_targets()
grp_cache = self.cli_ref._group_cache if self.cli_ref else []
recent_ids = {t.get("id") for t in targets}
for g in (grp_cache or []):
gid = g.get("group_id", "")
if gid and gid not in recent_ids:
targets.append({"type": "group", "id": gid, "name": g.get("name", gid)})
if self.cli_ref:
try:
unread = self.cli_ref.store.unread_counts()
except Exception:
unread = {}
existing_ids = {t.get("id") for t in targets}
for cid in unread:
if cid in existing_ids:
continue
if _is_valid_aid(cid):
targets.append({"type": "peer", "id": cid, "name": _short_name(cid)})
else:
unread = {}
current_id = self.cli_ref.target.get("id") if self.cli_ref.target else None
for t in targets:
tid = t.get("id", "")
if tid == current_id:
continue
tname = t.get("name", "")
if filter_text and not (tname.lower().startswith(filter_text) or tid.lower().startswith(filter_text)):
continue
display = f"→ {tname or _short_name(tid)}"
yield Completion(f"//target {tid}", start_position=-at_len,
display=display, display_meta="切换")
return
else:
# 非群聊:所有联系人列表,选中后补全为 //target
filter_text = after_at.lower()
targets = _get_recent_targets()
group_cache = self.cli_ref._group_cache if self.cli_ref else []
recent_ids = {t.get("id") for t in targets}
for g in (group_cache or []):
gid = g.get("group_id", "")
if gid and gid not in recent_ids:
targets.append({"type": "group", "id": gid, "name": g.get("name", gid)})
if self.cli_ref:
try:
unread = self.cli_ref.store.unread_counts()
except Exception:
unread = {}
existing_ids = {t.get("id") for t in targets}
for cid in unread:
if cid in existing_ids:
continue
if _is_valid_aid(cid):
targets.append({"type": "peer", "id": cid, "name": _short_name(cid)})
else:
unread = {}
if not targets:
yield Completion("@", start_position=-at_len,
display="(无最近联系人)", display_meta="使用 //target <aid>")
return
def _sort_key(t):
tid = t.get("id", "")
cnt = unread.get(tid, 0)
if cnt > 0:
return (0, -cnt)
try:
last_ts = self.cli_ref.store.last_message_time(tid) if self.cli_ref else 0
except Exception:
last_ts = 0
return (1, -(last_ts or 0))
targets.sort(key=_sort_key)
current_id = self.cli_ref.target.get("id") if self.cli_ref and self.cli_ref.target else None
for t in targets:
tid = t.get("id", "")
tname = t.get("name", "")
is_current = " ✓" if tid == current_id else ""
cnt = unread.get(tid, 0) if tid != current_id else 0
unread_tag = f" (未读{cnt}条)" if cnt > 0 else ""
display = f"{tname}{unread_tag}{is_current}"
if filter_text and not (tname.lower().startswith(filter_text) or tid.lower().startswith(filter_text)):
continue
yield Completion(f"//target {tid} ", start_position=-at_len,
display=display, display_meta=tid)
return
if text[0] != '/':
return
# // 前缀:本地命令菜单
if text.startswith("//"):
filter_text = text[2:]
# //local 二级补全:本地 AID 列表(仅切换)