-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1328 lines (1316 loc) · 52.4 KB
/
Copy pathmain.js
File metadata and controls
1328 lines (1316 loc) · 52.4 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
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
*/
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/main.ts
var main_exports = {};
__export(main_exports, {
default: () => DailyArticlePlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian4 = require("obsidian");
// src/settings.ts
var import_obsidian = require("obsidian");
var MODEL_OPTIONS = {
"deepseek-v4-flash": "DeepSeek V4 Flash (\u9ED8\u8BA4\uFF0C\u5FEB\u901F\u7ECF\u6D4E)",
"deepseek-v4-pro": "DeepSeek V4 Pro\uFF08\u6700\u5F3A\uFF0C\u66F4\u8D35\uFF09",
"deepseek-chat": "deepseek-chat\uFF08\u65E7\u7248\uFF0C2026-07-24 \u505C\u7528\uFF09",
"deepseek-reasoner": "deepseek-reasoner\uFF08\u65E7\u7248\uFF0C2026-07-24 \u505C\u7528\uFF09"
};
var DEFAULT_SETTINGS = {
deepseekApiKey: "",
model: "deepseek-v4-flash",
researchDirections: "Agent\nReinforcement Learning\n",
fetchTime: "08:00",
maxResultsPerDirection: 30,
topN: 10,
outputFolder: "DailyArticle",
outputLanguage: "zh-CN",
usePaSaCrawler: false,
crawlerDepth: 1
};
var DailyArticleSettingTab = class extends import_obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
new import_obsidian.Setting(containerEl).setName("DeepSeek API Key").setDesc("DeepSeek API \u5BC6\u94A5\uFF0C\u7528\u4E8E\u8BBA\u6587\u6253\u5206\u548C\u6458\u8981\u751F\u6210").addText((text) => {
text.inputEl.type = "password";
text.setPlaceholder("sk-...").setValue(this.plugin.settings.deepseekApiKey).onChange(async (value) => {
this.plugin.settings.deepseekApiKey = value;
await this.plugin.saveSettings();
});
});
new import_obsidian.Setting(containerEl).setName("DeepSeek \u6A21\u578B").setDesc("\u7528\u4E8E\u8BBA\u6587\u6253\u5206\u548C\u6458\u8981\u751F\u6210\u7684\u6A21\u578B\u3002V4 Flash \u6027\u4EF7\u6BD4\u6700\u9AD8").addDropdown((dropdown) => {
for (const value of Object.keys(MODEL_OPTIONS)) {
dropdown.addOption(value, MODEL_OPTIONS[value]);
}
dropdown.setValue(this.plugin.settings.model).onChange(async (value) => {
this.plugin.settings.model = value;
await this.plugin.saveSettings();
});
});
new import_obsidian.Setting(containerEl).setName("\u7814\u7A76\u65B9\u5411").setDesc("\u6BCF\u884C\u4E00\u4E2A\u7814\u7A76\u65B9\u5411\uFF0CAgent \u5C06\u81EA\u52A8\u751F\u6210\u641C\u7D22\u67E5\u8BE2\u3002\u4F8B\u5982\uFF1AAgent\u3001Reinforcement Learning\u3001GraphRAG").addTextArea(
(text) => text.setPlaceholder("Agent\nReinforcement Learning\nGraphRAG\nLLM").setValue(this.plugin.settings.researchDirections).onChange(async (value) => {
this.plugin.settings.researchDirections = value;
await this.plugin.saveSettings();
})
);
new import_obsidian.Setting(containerEl).setName("\u5B9A\u65F6\u83B7\u53D6\u65F6\u95F4").setDesc("\u6BCF\u65E5\u81EA\u52A8\u83B7\u53D6\u8BBA\u6587\u7684\u65F6\u95F4\uFF0824 \u5C0F\u65F6\u5236\uFF09").addText(
(text) => text.setPlaceholder("08:00").setValue(this.plugin.settings.fetchTime).onChange(async (value) => {
this.plugin.settings.fetchTime = value;
await this.plugin.saveSettings();
})
);
new import_obsidian.Setting(containerEl).setName("\u6BCF\u65B9\u5411\u6700\u5927\u83B7\u53D6\u6570").setDesc("\u6BCF\u4E2A\u7814\u7A76\u65B9\u5411\u6700\u591A\u83B7\u53D6\u7684\u8BBA\u6587\u6570\u91CF").addText(
(text) => text.setPlaceholder("30").setValue(String(this.plugin.settings.maxResultsPerDirection)).onChange(async (value) => {
const num = parseInt(value);
if (!isNaN(num) && num > 0) {
this.plugin.settings.maxResultsPerDirection = num;
await this.plugin.saveSettings();
}
})
);
new import_obsidian.Setting(containerEl).setName("\u7CBE\u9009\u6570\u91CF").setDesc("\u6BCF\u65E5\u7CBE\u9009\u8BBA\u6587\u6570\u91CF").addText(
(text) => text.setPlaceholder("10").setValue(String(this.plugin.settings.topN)).onChange(async (value) => {
const num = parseInt(value);
if (!isNaN(num) && num > 0) {
this.plugin.settings.topN = num;
await this.plugin.saveSettings();
}
})
);
new import_obsidian.Setting(containerEl).setName("\u8F93\u51FA\u6587\u4EF6\u5939").setDesc("\u751F\u6210\u7684 Markdown \u6587\u4EF6\u5B58\u653E\u8DEF\u5F84\uFF08\u76F8\u5BF9\u4E8E vault \u6839\u76EE\u5F55\uFF09").addText(
(text) => text.setPlaceholder("DailyArticle").setValue(this.plugin.settings.outputFolder).onChange(async (value) => {
this.plugin.settings.outputFolder = value;
await this.plugin.saveSettings();
})
);
new import_obsidian.Setting(containerEl).setName("\u8F93\u51FA\u8BED\u8A00").setDesc("\u751F\u6210\u62A5\u544A\u7684\u6458\u8981\u548C\u89E3\u6790\u8BED\u8A00").addDropdown(
(dropdown) => dropdown.addOption("zh-CN", "\u4E2D\u6587").addOption("en", "English").setValue(this.plugin.settings.outputLanguage).onChange(async (value) => {
this.plugin.settings.outputLanguage = value;
await this.plugin.saveSettings();
})
);
containerEl.createEl("h3", { text: "\u{1F4BE} \u66F4\u65B0" });
new import_obsidian.Setting(containerEl).setName("\u68C0\u67E5\u66F4\u65B0").setDesc(`\u5F53\u524D\u7248\u672C: v${this.plugin.manifest.version || "0.0.0"}`).addButton((button) => {
button.setButtonText("\u68C0\u67E5\u66F4\u65B0").onClick(async () => {
button.setDisabled(true);
button.setButtonText("\u68C0\u67E5\u4E2D...");
try {
const result = await this.plugin.checkForUpdates();
if (result === null) {
new import_obsidian.Notice("\u274C \u68C0\u67E5\u66F4\u65B0\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u8FDE\u63A5");
} else if (result.hasUpdate) {
new import_obsidian.Notice(`\u2705 \u53D1\u73B0\u65B0\u7248\u672C v${result.latestVersion}\uFF0C\u6B63\u5728\u4E0B\u8F7D...`);
const success = await this.plugin.performUpdate(result.latestTag);
if (success) {
new import_obsidian.Notice("\u2705 \u66F4\u65B0\u5B8C\u6210\uFF01\u8BF7\u91CD\u542F Obsidian \u4EE5\u5E94\u7528\u66F4\u65B0");
} else {
new import_obsidian.Notice("\u274C \u66F4\u65B0\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
}
} else {
new import_obsidian.Notice(`\u2705 \u5DF2\u662F\u6700\u65B0\u7248\u672C v${result.latestVersion}`);
}
} finally {
button.setDisabled(false);
button.setButtonText("\u68C0\u67E5\u66F4\u65B0");
}
});
});
}
};
// src/output.ts
function getDateString(date) {
const d = date || new Date();
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
return `${y}-${m}-${day}`;
}
function getTimeString() {
const now = new Date();
const hh = String(now.getHours()).padStart(2, "0");
const mm = String(now.getMinutes()).padStart(2, "0");
return `${hh}:${mm}`;
}
function getRankEmoji(rank) {
switch (rank) {
case 1:
return "\u{1F3C6}";
case 2:
return "\u{1F948}";
case 3:
return "\u{1F949}";
default:
return `#${rank}`;
}
}
function generateMarkdown(papers, summaries, totalFetched, language, date) {
const isZh = language === "zh-CN";
const dateStr = getDateString(date);
if (isZh) {
return generateChineseMarkdown(papers, summaries, totalFetched, dateStr);
}
return generateEnglishMarkdown(papers, summaries, totalFetched, dateStr);
}
function generateChineseMarkdown(papers, summaries, totalFetched, dateStr) {
var _a, _b;
const lines = [];
const timeStr = getTimeString();
lines.push(`# \u{1F4C4} Arxiv \u6BCF\u65E5\u8BBA\u6587\u7CBE\u9009 \u2014 ${dateStr}`);
lines.push("");
lines.push(`**\u5171\u68C0\u7D22 ${totalFetched} \u7BC7\u8BBA\u6587\uFF0C\u7CBE\u9009 Top ${papers.length}**`);
lines.push("");
lines.push(`> \u751F\u6210\u65F6\u95F4: ${dateStr} ${timeStr} | \u4F7F\u7528 DeepSeek AI \u8BC4\u5206\u6392\u5E8F`);
lines.push("");
lines.push("---");
lines.push("");
const summaryMap = /* @__PURE__ */ new Map();
for (const s of summaries) {
summaryMap.set(s.id, s);
}
for (let i = 0; i < papers.length; i++) {
const paper = papers[i];
const summary = summaryMap.get(paper.id);
const rank = i + 1;
const rankEmoji = getRankEmoji(rank);
const score = (_b = (_a = summary == null ? void 0 : summary.score) == null ? void 0 : _a.toFixed(1)) != null ? _b : "\u2014";
lines.push(`## ${rankEmoji} Top ${rank} \u2014 ${paper.title} (\u8BC4\u5206: ${score}/10)`);
lines.push("");
lines.push(`**\u4F5C\u8005**: ${paper.authors.join(", ")}`);
lines.push(`**\u94FE\u63A5**: [${paper.link}](${paper.link})`);
lines.push(`**\u5206\u7C7B**: ${paper.category}`);
if (summary == null ? void 0 : summary.reason) {
lines.push(`**\u8BC4\u5206\u7406\u7531**: ${summary.reason}`);
}
lines.push("");
if (summary == null ? void 0 : summary.summary) {
lines.push("### \u{1F4DD} \u6458\u8981");
lines.push("");
lines.push(summary.summary);
lines.push("");
}
if ((summary == null ? void 0 : summary.keyPoints) && summary.keyPoints.length > 0) {
lines.push("### \u{1F511} \u6838\u5FC3\u8981\u70B9");
lines.push("");
for (const point of summary.keyPoints) {
lines.push(`- ${point}`);
}
lines.push("");
}
lines.push("---");
lines.push("");
}
lines.push(
`*\u672C\u65E5\u62A5\u7531 DailyArticle \u63D2\u4EF6\u81EA\u52A8\u751F\u6210\uFF0C\u4F7F\u7528 DeepSeek API \u8FDB\u884C\u667A\u80FD\u8BC4\u5206\u4E0E\u6458\u8981*`
);
lines.push("");
return lines.join("\n");
}
function generateEnglishMarkdown(papers, summaries, totalFetched, dateStr) {
var _a, _b;
const lines = [];
const timeStr = getTimeString();
lines.push(`# \u{1F4C4} Arxiv Daily Paper Digest \u2014 ${dateStr}`);
lines.push("");
lines.push(`**${totalFetched} papers retrieved, Top ${papers.length} selected**`);
lines.push("");
lines.push(`> Generated: ${dateStr} ${timeStr} | Scored by DeepSeek AI`);
lines.push("");
lines.push("---");
lines.push("");
const summaryMap = /* @__PURE__ */ new Map();
for (const s of summaries) {
summaryMap.set(s.id, s);
}
for (let i = 0; i < papers.length; i++) {
const paper = papers[i];
const summary = summaryMap.get(paper.id);
const rank = i + 1;
const rankEmoji = getRankEmoji(rank);
const score = (_b = (_a = summary == null ? void 0 : summary.score) == null ? void 0 : _a.toFixed(1)) != null ? _b : "\u2014";
lines.push(`## ${rankEmoji} Top ${rank} \u2014 ${paper.title} (Score: ${score}/10)`);
lines.push("");
lines.push(`**Authors**: ${paper.authors.join(", ")}`);
lines.push(`**Link**: [${paper.link}](${paper.link})`);
lines.push(`**Category**: ${paper.category}`);
if (summary == null ? void 0 : summary.reason) {
lines.push(`**Scoring Reason**: ${summary.reason}`);
}
lines.push("");
if (summary == null ? void 0 : summary.summary) {
lines.push("### \u{1F4DD} Summary");
lines.push("");
lines.push(summary.summary);
lines.push("");
}
if ((summary == null ? void 0 : summary.keyPoints) && summary.keyPoints.length > 0) {
lines.push("### \u{1F511} Key Points");
lines.push("");
for (const point of summary.keyPoints) {
lines.push(`- ${point}`);
}
lines.push("");
}
lines.push("---");
lines.push("");
}
lines.push(
"*This digest was automatically generated by the DailyArticle plugin using DeepSeek API for scoring and summarization.*"
);
lines.push("");
return lines.join("\n");
}
function getOutputFilename(date) {
return `Arxiv-\u65E5\u62A5-${getDateString(date)}.md`;
}
// src/view.ts
var import_obsidian2 = require("obsidian");
var VIEW_TYPE = "daily-article-sidebar";
var TIME_PRESETS = [
{ label: "\u6700\u8FD1 24 \u5C0F\u65F6", days: 1 },
{ label: "\u6700\u8FD1 3 \u5929", days: 3 },
{ label: "\u6700\u8FD1 7 \u5929", days: 7 },
{ label: "\u6700\u8FD1 30 \u5929", days: 30 },
{ label: "\u81EA\u5B9A\u4E49\u8303\u56F4", days: -1 }
];
var DailyArticleSidebarView = class extends import_obsidian2.ItemView {
constructor(leaf, plugin) {
super(leaf);
this.plugin = plugin;
}
getViewType() {
return VIEW_TYPE;
}
getDisplayText() {
return "DailyArticle";
}
getIcon() {
return "search";
}
async onOpen() {
this.plugin.onProgress = (info) => {
this.updateProgress(info);
};
this.render();
}
onClose() {
this.plugin.onProgress = null;
return Promise.resolve();
}
getDirections() {
return this.plugin.settings.researchDirections.split("\n").map((d) => d.trim()).filter((d) => d.length > 0);
}
render() {
const { containerEl } = this;
containerEl.empty();
containerEl.addClass("daily-article-sidebar");
const header = containerEl.createDiv("daily-article-header");
header.createEl("h2", { text: "DailyArticle" });
const dateCard = containerEl.createDiv("daily-article-card");
dateCard.createEl("h3", { text: "\u{1F4C5} \u641C\u7D22\u65F6\u95F4\u8303\u56F4" });
new import_obsidian2.Setting(dateCard).setName("\u9009\u62E9\u8303\u56F4").addDropdown((dropdown) => {
for (const preset of TIME_PRESETS) {
dropdown.addOption(String(preset.days), preset.label);
}
dropdown.setValue("1");
this.timePresetDropdown = dropdown.selectEl;
dropdown.onChange(() => this.onTimePresetChange());
});
this.dateRangeContainer = dateCard.createDiv("daily-article-date-range");
this.dateRangeContainer.style.display = "none";
new import_obsidian2.Setting(this.dateRangeContainer).setName("\u8D77\u59CB\u65E5\u671F").addText((text) => {
text.inputEl.type = "date";
text.setValue(this.getDefaultDateStr(-7));
this.dateStartInput = text.inputEl;
});
new import_obsidian2.Setting(this.dateRangeContainer).setName("\u7ED3\u675F\u65E5\u671F").addText((text) => {
text.inputEl.type = "date";
text.setValue(this.getDefaultDateStr(0));
this.dateEndInput = text.inputEl;
});
const dirCard = containerEl.createDiv("daily-article-card");
dirCard.createEl("h3", { text: "\u{1F50D} \u7814\u7A76\u65B9\u5411" });
const directions = this.getDirections();
if (directions.length > 0) {
new import_obsidian2.Setting(dirCard).setName("\u8FC7\u6EE4\u65B9\u5411").addDropdown((dropdown) => {
dropdown.addOption("all", "\u6240\u6709\u65B9\u5411");
for (const dir of directions) {
dropdown.addOption(dir, dir);
}
dropdown.setValue("all");
this.directionDropdown = dropdown.selectEl;
});
}
const settingsCard = containerEl.createDiv("daily-article-card");
settingsCard.createEl("h3", { text: "\u2699\uFE0F \u641C\u7D22\u53C2\u6570" });
new import_obsidian2.Setting(settingsCard).setName("DeepSeek \u6A21\u578B").addDropdown((dropdown) => {
for (const [value, label] of Object.entries(MODEL_OPTIONS)) {
dropdown.addOption(value, label);
}
dropdown.setValue(this.plugin.settings.model);
dropdown.onChange(async (value) => {
this.plugin.settings.model = value;
await this.plugin.saveSettings();
});
});
const rowDiv = settingsCard.createDiv("daily-article-setting-row");
new import_obsidian2.Setting(rowDiv).setName("\u6BCF\u65B9\u5411\u83B7\u53D6\u6570").addText((text) => {
text.setPlaceholder("30").setValue(String(this.plugin.settings.maxResultsPerDirection)).onChange(async (value) => {
const num = parseInt(value);
if (!isNaN(num) && num > 0) {
this.plugin.settings.maxResultsPerDirection = num;
await this.plugin.saveSettings();
}
});
});
new import_obsidian2.Setting(rowDiv).setName("\u7CBE\u9009\u6570\u91CF").addText((text) => {
text.setPlaceholder("10").setValue(String(this.plugin.settings.topN)).onChange(async (value) => {
const num = parseInt(value);
if (!isNaN(num) && num > 0) {
this.plugin.settings.topN = num;
await this.plugin.saveSettings();
}
});
});
new import_obsidian2.Setting(settingsCard).setName("\u8F93\u51FA\u8BED\u8A00").addDropdown((dropdown) => {
dropdown.addOption("zh-CN", "\u4E2D\u6587").addOption("en", "English").setValue(this.plugin.settings.outputLanguage).onChange(async (value) => {
this.plugin.settings.outputLanguage = value;
await this.plugin.saveSettings();
});
});
new import_obsidian2.Setting(settingsCard).setName("\u{1F504} \u6269\u5C55\u5F15\u7528\u94FE").setDesc("PaSa Agent \u6A21\u5F0F\uFF1A\u81EA\u52A8\u4ECE\u5DF2\u627E\u5230\u7684\u8BBA\u6587\u4E2D\u6269\u5C55\u641C\u7D22\u66F4\u591A\u76F8\u5173\u8BBA\u6587\uFF08\u589E\u52A0 API \u8C03\u7528\uFF09").addToggle((toggle) => {
toggle.setValue(this.plugin.settings.usePaSaCrawler);
toggle.onChange(async (value) => {
this.plugin.settings.usePaSaCrawler = value;
await this.plugin.saveSettings();
});
});
const actionCard = containerEl.createDiv("daily-article-card");
actionCard.createEl("h3", { text: "\u25B6\uFE0F \u64CD\u4F5C" });
const btnSetting = new import_obsidian2.Setting(actionCard).addButton((button) => {
button.setButtonText("\u641C\u7D22\u5E76\u751F\u6210\u62A5\u544A").setCta().onClick(() => this.handleSearch());
});
this.searchBtn = btnSetting.controlEl.querySelector("button");
const progressContainer = actionCard.createDiv("daily-article-progress");
this.progressBarEl = progressContainer.createDiv("daily-article-progress-bar");
this.progressFillEl = progressContainer.createDiv("daily-article-progress-fill");
this.progressLabelEl = progressContainer.createSpan("daily-article-progress-label");
progressContainer.style.display = "none";
this.statusEl = actionCard.createDiv("daily-article-status");
this.statusEl.setText("\u5C31\u7EEA");
}
/** Get date string for an offset from today (0 = today, -7 = 7 days ago) */
getDefaultDateStr(daysOffset) {
const d = new Date();
d.setDate(d.getDate() + daysOffset);
return d.toISOString().slice(0, 10);
}
/** Show/hide custom date inputs based on preset selection */
onTimePresetChange() {
var _a;
const val = (_a = this.timePresetDropdown) == null ? void 0 : _a.value;
const isCustom = val === "-1";
if (this.dateRangeContainer) {
this.dateRangeContainer.style.display = isCustom ? "block" : "none";
}
}
/** Compute start and end dates based on the selected preset */
getDateRange() {
var _a, _b, _c;
const presetDays = parseInt(((_a = this.timePresetDropdown) == null ? void 0 : _a.value) || "1");
if (presetDays === -1) {
const startVal = (_b = this.dateStartInput) == null ? void 0 : _b.value;
const endVal = (_c = this.dateEndInput) == null ? void 0 : _c.value;
if (!startVal || !endVal) {
new import_obsidian2.Notice("\u274C \u8BF7\u9009\u62E9\u8D77\u6B62\u65E5\u671F");
return {};
}
const [sy, sm, sd] = startVal.split("-").map(Number);
const [ey, em, ed] = endVal.split("-").map(Number);
const start2 = new Date(sy, sm - 1, sd, 0, 0);
const end2 = new Date(ey, em - 1, ed + 1, 0, 0);
return { start: start2, end: end2 };
}
const end = new Date();
const start = new Date(end.getTime() - presetDays * 24 * 60 * 60 * 1e3);
return { start, end };
}
setLoading(loading) {
if (!this.searchBtn)
return;
if (loading) {
this.searchBtn.disabled = true;
this.searchBtn.innerHTML = '<span class="daily-article-spinner"></span> \u5904\u7406\u4E2D...';
} else {
this.searchBtn.disabled = false;
this.searchBtn.textContent = "\u641C\u7D22\u5E76\u751F\u6210\u62A5\u544A";
}
}
updateProgress(info) {
if (!this.progressBarEl || !this.progressFillEl || !this.progressLabelEl)
return;
const { step, message, percent } = info;
if (step !== "done" && step !== "error") {
this.progressBarEl.style.display = "flex";
}
this.progressLabelEl.textContent = message;
this.progressFillEl.style.width = `${Math.min(percent, 100)}%`;
if (percent < 10) {
this.progressFillEl.style.background = "var(--interactive-accent)";
} else if (percent >= 90) {
this.progressFillEl.style.background = "var(--color-green)";
} else {
this.progressFillEl.style.background = "var(--interactive-accent)";
}
if (this.statusEl) {
this.statusEl.setText(message);
}
}
async handleSearch() {
var _a;
const selectedDirection = (_a = this.directionDropdown) == null ? void 0 : _a.value;
const { start, end } = this.getDateRange();
if (!start || !end) {
return;
}
let directions;
if (selectedDirection && selectedDirection !== "all") {
directions = [selectedDirection];
}
if (this.progressBarEl) {
this.progressBarEl.style.display = "flex";
}
this.updateProgress({ step: "query", message: "\u6B63\u5728\u641C\u7D22\u8BBA\u6587...", percent: 0 });
this.setLoading(true);
const success = await this.plugin.fetchAndProcess(start, end, directions);
this.setLoading(false);
this.updateProgress({
step: "done",
message: success ? "\u2705 \u5B8C\u6210" : "\u274C \u64CD\u4F5C\u5931\u8D25",
percent: success ? 100 : 0
});
if (success && this.progressBarEl) {
setTimeout(() => {
this.progressBarEl.style.display = "none";
}, 3e3);
}
}
};
// src/arxiv.ts
var import_obsidian3 = require("obsidian");
function pad(n) {
return n.toString().padStart(2, "0");
}
function formatDate(date) {
const y = date.getFullYear();
const m = pad(date.getMonth() + 1);
const d = pad(date.getDate());
const hh = pad(date.getHours());
const mm = pad(date.getMinutes());
return `${y}${m}${d}${hh}${mm}`;
}
function decodeXmlEntities(str) {
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/'/g, "'");
}
function parseAtomXml(xml) {
var _a, _b, _c, _d, _e, _f;
const parser = new DOMParser();
const doc = parser.parseFromString(xml, "text/xml");
const entries = doc.querySelectorAll("entry");
const papers = [];
const totalResultsEl = doc.querySelector("totalResults") || doc.querySelector("opensearch\\:totalResults");
const totalResults = totalResultsEl ? parseInt(totalResultsEl.textContent || "0") : entries.length;
for (const entry of Array.from(entries)) {
const idEl = entry.querySelector("id");
const titleEl = entry.querySelector("title");
const summaryEl = entry.querySelector("summary");
const publishedEl = entry.querySelector("published");
const authorEls = entry.querySelectorAll("author name");
const authors = Array.from(authorEls).map(
(el) => el.textContent || ""
);
const linkEl = entry.querySelector("link[title='pdf']");
const link = linkEl ? linkEl.getAttribute("href") || "" : ((_a = idEl == null ? void 0 : idEl.textContent) == null ? void 0 : _a.replace("http:", "https:")) || "";
let catEl = entry.querySelector("primary_category") || entry.querySelector("arxiv\\:primary_category");
const category = catEl ? catEl.getAttribute("term") || "" : ((_b = entry.querySelector("category")) == null ? void 0 : _b.getAttribute("term")) || "";
const id = ((_c = idEl == null ? void 0 : idEl.textContent) == null ? void 0 : _c.trim()) || "";
const title = decodeXmlEntities(
(((_d = titleEl == null ? void 0 : titleEl.textContent) == null ? void 0 : _d.trim()) || "").replace(/\s+/g, " ")
);
const summary = decodeXmlEntities(
(((_e = summaryEl == null ? void 0 : summaryEl.textContent) == null ? void 0 : _e.trim()) || "").replace(/\s+/g, " ")
);
const published = ((_f = publishedEl == null ? void 0 : publishedEl.textContent) == null ? void 0 : _f.trim()) || "";
papers.push({ id, title, summary, authors, published, link, category });
}
return { entries: papers, totalResults };
}
async function queryArxiv(query, maxResults) {
const params = new URLSearchParams({
search_query: query,
start: "0",
max_results: String(maxResults),
sortBy: "submittedDate",
sortOrder: "descending"
});
const url = `https://export.arxiv.org/api/query?${params.toString()}`;
const response = await (0, import_obsidian3.requestUrl)({ url });
if (response.status >= 400) {
throw new Error(`Arxiv API error: ${response.status}`);
}
const xml = response.text;
return parseAtomXml(xml);
}
async function fetchPapersByQuery(queryString, maxResults, startDate, endDate) {
let dateRange;
if (startDate && endDate) {
dateRange = `submittedDate:[${formatDate(startDate)} TO ${formatDate(endDate)}]`;
} else {
const now = new Date();
const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1e3);
dateRange = `submittedDate:[${formatDate(yesterday)} TO ${formatDate(now)}]`;
}
const query = `${queryString} AND ${dateRange}`;
const result = await queryArxiv(query, maxResults);
return result.entries;
}
async function fetchPapersByQueries(queries, maxResultsPerQuery, startDate, endDate) {
var _a;
const seen = /* @__PURE__ */ new Set();
const allPapers = [];
for (const query of queries) {
try {
const papers = await fetchPapersByQuery(query, maxResultsPerQuery, startDate, endDate);
for (const paper of papers) {
if (!seen.has(paper.id)) {
seen.add(paper.id);
allPapers.push(paper);
}
}
} catch (e) {
console.error(`Failed to fetch query "${query.slice(0, 80)}":`, e);
new import_obsidian3.Notice(`\u26A0\uFE0F arXiv \u8BF7\u6C42\u9519\u8BEF: ${(_a = e.message) == null ? void 0 : _a.slice(0, 100)}`, 6e3);
}
}
return allPapers;
}
// src/agent.ts
var scoringCache = /* @__PURE__ */ new Map();
function getCachedScore(id) {
return scoringCache.get(id);
}
function setCachedScore(id, score, reason) {
scoringCache.set(id, { score, reason });
}
var DEEPSEEK_BASE_URL = "https://api.deepseek.com";
async function callDeepSeekWithTools(apiKey, model, systemPrompt, userMessage, tools) {
var _a, _b, _c, _d, _e, _f;
const body = {
model,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userMessage }
],
tools,
tool_choice: "required",
temperature: 0.3,
max_tokens: 4096
};
const response = await fetch(`${DEEPSEEK_BASE_URL}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`
},
body: JSON.stringify(body)
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(
`DeepSeek API error: ${response.status} ${response.statusText}
${errorBody}`
);
}
const data = await response.json();
const choice = (_a = data.choices) == null ? void 0 : _a[0];
if ((_e = (_d = (_c = (_b = choice == null ? void 0 : choice.message) == null ? void 0 : _b.tool_calls) == null ? void 0 : _c[0]) == null ? void 0 : _d.function) == null ? void 0 : _e.arguments) {
return choice.message.tool_calls[0].function.arguments;
}
if ((_f = choice == null ? void 0 : choice.message) == null ? void 0 : _f.content) {
try {
JSON.parse(choice.message.content);
} catch (e) {
throw new Error("DeepSeek returned non-JSON content, falling back to json_object mode");
}
return choice.message.content;
}
throw new Error("Unexpected DeepSeek response: no tool_calls or content");
}
async function callDeepSeekJson(apiKey, model, systemPrompt, userMessage) {
const body = {
model,
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userMessage }
],
response_format: { type: "json_object" },
temperature: 0.3,
max_tokens: 4096
};
const response = await fetch(`${DEEPSEEK_BASE_URL}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`
},
body: JSON.stringify(body)
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(
`DeepSeek API error: ${response.status} ${response.statusText}
${errorBody}`
);
}
const data = await response.json();
return data.choices[0].message.content;
}
var QUERY_TOOL = {
type: "function",
function: {
name: "submit_queries",
description: "Submit Arxiv search queries",
parameters: {
type: "object",
properties: {
queries: {
type: "array",
items: { type: "string" },
description: "Array of Arxiv search queries, each starting with all: prefix"
}
},
required: ["queries"],
additionalProperties: false
}
}
};
async function expandSearchQueries(apiKey, model, directions) {
const systemPrompt = "You are a research assistant that generates precise Arxiv search queries. Given research directions, produce exactly ONE query per direction. CRITICAL: Each query must be DIRECTLY about the given direction \u2014 no tangential topics. EVERY query MUST start with all: prefix. Use quotes for multi-word phrases. Include the most specific terms from the direction to ensure relevance.";
const userMessage = `Generate one precise Arxiv search query for EACH direction:
${directions.map((d, i) => `${i + 1}. ${d}`).join("\n")}`;
let content;
try {
content = await callDeepSeekWithTools(apiKey, model, systemPrompt, userMessage, [QUERY_TOOL]);
} catch (e) {
const fallbackPrompt = systemPrompt + '\n\nReturn a JSON object: { "queries": ["..."] }';
content = await callDeepSeekJson(apiKey, model, fallbackPrompt, userMessage);
}
const result = JSON.parse(content);
if (!result.queries || !Array.isArray(result.queries)) {
throw new Error("Query expansion failed: missing 'queries' array");
}
return result.queries.map((q) => {
const t = q.trim();
if (t.startsWith("all:") || t.startsWith("cat:"))
return t;
return `all:${t}`;
});
}
var SCORE_BATCH_SIZE = 20;
var SCORE_TOOL = {
type: "function",
function: {
name: "submit_paper_scores",
description: "Submit scored paper evaluations",
parameters: {
type: "object",
properties: {
papers: {
type: "array",
items: {
type: "object",
properties: {
id: { type: "string", description: "Paper ID" },
score: { type: "number", description: "Score 1-10" },
reason: { type: "string", description: "Brief reason for the score" }
},
required: ["id", "score", "reason"],
additionalProperties: false
}
}
},
required: ["papers"],
additionalProperties: false
}
}
};
async function scorePaperBatch(apiKey, model, batch, language, directions) {
const langHint = language === "zh-CN" ? "\u4E2D\u6587" : "English";
const directionList = directions.join(", ");
const systemPrompt = `You are a research paper reviewer. Score each paper 1-10 based on: (1) relevance to the specified research directions, (2) novelty, (3) impact, (4) quality. Relevance is the MOST important factor \u2014 only score high if the paper is clearly about one of the given directions. Write reasons in ${langHint}. Be critical \u2014 most papers score 3-5.`;
const paperList = batch.map(
(p, i) => `[${i + 1}] ID: ${p.id}
Title: ${p.title}
Abstract: ${p.summary}`
).join("\n---\n");
const userMessage = `Research directions: ${directionList}
Score these ${batch.length} papers for relevance to the above directions:
${paperList}`;
let content;
try {
content = await callDeepSeekWithTools(apiKey, model, systemPrompt, userMessage, [SCORE_TOOL]);
} catch (e) {
const fallbackPrompt = systemPrompt + '\n\nReturn JSON: { "papers": [{ "id": "...", "score": 0, "reason": "..." }] }';
content = await callDeepSeekJson(apiKey, model, fallbackPrompt, userMessage);
}
const result = JSON.parse(content);
if (!result.papers || !Array.isArray(result.papers)) {
throw new Error("Scoring failed: missing 'papers' array");
}
return result.papers;
}
async function scorePapers(apiKey, model, papers, language, directions, onProgress) {
if (papers.length === 0)
return [];
const toScore = [];
const cachedResults = [];
for (const p of papers) {
const cached = getCachedScore(p.id);
if (cached) {
cachedResults.push({ id: p.id, ...cached });
} else {
toScore.push(p);
}
}
if (toScore.length === 0) {
return cachedResults.sort((a, b) => b.score - a.score);
}
const allScored = [...cachedResults];
const totalBatches = Math.ceil(toScore.length / SCORE_BATCH_SIZE);
for (let i = 0; i < toScore.length; i += SCORE_BATCH_SIZE) {
const batch = toScore.slice(i, i + SCORE_BATCH_SIZE);
const batchNum = Math.floor(i / SCORE_BATCH_SIZE) + 1;
onProgress == null ? void 0 : onProgress({
step: "score",
message: `\u8BC4\u5206\u4E2D... \u7B2C ${batchNum}/${totalBatches} \u6279 (${Math.min(i + SCORE_BATCH_SIZE, toScore.length)}/${toScore.length} \u7BC7)`,
percent: Math.round(i / toScore.length * 80) + 10
// 10-90% range
});
const batchResults = await scorePaperBatch(apiKey, model, batch, language, directions);
for (const r of batchResults) {
setCachedScore(r.id, r.score, r.reason);
}
allScored.push(...batchResults);
}
return allScored.sort((a, b) => b.score - a.score);
}
var SUMMARY_TOOL = {
type: "function",
function: {
name: "submit_paper_summaries",
description: "Submit detailed paper summaries",
parameters: {
type: "object",
properties: {
summaries: {
type: "array",
items: {
type: "object",
properties: {
id: { type: "string", description: "Paper ID" },
summary: { type: "string", description: "2-3 sentence summary" },
keyPoints: {
type: "array",
items: { type: "string" },
description: "3-5 key bullet points"
}
},
required: ["id", "summary", "keyPoints"],
additionalProperties: false
}
}
},
required: ["summaries"],
additionalProperties: false
}
}
};
async function summarizePapers(apiKey, model, papers, language, onProgress) {
if (papers.length === 0)
return [];
const langHint = language === "zh-CN" ? "\u4E2D\u6587" : "English";
const systemPrompt = `You are a research paper analyst. Generate concise summaries and key points in ${langHint}. Summaries should be 2-3 sentences capturing the essence. Key points should be 3-5 specific technical bullet points. Keep technical terms in English when commonly used.`;
const paperList = papers.map(
(p, i) => `[${i + 1}] ID: ${p.id}
Title: ${p.title}
Authors: ${p.authors.join(", ")}
Abstract: ${p.summary}`
).join("\n---\n");
const userMessage = `Summarize these ${papers.length} papers:
${paperList}`;
onProgress == null ? void 0 : onProgress({ step: "summarize", message: "\u6B63\u5728\u751F\u6210\u6458\u8981...", percent: 90 });
let content;
try {
content = await callDeepSeekWithTools(apiKey, model, systemPrompt, userMessage, [SUMMARY_TOOL]);
} catch (e) {
const fallbackPrompt = systemPrompt + '\n\nReturn JSON: { "summaries": [{ "id": "...", "summary": "...", "keyPoints": ["..."] }] }';
content = await callDeepSeekJson(apiKey, model, fallbackPrompt, userMessage);
}
const result = JSON.parse(content);
if (!result.summaries || !Array.isArray(result.summaries)) {
throw new Error("Summarization failed: missing 'summaries' array");
}
return result.summaries;
}
var CRAWL_TOOL = {
type: "function",
function: {
name: "submit_crawl_queries",
description: "Submit expanded search queries based on discovered papers",
parameters: {
type: "object",
properties: {
queries: {
type: "array",
items: { type: "string" },
description: "Additional Arxiv search queries with all: prefix"
}
},
required: ["queries"],
additionalProperties: false
}
}
};
async function crawlReferences(apiKey, model, topPapers, maxResultsPerQuery, startDate, endDate, onProgress) {
onProgress == null ? void 0 : onProgress({ step: "crawl", message: "PaSa Agent \u6B63\u5728\u5206\u6790\u8BBA\u6587\u5E76\u6269\u5C55\u641C\u7D22...", percent: 5 });
const keywordHints = topPapers.slice(0, 5).map((p) => p.title.replace(/[^a-zA-Z0-9\s]/g, "").slice(0, 80)).join("\n");
const systemPrompt = "You are a paper search agent (PaSa Crawler). Given top papers found, generate ADDITIONAL Arxiv search queries to find RELATED but DIFFERENT papers that cite similar concepts. Generate 2-4 queries. CRITICAL: Each query must start with all: prefix. Avoid duplicating existing searches.";
const userMessage = `Top papers found:
${keywordHints}
Generate additional search queries to find more relevant papers.`;
let content;
try {
content = await callDeepSeekWithTools(apiKey, model, systemPrompt, userMessage, [CRAWL_TOOL]);
} catch (e) {
const fallbackPrompt = systemPrompt + '\n\nReturn JSON: { "queries": ["all:...", "all:..."] }';
content = await callDeepSeekJson(apiKey, model, fallbackPrompt, userMessage);
}
const result = JSON.parse(content);
if (!result.queries || !Array.isArray(result.queries)) {
return [];
}
const queries = result.queries.map((q) => {
const t = q.trim();
return t.startsWith("all:") || t.startsWith("cat:") ? t : `all:${t}`;
});
onProgress == null ? void 0 : onProgress({ step: "crawl", message: `PaSa Agent \u6B63\u5728\u641C\u7D22 ${queries.length} \u4E2A\u6269\u5C55\u67E5\u8BE2...`, percent: 30 });
const newPapers = await fetchPapersByQueries(queries, maxResultsPerQuery, startDate, endDate);
onProgress == null ? void 0 : onProgress({
step: "crawl",
message: `PaSa Agent \u6269\u5C55\u627E\u5230 ${newPapers.length} \u7BC7\u989D\u5916\u8BBA\u6587`,
percent: 60
});
return newPapers;
}
async function orchestrate(options) {
const {
apiKey,
model,
directions,
maxResultsPerDirection,
topN,
language,
startDate,
endDate,
usePaSaCrawler = false,
onProgress
} = options;
onProgress == null ? void 0 : onProgress({ step: "query", message: "Agent \u6B63\u5728\u5206\u6790\u7814\u7A76\u65B9\u5411\u5E76\u751F\u6210\u641C\u7D22\u67E5\u8BE2...", percent: 0 });
let queries;
try {
queries = await expandSearchQueries(apiKey, model, directions);
onProgress == null ? void 0 : onProgress({ step: "query", message: `\u5DF2\u751F\u6210 ${queries.length} \u6761\u641C\u7D22\u67E5\u8BE2`, percent: 5 });
} catch (e) {
console.warn("Query expansion failed, using raw directions:", e);
queries = directions.map((d) => `all:${d}`);
onProgress == null ? void 0 : onProgress({ step: "query", message: `\u76F4\u63A5\u4F7F\u7528 ${queries.length} \u4E2A\u65B9\u5411\u540D\u79F0\u641C\u7D22`, percent: 5 });
}
onProgress == null ? void 0 : onProgress({ step: "fetch", message: "\u6B63\u5728\u4ECE arXiv \u83B7\u53D6\u8BBA\u6587...", percent: 5 });
let allPapers = await fetchPapersByQueries(queries, maxResultsPerDirection, startDate, endDate);
if (allPapers.length === 0) {
console.warn("Generated queries returned no papers, retrying with raw direction queries");
const fallbackQueries = directions.map((d) => `all:${d}`);
allPapers = await fetchPapersByQueries(fallbackQueries, maxResultsPerDirection, startDate, endDate);
}
if (allPapers.length === 0) {
throw new Error("\u8BE5\u65E5\u671F\u6682\u65E0\u76F8\u5173\u8BBA\u6587");
}
onProgress == null ? void 0 : onProgress({ step: "fetch", message: `\u5DF2\u83B7\u53D6 ${allPapers.length} \u7BC7\u8BBA\u6587`, percent: 10 });
const scoredPapers = await scorePapers(apiKey, model, allPapers, language, directions, onProgress);
if (scoredPapers.length === 0) {
throw new Error("\u8BBA\u6587\u8BC4\u5206\u5931\u8D25");
}
onProgress == null ? void 0 : onProgress({ step: "score", message: `\u5DF2\u8BC4\u5206 ${scoredPapers.length} \u7BC7\u8BBA\u6587`, percent: 85 });
if (usePaSaCrawler) {
const topForCrawl = scoredPapers.slice(0, Math.min(topN * 2, scoredPapers.length));
const topPaperObjects = topForCrawl.map((sp) => allPapers.find((p) => p.id === sp.id)).filter((p) => !!p);
const crawledPapers = await crawlReferences(
apiKey,
model,
topPaperObjects,
maxResultsPerDirection,
startDate,
endDate,
onProgress
);
if (crawledPapers.length > 0) {
const crawledScored = await scorePapers(apiKey, model, crawledPapers, language, directions, onProgress);
allPapers.push(...crawledPapers);