-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathafterchat.user.js
More file actions
7043 lines (6329 loc) · 280 KB
/
Copy pathafterchat.user.js
File metadata and controls
7043 lines (6329 loc) · 280 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
// ==UserScript==
// @name AfterChat — LLM Chat Exporter
// @name:zh-CN AfterChat — LLM 对话导出器
// @name:zh-TW AfterChat — LLM 對話匯出器
// @name:ja AfterChat — LLM チャット書き出しツール
// @name:ko AfterChat — LLM 채팅 내보내기
// @name:es AfterChat — Exportador de chats de LLM
// @name:fr AfterChat — Exportateur de conversations LLM
// @name:de AfterChat — LLM-Chat-Exporter
// @name:pt-BR AfterChat — Exportador de Chats de LLM
// @name:ru AfterChat — экспортёр чатов LLM
// @name:it AfterChat — Esportatore di chat LLM
// @name:vi AfterChat — Trình xuất khẩu hội thoại LLM
// @name:id AfterChat — Eksportir Chat LLM
// @name:th AfterChat — เครื่องมือส่งออกแชท LLM
// @name:tr AfterChat — LLM Sohbet Dışa Aktarıcı
// @name:ar AfterChat — مصدِّر محادثات LLM
// @namespace https://github.com/AfterThink
// @version 1.11.3
// @description Export chat history from ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat, Perplexity
// @description:zh-CN 一键导出 ChatGPT、Gemini、DeepSeek、通义千问、Kimi、豆包、Dola、Grok、Google AI Studio、Microsoft Copilot、M365 Copilot、腾讯元宝、腾讯混元、MiniMax、Mistral、Sakana AI、千问、Arena AI、腾讯 ima、Z.ai、智谱清言、DuckDuckGo AI Chat、Perplexity 的聊天记录
// @description:zh-TW 一鍵匯出 ChatGPT、Gemini、DeepSeek、通義千問、Kimi、豆包、Dola、Grok、Google AI Studio、Microsoft Copilot、M365 Copilot、騰訊元寶、騰訊混元、MiniMax、Mistral、Sakana AI、千問、Arena AI、騰訊 ima、Z.ai、智譜清言、DuckDuckGo AI Chat、Perplexity 的聊天記錄
// @description:ja ChatGPT、Gemini、DeepSeek、Qwen、Kimi、Doubao、Dola、Grok、Google AI Studio、Microsoft Copilot、M365 Copilot、Tencent Yuanbao、Tencent Hunyuan、MiniMax、Mistral、Sakana AI、Qianwen、Arena AI、Tencent IMA、Z.ai、ChatGLM、DuckDuckGo AI Chat、Perplexity などのチャット履歴をワンクリックで書き出し
// @description:ko ChatGPT、Gemini、DeepSeek、Qwen、Kimi、Doubao、Dola、Grok、Google AI Studio、Microsoft Copilot、M365 Copilot、Tencent Yuanbao、Tencent Hunyuan、MiniMax、Mistral、Sakana AI、Qianwen、Arena AI、Tencent IMA、Z.ai、ChatGLM、DuckDuckGo AI Chat、Perplexity 등 LLM 채팅 기록을 원클릭으로 내보내기
// @description:es Exporta con un clic el historial de chat de ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat y Perplexity
// @description:fr Exportez en un clic l'historique de vos conversations ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat et Perplexity
// @description:de Chatverläufe von ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat und Perplexity mit einem Klick exportieren
// @description:pt-BR Exporte com um clique o histórico de chats do ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat e Perplexity
// @description:ru Экспортируйте в один клик историю чатов ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat и Perplexity
// @description:it Esporta con un clic la cronologia delle chat di ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat e Perplexity
// @description:vi Xuất lịch sử trò chuyện từ ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat và Perplexity chỉ với một cú nhấp chuột
// @description:id Ekspor riwayat chat dari ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat, dan Perplexity dengan sekali klik
// @description:th ส่งออกประวัติแชทจาก ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat และ Perplexity ด้วยคลิกเดียว
// @description:tr ChatGPT, Gemini, DeepSeek, Qwen, Kimi, Doubao, Dola, Grok, Google AI Studio, Microsoft Copilot, M365 Copilot, Tencent Yuanbao, Tencent Hunyuan, MiniMax, Mistral, Sakana AI, Qianwen, Arena AI, Tencent IMA, Z.ai, ChatGLM, DuckDuckGo AI Chat ve Perplexity sohbet geçmişini tek tıkla dışa aktarın
// @description:ar صدّر سجل المحادثات من ChatGPT وGemini وDeepSeek وQwen وKimi وDoubao وDola وGrok وGoogle AI Studio وMicrosoft Copilot وM365 Copilot وTencent Yuanbao وTencent Hunyuan وMiniMax وMistral وSakana AI وQianwen وArena AI وTencent IMA وZ.ai وChatGLM وDuckDuckGo AI Chat وPerplexity بنقرة واحدة
// @author AfterThink Studio
// @license AGPL-3.0
// @match https://m365.cloud.microsoft/chat*
// @match https://ima.qq.com/*
// @match https://chat.z.ai/*
// @match https://chatglm.cn/*
// @match https://duck.ai/*
// @match https://chatgpt.com/*
// @match https://chat.mistral.ai/*
// @match https://chat.sakana.ai/*
// @match https://chat.deepseek.com/*
// @match https://chat.qwen.ai/*
// @match https://www.qianwen.com/*
// @match https://yuanbao.tencent.com/*
// @match https://copilot.microsoft.com/*
// @match https://aistudio.google.com/*
// @match https://aistudio.tencent.com/*
// @match https://aistudio.tencent.ai/*
// @match https://x.com/i/grok*
// @match https://gemini.google.com/*
// @match https://www.kimi.com/*
// @match https://www.doubao.com/*
// @match https://www.dola.com/*
// @match https://arena.ai/*
// @match https://www.perplexity.ai/*
// @match https://agent.minimax.io/*
// @match https://agent.minimaxi.com/*
// @icon https://avatars.githubusercontent.com/u/266756423?s=400&u=d38fce2849e95af734f50228d5195fcdf1c7719e&v=4
// @grant none
// @run-at document-idle
// ==/UserScript==
// AfterChat — LLM Chat Exporter
// Copyright (C) 2026 AfterThink Studio
// SPDX-License-Identifier: AGPL-3.0
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, version 3 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// =============================================================
// 📜 Changelog(完整版见仓库根 CHANGELOG.md)
// =============================================================
// 1.1.0 (2026-08-05)
// - 新增 arena.ai 适配器:battle / side-by-side / direct-chat / agent
// 四种模式(含投票、引用、思维链;格式规范见 docs/ChatFormat.arena.md)
// - 时间格式:全平台 UTC → 本地时间 + 时区偏移(如 16:00:53 +08:00)
// - 修复 aistudio 多账号切换(/u/<n>/ 前缀)后的导出
// 1.2.0 (2026-08-06)
// - 新增腾讯 ima 适配器:列表 get_history_list(cursor 翻页)+ 详情 get_session
// 认证走 localStorage accountInfo → x-ima-cookie;支持思考链、引用重编号
// 注意:get_session 仅返回最近 20 轮(服务端上限,无翻页)
// 1.3.0 (2026-08-06)
// - 新增 Z.ai 适配器:列表 get chats(页码翻页)+ 详情两步走
// (消息树 + messages/batch 批量正文);支持思考链、引用重编号
// 消息树含全部消息 id,长对话也能完整导出
// 1.4.0 (2026-08-06)
// - 新增智谱清言 chatglm.cn 适配器:列表 recent_list + 详情 messages
// 认证走 cookie chatglm_token;请求需 x-sign 签名(md5(ts-nonce-盐))
// 支持思考链(原样保留)、引用重编号
// 1.5.0 (2026-08-06)
// - 新增 duck.ai 适配器:无后端 API,直接读写浏览器 IndexedDB(savedAIChatData/saved-chats)
// 支持思考链、搜索引用(<citation src> → [N]);无会话 URL,仅全部导出
// 1.6.0 (2026-08-08)
// - 新增 Perplexity 适配器:列表 /rest/thread/list_recent + 详情 /rest/thread/{uuid}
// (schematized 响应 blocks 分块);每条 entry 一轮问答,正文 [N] 引用按
// web_results[N-1].url 汇总到末尾 References;详情接口游标翻页
// 1.7.0 (2026-08-12)
// - 新增腾讯混元适配器(aistudio.tencent.com + 海外站 aistudio.tencent.ai):
// 列表 /api/new-portal/chat/conversation/list(offset 翻页)
// + 详情 /api/new-portal/user/agent/conversation/v1/detail(lastId 游标翻页,整轮返回)
// URL /chat/<agentId>/<conversationId>,支持思考链、搜索引用汇总 References
// 海外站 API 域自动切到 api.hy.tencent.ai(路径与国内站一致)
// 1.7.1 (2026-08-12)
// - 修复 chatgpt.com 等站点按钮消失:应用挂载后会重建 body/html 顶层子节点,
// 把按钮容器一并清掉;新增 ensureUIAlive 自愈观察器,被移除后自动重建
// 1.8.0 (2026-08-12)
// - 新增 Mistral Le Chat 适配器:列表 tRPC chat.last(cursor 翻页)
// + 详情 Next.js RSC 流(提取 initialMessages,支持搜索引用)
// 1.9.0 (2026-08-12)
// - 新增 Sakana AI 适配器:列表 /api/v2/conversations + 详情 /api/v2/conversations/<id>
// content 里 <plan>/<think> 思考 → Thought Process,<answer> → Response
// <source-chip title url /> 搜索引用 → [标题](链接)
// 1.10.0 (2026-08-13)
// - Dola(豆包国际版 www.dola.com):与豆包 API 同构,按 hunyuan 模式并入 doubao 适配器
// 一站双域(_siteHost 区分 aid/region/导出 URL/Model 兜底),README 拆分为独立平台
// - 新增 MiniMax 适配器(agent.minimax.io + 国内版 agent.minimaxi.com,API 同构):
// 列表 /minimax-cloud/api/v1/sidebar/session/tree + 详情 /session/{id} + /session/{id}/message
// 认证 token 头+query(localStorage _token);x-signature = md5(x-timestamp + 固定盐 + body)
// (盐与算法从页面 webpack 逆向,cURL 交叉验证);yy 头实测不校验;msg_type 2 中间消息跳过
// 国内版仅前端代码确认同构,消息接口未实测(无账号)
// 1.10.1 (2026-08-14)
// - 修复 AI Studio 下载按钮空白:页面 CSP require-trusted-types-for 拦截 innerHTML 写入,
// 新增 setInnerHTML 走 trustedTypes policy,无 Trusted Types 的平台自动回退普通赋值
// 1.11.0 (2026-08-14)
// - 全部导出改为增量:记录上次导出的时间锚点(localStorage 仅存时间戳,无对话内容),
// 下次跳过 updatedAt ≤ 锚点的会话,只导新增/更新的;全部成功才推进锚点(有失败保留旧锚点)
// - Shift+左键点击按钮 = 强制全量导出(先把锚点重置到最早,走普通流程;失败时锚点保持为空下次仍全量重试)
// - ZIP 文件名改时间前缀 YYYYMMDD-HHMMSS-标题.md(本地时间),跨平台/跨批次混排按时间排序;
// ZIP 内顺序改为降序(最新在前);无时间会话回退序号前缀
// - AI Studio 列表接口补提取时间戳(item[4][4][0]);getConversationSortTime 补 kimi/ima/duck 时间字段
// 锚点缺失或时间拿不到的会话宁重复不漏,始终导出;全跳过时提示“已是最新”
// =============================================================
(function () {
'use strict';
// =============================================================
// 🎛️ CONFIG — 全局配置
// =============================================================
// LLM 注意: 这里可以调参数(延迟、限条数),但不要删除字段或改变结构。
// =============================================================
const CONFIG = {
EXPORT_PREFIX: 'chat-export',
AFTERCHAT_WORKSPACE: 'downloadchats', // AfterChat workspace basename; localStorage 可覆盖
API_PAGE_DELAY: 300, // 列表分页请求间隔(毫秒)
API_DELAY: 1200, // 单条对话导出间隔(毫秒)
DEBUG_LIMIT: 0, // 调试限条数,0 或 null 表示不限
INCREMENTAL: true, // 增量导出:跳过 updatedAt ≤ 上次锚点的会话(localStorage 记录,几十字节元数据)
};
// ---- 通用时间格式化:本地时间 + 数值时区偏移(如 2026-08-05 16:00:53 +08:00) ----
function formatLocalTime(date) {
if (!date || isNaN(date.getTime())) return 'unknown';
const p2 = (n) => String(n).padStart(2, '0');
const offMin = -date.getTimezoneOffset();
const offSign = offMin >= 0 ? '+' : '-';
const offAbs = Math.abs(offMin);
const offStr = offSign + p2(Math.floor(offAbs / 60)) + ':' + p2(offAbs % 60);
return date.getFullYear() + '-' + p2(date.getMonth() + 1) + '-' + p2(date.getDate())
+ ' ' + p2(date.getHours()) + ':' + p2(date.getMinutes()) + ':' + p2(date.getSeconds())
+ ' ' + offStr;
}
// =============================================================
// 🧩 PLATFORM_ADAPTERS — 平台适配器
// =============================================================
// LLM 注意: 新增供应商 = 在这里 push 一个适配器对象。
// 接口定义(PlatformAdapter @typedef)不要改,否则所有适配器都要修。
// 每个适配器必须实现全部 4 个方法。
// =============================================================
/**
* @typedef {Object} PlatformAdapter
* @property {string} id - 平台唯一标识
* @property {string} name - 平台显示名称
* @property {()=>boolean} detect - 检测当前是否为此平台
* @property {()=>string|null} getCurrentConversationId - 当前对话 ID(列表页返回 null)
* @property {(onProgress?:(n:number)=>void)=>Promise<Array>} getAllConversations
* @property {(id:string)=>Promise<Object>} getConversationDetails
* @property {((data:Object, title:string)=>string)=} toMarkdown - [可选] 将对话数据转为 Markdown 字符串
*/
/** @type {PlatformAdapter[]} */
const PLATFORM_ADAPTERS = [
// ═══════════════════════════════════════════════════════
// ADAPTER[m365] M365 Copilot
// ═══════════════════════════════════════════════════════
// LLM 注意: 完整实现。API 端点、请求头、数据清洗全封装在这里。
{
id: 'm365',
name: 'M365 Copilot',
detect: () => window.location.hostname === 'm365.cloud.microsoft',
getCurrentConversationId: () => {
const match = window.location.pathname.match(/^\/chat\/conversation\/([^\/?]+)/);
return match ? match[1] : null;
},
async getAllConversations(onProgress) {
let allChats = [];
let syncState = '';
const limit = CONFIG.DEBUG_LIMIT || Infinity;
while (allChats.length < limit) {
const result = await this._fetchPage(syncState, allChats);
if (!result || !result.chats) break;
if (result.chats.length <= allChats.length) break;
allChats = result.chats;
syncState = result.syncState || '';
if (onProgress) onProgress(allChats.length);
await sleep(CONFIG.API_PAGE_DELAY);
}
return allChats
.map((c) => ({
id: c.conversationId || '',
title: (c.chatName || '').trim(),
createTimeUtc: c.createTimeUtc,
updateTimeUtc: c.updateTimeUtc,
tone: c.tone,
path: c.path,
}))
.filter((c) => c.id);
},
async getConversationDetails(id) {
const url = `/chat/conversation/${id}?auth=2`;
const resp = await fetch(url, {
headers: {
'accept': 'application/json',
'x-route-id': 'chat-history',
'x-slim-rehydration': 'true',
'x-host-context': JSON.stringify({
clientPlatform: 'web',
hostName: 'officeweb',
appName: 'SSR',
appMode: 'default',
}),
},
});
if (!resp.ok) throw new Error(`API ${resp.status}: ${resp.statusText}`);
return resp.json();
},
/** 将 M365 聊天数据转为 Markdown */
toMarkdown(data, title, convId) {
const rcr = data?.store?.rawConversationResponse;
if (!rcr) throw new Error('未找到 rawConversationResponse');
const tone = rcr.tone || 'unknown';
const createTimeMs = rcr.createTimeUtc;
const timeStr = createTimeMs
? formatLocalTime(new Date(createTimeMs))
: 'unknown';
const convUrl = convId
? `https://m365.cloud.microsoft/chat/conversation/${convId}?auth=2`
: 'https://m365.cloud.microsoft';
const lines = [];
lines.push(`# ${title}`);
lines.push('');
lines.push('## Metadata');
lines.push('');
lines.push('- **Model:** `' + tone + '`');
lines.push(`- **Time:** ${timeStr}`);
lines.push(`- **URL:** ${convUrl}`);
lines.push('');
lines.push('## Conversation');
lines.push('');
const messages = rcr.messages || [];
// markdown 井号标题 → 加粗(保留突出感,不破坏标题层级)
const stripHashes = (s) => s.replace(/^#{1,6}\s+(.+)$/gm, '**$1**');
// ---- 第一遍:收集引用,按 URL 去重全局编号 ----
const urlToNum = new Map(); // URL → 编号
const refKeyToNum = new Map(); // refKey → 编号
let nextNum = 1;
// 每条最终回复消息的引用映射
const msgCitationMap = new Map(); // msgIndex → Map<refKey, globalNum>
for (let i = 0; i < messages.length; i++) {
const msg = messages[i];
if (!this._isFinalResponse(msg)) continue;
const text = this._getResponseText(msg);
if (!text) continue;
const refs = msg.references || {};
const foundKeys = [...text.matchAll(/【([^】]+)】/g)].map(m => m[1]);
const uniqueKeys = [...new Set(foundKeys)];
const localMap = new Map();
for (const key of uniqueKeys) {
if (!refKeyToNum.has(key)) {
const refInfo = refs[key];
if (refInfo && refInfo.targetLink) {
const link = refInfo.targetLink;
if (urlToNum.has(link)) {
refKeyToNum.set(key, urlToNum.get(link));
} else {
urlToNum.set(link, nextNum);
refKeyToNum.set(key, nextNum);
nextNum++;
}
} else {
refKeyToNum.set(key, null);
}
}
const gn = refKeyToNum.get(key);
if (gn !== null && gn !== undefined) {
localMap.set(key, gn);
}
}
msgCitationMap.set(i, localMap);
}
// ---- 第二遍:生成正文 ----
for (let i = 0; i < messages.length; i++) {
const msg = messages[i];
const author = msg.author;
if (author === 'user') {
const text = (msg.text || '').trim();
if (!text) continue;
lines.push('### 🧑💻 User');
lines.push('');
lines.push(stripHashes(text));
lines.push('');
} else if (author === 'bot') {
if (this._isThinkingMsg(msg)) continue;
const responseText = this._getResponseText(msg);
if (!responseText) continue;
// 收集同 turn 的思考过程
const turn = msg.turnCount;
const thoughts = [];
for (let j = i - 1; j >= 0 && messages[j].turnCount === turn; j--) {
if (this._isThinkingMsg(messages[j])) {
const t = (messages[j].text || '').trim();
if (t) thoughts.unshift(t);
}
}
// 替换引用
const citeMap = msgCitationMap.get(i) || new Map();
let cleaned = responseText.replace(/【([^】]+)】/g, (_, key) => {
const n = citeMap.get(key);
return n !== undefined && n !== null ? `[${n}]` : '';
});
lines.push('### 🤖 Assistant');
lines.push('');
if (thoughts.length > 0) {
lines.push('#### 🤔 Thought Process');
lines.push('');
for (const t of thoughts) {
lines.push(stripHashes(t));
lines.push('');
}
lines.push('#### 💡 Response');
lines.push('');
}
lines.push(stripHashes(cleaned));
lines.push('');
}
}
// ---- References ----
if (urlToNum.size > 0) {
const sorted = [...urlToNum.entries()].sort((a, b) => a[1] - b[1]);
lines.push('---');
lines.push('');
lines.push('### References');
lines.push('');
for (const [link, num] of sorted) {
lines.push(`- [${num}] ${link}`);
}
lines.push('');
}
return lines.join('\n');
},
// ---- 内部辅助方法 ----
_isThinkingMsg(msg) {
return msg.messageType === 'Progress'
|| msg.addToChainOfThought === true
|| msg.contentType === 'SearchResults';
},
_isFinalResponse(msg) {
if (msg.author !== 'bot') return false;
if (this._isThinkingMsg(msg)) return false;
return this._getResponseText(msg) !== null;
},
_getResponseText(msg) {
try {
return msg.adaptiveCards[0].body[0].text;
} catch (e) {
return null;
}
},
// M365 专用:列表分页请求(XHR,因为 fetch 在这个接口上有坑)
_fetchPage(syncState, existingChats) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/chat', true);
xhr.setRequestHeader('accept', 'application/json');
xhr.setRequestHeader('content-type', 'application/json');
xhr.setRequestHeader('x-route-id', 'chat');
xhr.setRequestHeader('x-host-context', JSON.stringify({
clientPlatform: 'web', hostName: 'officeweb', appName: 'SSR', appMode: 'default',
}));
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
try {
resolve(JSON.parse(xhr.responseText).store?.conversationPageHistoryList ?? null);
} catch (e) {
reject(new Error('解析列表API响应失败: ' + e.message));
}
} else {
reject(new Error(`列表API ${xhr.status}: ${xhr.statusText}`));
}
};
xhr.onerror = () => reject(new Error('列表API 网络错误'));
xhr.send(JSON.stringify({
action: 'GetConversationPageHistoryList',
syncState: syncState || '',
enableLastMessage: true,
conversationHistoryFilter: null,
state: {
conversationPageHistoryList: {
chats: existingChats || [],
syncState: syncState || '',
},
},
}));
});
},
},
// ═══════════════════════════════════════════════════════
// ADAPTER[ima] 腾讯 ima 知识库
// ═══════════════════════════════════════════════════════
// 列表 /cgi-bin/history/get_history_list(cursor 翻页)
// 详情 /cgi-bin/session_logic/get_session(仅返回最近 msgs_limit≤20 轮)
// 鉴权:localStorage['ima-universal-local-storage-accountInfo'] → x-ima-cookie
{
id: 'ima',
name: '腾讯 ima 知识库',
detect: () => window.location.hostname === 'ima.qq.com',
getCurrentConversationId: () => {
const m = window.location.pathname.match(/^\/chat\/([^\/?]+)/)
|| window.location.search.match(/[?&]sessionId=([^&]+)/);
return m ? m[1] : null;
},
/** 从 localStorage 读取登录态 */
_account() {
try {
return JSON.parse(localStorage.getItem('ima-universal-local-storage-accountInfo')) || {};
} catch (e) {
return {};
}
},
/** 组装 x-ima-cookie 头(token 字段与服务端校验一致) */
_imaCookie() {
const a = this._account();
return 'PLATFORM=H5; CLIENT-TYPE=256053; WEB-VERSION=999.999.999; '
+ 'IMA-GUID=' + (a.guid || '') + '; '
+ 'IMA-Q36=' + String(a.guid || '').replace(/^guid-/, '') + '; '
+ 'IMA-IUA=' + navigator.userAgent + '; '
+ 'IMA-UID=' + (a.userId || '') + '; '
+ 'IMA-TOKEN=' + (a.token || '') + '; '
+ 'IMA-REFRESH-TOKEN=' + (a.refreshToken || '') + '; '
+ 'UID-TYPE=' + (a.idType ?? '') + '; '
+ 'TOKEN-TYPE=' + (a.tokenType ?? '');
},
_headers() {
return {
'content-type': 'application/json',
'from_browser_ima': '1',
'extension_version': '999.999.999',
'x-ima-cookie': this._imaCookie(),
};
},
async getAllConversations(onProgress) {
const all = [];
let cursor = '';
const limit = CONFIG.DEBUG_LIMIT || Infinity;
while (all.length < limit) {
const r = await fetch('/cgi-bin/history/get_history_list', {
method: 'POST',
headers: this._headers(),
body: JSON.stringify({
limit: 20,
filter: 3,
cursor: cursor || '',
conditions: [{ type: 1, relate_type_condition: { not: false, relate_types: [] } }],
}),
});
if (!r.ok) throw new Error(`列表API ${r.status}: ${r.statusText}`);
const body = await r.json();
if (body.code !== 0) throw new Error(`列表API code ${body.code}: ${body.msg || ''}`);
const items = (body.histories || [])
.map((h) => h.ai_session)
.filter((s) => s && s.id)
.map((s) => ({
id: s.id,
title: (s.title || '').trim(),
update_ts: s.update_ts,
}));
if (!items.length) break;
all.push(...items);
if (onProgress) onProgress(all.length);
if (body.is_end) break;
cursor = body.next_cursor || '';
if (!cursor) break;
await sleep(CONFIG.API_PAGE_DELAY);
}
return all.slice(0, limit);
},
async getConversationDetails(id) {
const r = await fetch('/cgi-bin/session_logic/get_session', {
method: 'POST',
headers: this._headers(),
body: JSON.stringify({ session_id: id, msgs_limit: 20 }),
});
if (!r.ok) throw new Error(`详情API ${r.status}: ${r.statusText}`);
const body = await r.json();
if (body.code !== 0) throw new Error(`详情API code ${body.code}: ${body.msg || ''}`);
const session = body.session || {};
// 标题兜底:name 为空时取第一条提问(getChatTitle 读 data.session.title)
session.title = (session.name || '').trim()
|| this._firstQuestion(session)
|| '';
return body;
},
_firstQuestion(session) {
for (const m of session.msgs || []) {
const q = m?.qa_msg?.question?.text;
if (q && q.trim()) return q.trim();
}
return '';
},
/** 将 ima 聊天数据转为 Markdown */
toMarkdown(data, title, convId) {
const session = data?.session || {};
const msgs = this._collectMessages(data);
const timeStr = session.update_ts
? formatLocalTime(new Date(Number(session.update_ts)))
: 'unknown';
const convUrl = convId ? `https://ima.qq.com/chat/${convId}` : 'https://ima.qq.com';
const lines = [];
lines.push('## Metadata');
lines.push('');
lines.push('- **Model:** `' + this._modelName(msgs) + '`');
lines.push(`- **Time:** ${timeStr}`);
lines.push(`- **URL:** ${convUrl}`);
lines.push('');
lines.push('## Conversation');
lines.push('');
// markdown 井号标题 → 加粗(保留突出感,不破坏标题层级)
const stripHashes = (s) => s.replace(/^#{1,6}\s+(.+)$/gm, '**$1**');
// ---- 第一遍:收集每条消息的引用编号 [N](@ref) → 全局编号(按 URL 去重) ----
const msgCiteMap = new Map(); // msgIndex → Map<localNum, globalNum>
const urlToNum = new Map(); // url → globalNum
let nextNum = 1;
for (let i = 0; i < msgs.length; i++) {
const fa = msgs[i]?.qa_msg?.format_answer || {};
const text = this._assistantText(fa);
if (!text) continue;
const medias = this._parseMedias(fa);
const nums = [...new Set([...text.matchAll(/\[(\d+)\]\(@ref\)/g)].map(m => Number(m[1])))];
const localMap = new Map();
for (const n of nums) {
const url = medias[n - 1]?.jumpUrl || '';
if (!url) continue;
if (!urlToNum.has(url)) urlToNum.set(url, nextNum++);
localMap.set(n, urlToNum.get(url));
}
msgCiteMap.set(i, localMap);
}
// ---- 第二遍:生成正文 ----
for (let i = 0; i < msgs.length; i++) {
const q = msgs[i]?.qa_msg || {};
const question = (q.question?.text || q.question?.processed_text || '').trim();
if (!question) continue;
lines.push('### 🧑\u200d💻 User');
lines.push('');
lines.push(stripHashes(question));
lines.push('');
const fa = q.format_answer || {};
const responseText = this._assistantText(fa);
if (!responseText) continue;
const citeMap = msgCiteMap.get(i) || new Map();
const cleaned = responseText.replace(/\[(\d+)\]\(@ref\)/g, (_, n) => {
const gn = citeMap.get(Number(n));
return gn !== undefined ? `[${gn}]` : '';
});
lines.push('### 🤖 Assistant');
lines.push('');
const thinking = this._thinkingText(fa);
if (thinking) {
lines.push('#### 🤔 Thought Process');
lines.push('');
lines.push(stripHashes(thinking));
lines.push('');
lines.push('#### 💡 Response');
lines.push('');
}
lines.push(stripHashes(cleaned));
lines.push('');
}
// ---- References ----
if (urlToNum.size > 0) {
const sorted = [...urlToNum.entries()].sort((a, b) => a[1] - b[1]);
lines.push('---');
lines.push('');
lines.push('### References');
lines.push('');
for (const [url, num] of sorted) {
lines.push(`- [${num}] ${url}`);
}
lines.push('');
}
return lines.join('\n');
},
// ---- 内部辅助方法 ----
_collectMessages(data) {
const out = [];
const pushSession = (s) => { if (s && Array.isArray(s.msgs)) out.push(...s.msgs); };
pushSession(data?.session);
for (const cs of data?.child_sessions || []) pushSession(cs);
// 按消息时间正序
return out.sort((a, b) =>
(Number(a?.qa_msg?.create_ts) || 0) - (Number(b?.qa_msg?.create_ts) || 0)
);
},
_modelName(msgs) {
for (const m of msgs) {
try {
const qaStart = JSON.parse(m?.qa_msg?.format_answer?.qa_start || '{}');
if (qaStart?.title) return qaStart.title;
} catch (e) { /* 忽略 */ }
}
return 'ima';
},
_assistantText(fa) {
try {
const parsed = JSON.parse(fa?.answer || '');
if (parsed && typeof parsed.Text === 'string') return parsed.Text;
} catch (e) { /* 忽略 */ }
return '';
},
_thinkingText(fa) {
try {
const parsed = JSON.parse(fa?.thinking || '');
if (parsed && typeof parsed.Message === 'string') return parsed.Message.trim();
} catch (e) { /* 忽略 */ }
return '';
},
_parseMedias(fa) {
try {
const sm = typeof fa?.search_medias === 'string'
? JSON.parse(fa.search_medias)
: (fa?.search_medias || {});
return Array.isArray(sm?.medias) ? sm.medias : [];
} catch (e) {
return [];
}
},
},
// ═══════════════════════════════════════════════════════
// ADAPTER[zai] Z.ai (GLM)
// ═══════════════════════════════════════════════════════
// 列表 GET /api/v1/chats/?page=N&type=default(纯数组,翻到空页结束)
// 详情 GET /api/v1/chats/<id> → 消息树(含全部消息 id,无分页)
// 正文 POST /api/v1/chats/<id>/messages/batch {ids} → 消息内容 map(可大批量)
// 鉴权:localStorage['token'] → authorization: Bearer <jwt>,x-region: overseas
{
id: 'zai',
name: 'Z.ai',
detect: () => window.location.hostname === 'chat.z.ai',
getCurrentConversationId: () => {
const match = window.location.pathname.match(/^\/c\/([^\/?]+)/);
return match ? match[1] : null;
},
/** 从 localStorage 读取 JWT */
_token() {
try {
return localStorage.getItem('token') || '';
} catch (e) {
return '';
}
},
_headers() {
return {
'accept': 'application/json',
'content-type': 'application/json',
'x-region': 'overseas',
...(this._token() ? { 'authorization': 'Bearer ' + this._token() } : {}),
};
},
async getAllConversations(onProgress) {
const all = [];
let page = 1;
const limit = CONFIG.DEBUG_LIMIT || Infinity;
while (all.length < limit) {
const r = await fetch(`/api/v1/chats/?page=${page}&type=default`, { headers: this._headers() });
if (!r.ok) throw new Error(`列表API ${r.status}: ${r.statusText}`);
const items = await r.json();
if (!Array.isArray(items) || !items.length) break; // 空页 = 没有更多
const mapped = items
.map((c) => ({
id: c.id || '',
title: (c.title || '').trim(),
updated_at: c.updated_at,
created_at: c.created_at,
}))
.filter((c) => c.id);
if (!mapped.length) break;
all.push(...mapped);
if (onProgress) onProgress(all.length);
page++;
await sleep(CONFIG.API_PAGE_DELAY);
}
return all.slice(0, limit);
},
async getConversationDetails(id) {
const r = await fetch(`/api/v1/chats/${id}`, { headers: this._headers() });
if (!r.ok) throw new Error(`详情API ${r.status}: ${r.statusText}`);
const body = await r.json();
// 收集全部消息 id(活动链 + 根节点兜底,与前端一致)
const tree = body?.chat?.history?.messages || {};
const ids = this._collectMessageIds(tree, body?.chat?.history?.currentId);
const contents = await this._fetchMessageContents(id, ids);
// 消息正文挂到返回体(toMarkdown 读 data.messages)
body.messages = contents;
return body;
},
/** 消息树 → 全部 id:沿 currentId 的父链回退 + 无父节点的根 */
_collectMessageIds(tree, currentId) {
const set = new Set();
let cur = currentId;
while (cur && !set.has(cur)) {
set.add(cur);
cur = tree[cur]?.parentId || null;
}
for (const m of Object.values(tree)) {
if (m && !m.parentId) set.add(m.id);
}
return [...set];
},
/** 批量拉消息正文(每批 100 个 id,防止超长会话单次过大) */
async _fetchMessageContents(id, ids) {
const out = {};
const CHUNK = 100;
for (let i = 0; i < ids.length; i += CHUNK) {
const slice = ids.slice(i, i + CHUNK);
const r = await fetch(`/api/v1/chats/${id}/messages/batch`, {
method: 'POST',
headers: this._headers(),
body: JSON.stringify({ ids: slice }),
});
if (!r.ok) throw new Error(`消息API ${r.status}: ${r.statusText}`);
const d = await r.json();
Object.assign(out, d.data || {});
if (i + CHUNK < ids.length) await sleep(CONFIG.API_PAGE_DELAY);
}
return out;
},
/** 活动链(currentId → 根 反转 = 时间正序);异常时退回按时间排序 */
_activeChain(tree, currentId) {
const chain = [];
const seen = new Set();
let cur = currentId;
while (cur && !seen.has(cur)) {
seen.add(cur);
chain.push(cur);
cur = tree[cur]?.parentId || null;
}
chain.reverse();
if (!chain.length) {
return Object.values(tree)
.filter((m) => m && m.id)
.sort((a, b) => (a.timestamp || 0) - (b.timestamp || 0))
.map((m) => m.id);
}
return chain;
},
/** 将 Z.ai 聊天数据转为 Markdown */
toMarkdown(data, title, convId) {
const chat = data?.chat || {};
const tree = chat.history?.messages || {};
const contents = data?.messages || {};
const chain = this._activeChain(tree, chat.history?.currentId);
if (!chain.length) throw new Error('未找到消息数据');
const models = chat.models || data?.meta?.models || [];
const model = (Array.isArray(models) && models[0]) || 'glm';
const timeStr = data.updated_at
? formatLocalTime(new Date(Number(data.updated_at) * 1000))
: 'unknown';
const convUrl = convId ? `https://chat.z.ai/c/${convId}` : 'https://chat.z.ai';
const lines = [];
lines.push('## Metadata');
lines.push('');
lines.push('- **Model:** `' + model + '`');
lines.push(`- **Time:** ${timeStr}`);
lines.push(`- **URL:** ${convUrl}`);
lines.push('');
lines.push('## Conversation');
lines.push('');
// markdown 井号标题 → 加粗(保留突出感,不破坏标题层级)
const stripHashes = (s) => s.replace(/^#{1,6}\s+(.+)$/gm, '**$1**');
// ---- 第一遍:引用编号【turnNsearchM】→ 全局编号(按 URL 去重) ----
const msgCiteMap = new Map(); // msgId → Map<refId, globalNum>
const urlToNum = new Map(); // url → globalNum
let nextNum = 1;
for (const mid of chain) {
const blocks = contents[mid]?.content_blocks || [];
const text = this._textBlock(blocks);
if (!text) continue;
const refMap = this._toolRefs(blocks); // refId → {title, url}
const keys = [...new Set([...text.matchAll(/【(turn\d+search\d+)】/g)].map(x => x[1]))];
const localMap = new Map();
for (const key of keys) {
const ref = refMap.get(key);
if (!ref || !ref.url) continue;
if (!urlToNum.has(ref.url)) urlToNum.set(ref.url, nextNum++);
localMap.set(key, urlToNum.get(ref.url));
}
msgCiteMap.set(mid, localMap);
}
// ---- 第二遍:生成正文 ----
for (const mid of chain) {
const m = contents[mid] || {};
const role = m.role || tree[mid]?.role;
const blocks = m.content_blocks || [];
if (role === 'user') {
const text = (m.content || '').trim();
if (!text) continue;
lines.push('### 🧑\u200d💻 User');
lines.push('');
lines.push(stripHashes(text));
lines.push('');
} else if (role === 'assistant') {
const responseText = this._textBlock(blocks);
if (!responseText) continue;
const citeMap = msgCiteMap.get(mid) || new Map();
const cleaned = responseText.replace(/【(turn\d+search\d+)】/g, (_, key) => {
const gn = citeMap.get(key);
return gn !== undefined ? `[${gn}]` : '';
});
lines.push('### 🤖 Assistant');
lines.push('');
const thinking = this._reasoningText(blocks);
if (thinking) {
lines.push('#### 🤔 Thought Process');
lines.push('');
lines.push(stripHashes(thinking));
lines.push('');
lines.push('#### 💡 Response');
lines.push('');
}
lines.push(stripHashes(cleaned));
lines.push('');
}
// system / tool 消息不导出
}
// ---- References ----
if (urlToNum.size > 0) {
const sorted = [...urlToNum.entries()].sort((a, b) => a[1] - b[1]);
lines.push('---');
lines.push('');
lines.push('### References');
lines.push('');
for (const [url, num] of sorted) {
lines.push(`- [${num}] ${url}`);
}
lines.push('');
}
return lines.join('\n');
},
// ---- 内部辅助方法 ----
_textBlock(blocks) {
const b = (blocks || []).find((x) => x.type === 'text');
const text = (b?.content || '').trim();
return text;
},
_reasoningText(blocks) {
return (blocks || [])
.filter((x) => x.type === 'reasoning')
.map((x) => (x.content || '').trim())
.filter(Boolean)
.join('\n\n');
},
/** tool_calls results → refId → {title, url} */
_toolRefs(blocks) {
const map = new Map();
for (const b of blocks || []) {
if (b.type !== 'tool_calls') continue;
for (const res of b.results || []) {
// results[].content 里可能拼接了多个 [ref_id=...] 块,需要 matchAll
const re = /\[ref_id=(turn\d+search\d+)†([^†]*)†([^\]]+)\]/g;
let mm;
while ((mm = re.exec(res.content || '')) !== null) {
map.set(mm[1], { title: mm[2].trim(), url: mm[3].trim() });
}
}
}