forked from anan1213095357/PiPiClaw
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
4413 lines (4152 loc) · 211 KB
/
Copy pathProgram.cs
File metadata and controls
4413 lines (4152 loc) · 211 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
using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Net.NetworkInformation;
Directory.SetCurrentDirectory(AppContext.BaseDirectory);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !Console.IsOutputRedirected)
{
try
{
using var pChcp = Process.Start(new ProcessStartInfo("cmd.exe", "/c chcp 65001") { CreateNoWindow = true });
pChcp?.WaitForExit();
}
catch { }
}
Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;
AppConfig GlobalConfig = new();
// ========================== 1. 基础配置与初始化 ==========================
if (!File.Exists("appsettings.json"))
{
// 初次运行生成默认配置
File.WriteAllText("appsettings.json", JsonSerializer.Serialize(GlobalConfig, AppJsonContext.Default.AppConfig), Encoding.UTF8);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("检测到首次运行,已自动生成默认的 appsettings.json 文件。");
Console.ResetColor();
}
else
{
try
{
var json = File.ReadAllText("appsettings.json", Encoding.UTF8);
var cfg = JsonSerializer.Deserialize(json, AppJsonContext.Default.AppConfig);
if (cfg != null) GlobalConfig = cfg;
}
catch { /* 忽略解析错误,使用默认值 */ }
}
string GetConfig(string key, string def = "")
{
var envValue = Environment.GetEnvironmentVariable(key);
if (envValue != null) return envValue;
var firstModel = (GlobalConfig.Models != null && GlobalConfig.Models.Count > 0)
? GlobalConfig.Models[0]
: new ModelConfig();
return key switch
{
"ApiKey" => !string.IsNullOrEmpty(firstModel.ApiKey) ? firstModel.ApiKey : def,
"Model" => !string.IsNullOrEmpty(firstModel.Model) ? firstModel.Model : def,
"Endpoint" => !string.IsNullOrEmpty(firstModel.Endpoint) ? firstModel.Endpoint : def,
"SudoPassword" => GlobalConfig.SudoPassword ?? def,
"WebPort" => GlobalConfig.WebPort > 0 ? GlobalConfig.WebPort.ToString() : def,
"SkillHubSearchUrl" => !string.IsNullOrEmpty(GlobalConfig.SkillHubSearchUrl) ? GlobalConfig.SkillHubSearchUrl : def,
_ => def
};
}
// 新增热重载函数
void ReloadConfig()
{
try
{
if (File.Exists("appsettings.json"))
{
var json = File.ReadAllText("appsettings.json", Encoding.UTF8);
var cfg = JsonSerializer.Deserialize(json, AppJsonContext.Default.AppConfig);
if (cfg != null) GlobalConfig = cfg;
}
}
catch { /* 忽略解析错误,避免配置文件损坏时程序崩溃 */ }
}
var toolsDoc = JsonDocument.Parse("""
[
{ "type": "function", "function": { "name": "execute_command", "description": "执行终端命令", "parameters": { "type": "object", "properties": { "command": { "type": "string" }, "is_background": { "type": "boolean", "description": "【注意,生死攸关的判断】请严格按以下规则选择:\n1. 必须设为 true (后台):适用于【永远不会自动退出】或【启动常驻服务/UI】或【启动浏览器自动化】等等的命令。例如:启动 Web 服务器、数据库守护进程、打开浏览器及UI自动化(如 agent-browser/chrome)、死循环脚本。这类任务必须丢入后台,否则你会把自己永久卡死!\n2. 必须设为 false (前台):适用于【执行完会自动结束】并且你需要查看最终输出结果的命令。例如:环境部署(npm install, pip install)、编译构建、下载文件、查日志、执行普通算法脚本。即使这些任务非常耗时,只要它们最终会结束,就必须设为 false 以便拿到完整的执行日志。" } }, "required": ["command", "is_background"] } } },
{ "type": "function", "function": { "name": "read_file", "description": "读文件", "parameters": { "type": "object", "properties": { "file_path": { "type": "string" } }, "required": ["file_path"] } } },
{ "type": "function", "function": { "name": "write_file", "description": "写文件或局部修改文件。局部修改必须提供 old_content。", "parameters": { "type": "object", "properties": { "file_path": { "type": "string" }, "content": { "type": "string" }, "old_content": { "type": "string" } }, "required": ["file_path", "content"] } } },
{ "type": "function", "function": { "name": "read_local_image", "description": "看图(读取本地图片为 base64)", "parameters": { "type": "object", "properties": { "file_path": { "type": "string" } }, "required": ["file_path"] } } },
{ "type": "function", "function": { "name": "search_content", "description": "全局搜索关键字。", "parameters": { "type": "object", "properties": { "keyword": { "type": "string" }, "directory": { "type": "string" }, "file_pattern": { "type": "string" } }, "required": ["keyword"] } } },
{ "type": "function", "function": { "name": "finish_task", "description": "当用户主动提及清理上下文或者清理聊天记录时触发。", "parameters": { "type": "object", "properties": {} } } },
{ "type": "function", "function": { "name": "add_scheduled_task", "description": "添加定时或延时任务。系统底层的C#引擎会绝对接管时间调度,绝不能在任务执行时由AI去动态补加下一次任务。", "parameters": { "type": "object", "properties": { "execute_at": { "type": "string", "description": "首次执行时间,严格遵循 ISO 8601 格式,例如 '2026-03-20T14:30:00+08:00'" }, "user_intent": { "type": "string", "description": "到达时间时,大模型需要执行的具体任务要求和背景" }, "interval_minutes": { "type": "integer", "description": "可选。如果是周期性任务,请设置此周期间隔(分钟数)。例如每天执行则设为 1440。如果不填或为 0,则仅执行一次。系统会在底层自动无限循环,无需AI干预。" } }, "required": ["execute_at", "user_intent"] } } },
{ "type": "function", "function": { "name": "remove_scheduled_task", "description": "删除指定的定时或延时任务。", "parameters": { "type": "object", "properties": { "task_id": { "type": "string", "description": "要删除的任务ID(从任务列表中获取)" } }, "required": ["task_id"] } } },
{ "type": "function", "function": { "name": "install_skill", "description": "安装 单个 Skill-hub 或者 从第三方的技能,并根据包含的 MD 文件自动了解对接方式。", "parameters": { "type": "object", "properties": { "slug": { "type": "string", "description": "技能列表中的slug字段只需传入这个字段即可" } }, "required": ["slug"] } } },
{ "type": "function", "function": { "name": "self_update", "description": "当用户要求皮皮虾自我更新、自动更新或升级自身时调用此工具。将从 GitHub 下载最新版本并自动重启。", "parameters": { "type": "object", "properties": {} } } },
{ "type": "function", "function": { "name": "delegate_task", "description": "向通讯录中的其他皮皮虾节点指派任务。请从系统提示词的【友军通讯录】中查找对方的准确名字。严禁委派给当前节点自己!", "parameters": { "type": "object", "properties": { "user_name": { "type": "string", "description": "目标节点的名称,例如 '树莓派'" }, "task_message": { "type": "string", "description": "你要交办的具体任务内容" } }, "required": ["user_name", "task_message"] } } },
{ "type": "function", "function": { "name": "save_memory", "description": "当用户提到重要的个人信息、偏好设定、或者明确要求你'记住'某事时调用此工具。", "parameters": { "type": "object", "properties": { "content": { "type": "string", "description": "要保存的具体记忆内容" } }, "required": ["content"] } } },
{ "type": "function", "function": { "name": "recall_memory", "description": "通过语义向量检索长期记忆库。当用户问'我之前说过什么'、'我的喜好',或你需要回忆过去的上下文背景时调用。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "要检索的关键字或语义短语" } }, "required": ["query"] } } }
]
""");
//在没有找到合适的 搜索 api 之前先注释
// { "type": "function", "function": { "name": "search_skill", "description": "当用户要求安装、查找或添加某个特定技能时执行此功能。根据关键词从 Skill-hub 搜索技能。注意:当用户说要“自我构建”或“编写”技能时,不要执行此功能。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "用户想要搜索或安装的技能关键词,例如 'calendar', 'weather' 等" } }, "required": ["query"] } } },
// ========================== Logo & 简介 ==========================
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine(@"
____ _ ____ _ ______ _
| _ \ (_)| _ \ (_)/ ____|| |
| |_) | _ | |_) | _ | | | | __ _ __ __
| __/ | || __/ | || | | | / _ |\ \ /\ / /
| | | || | | || |____ | | | (_| | \ V V /
|_| |_||_| |_| \______|____\__,_| \_/\_/
");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"皮皮虾已就绪。当前模型:[ {GetConfig("Model", "qwen3.5-plus")} ]");
Console.WriteLine("跨平台全能智能体 · http://www.clawhub.ai 30000+ 技能即刻可用\n");
Console.ResetColor();
Console.WriteLine("【简介与食用指南】");
Console.WriteLine("这是一个能够全自动执行终端命令、读写文件、规划任务的 AI 自动化终端。\n只要像吩咐人类一样说话,它就会自己写脚本、查日志、执行系统命令来帮你办事。");
Console.WriteLine("\n💡 试试直接粘贴以下命令 (傻瓜式案例):");
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(" 1. \"帮我扫描一下当前目录,看有没有 C# 相关的源码文件\"");
Console.WriteLine(" 2. \"用 C# 写一个能控制树莓派 GPIO 针脚电平的简单脚本,并帮我运行它测试一下\"");
Console.WriteLine(" 3. \"帮我查一下系统当前的内存占用情况,并把结果写进 memory_log.txt\"");
Console.WriteLine(" 4. \"每天下午3点,帮我屏幕截图看一下我在干什么?\"");
Console.ResetColor();
Console.WriteLine("---------------------------------------------------------------------------\n");
// ========================== 4. Sudo 权限处理 ==========================
string sudoPassword = GetConfig("SudoPassword", "");
bool isWin = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
string sudoInstruction = isWin
? "如果遇到权限拒绝,请使用 PowerShell 的 PSCredential 结合 Start-Process -Verb RunAs 尝试执行,或者直接提示用户关闭控制台,以【管理员身份运行】重新打开本程序。千万不要使用 sudo 命令。"
: "如果遇到提权(Permission denied),请直接使用 sudo 命令。系统会在底层按需拦截并向用户索要密码,你无需关心密码输入环节。";
// ========================== 5. 核心状态变量与网络请求初始化 ==========================
string recordsDir = Path.Combine(AppContext.BaseDirectory, "Records");
if (!Directory.Exists(recordsDir)) Directory.CreateDirectory(recordsDir);
string tasksPath = Path.Combine(recordsDir, "pi_scheduled_tasks.json");
// 移除单一的全局变量,改为多用户并发字典
System.Collections.Concurrent.ConcurrentDictionary<string, List<ChatMessage>> userHistories = new();
System.Collections.Concurrent.ConcurrentDictionary<string, SemaphoreSlim> userLocks = new();
System.Collections.Concurrent.ConcurrentDictionary<string, CancellationTokenSource> userCts = new();
System.Collections.Concurrent.ConcurrentDictionary<string, List<PushMsg>> userLiveStream = new();
System.Collections.Concurrent.ConcurrentDictionary<string, Action<PushMsg>> userConnections = new();
lock (tasksPath)
{
if (!File.Exists(tasksPath)) File.WriteAllText(tasksPath, "[]", Encoding.UTF8);
}
List<ChatMessage> GetHistory(string user)
{
if (userHistories.TryGetValue(user, out var h)) return h;
var path = Path.Combine(recordsDir, $"{user}_history.json");
var list = new List<ChatMessage>();
if (File.Exists(path))
{
try { list = JsonSerializer.Deserialize(File.ReadAllText(path, Encoding.UTF8), AppJsonContext.Default.ListChatMessage) ?? new(); } catch { }
}
userHistories[user] = list;
return list;
}
using var client = new HttpClient();
client.Timeout = TimeSpan.FromHours(1);
const string CancelledMsg = "\n[任务已取消]";
bool selfUpdateRequested = false;
// ========================== 6. 启动后台服务 (调度 + WebUI) ==========================
_ = Task.Run(ScheduleLoop);
_ = Task.Run(StartWebManager);
// ========================== 7. 定时任务管理逻辑 ==========================
string AddScheduledTask(string username, string? execAtStr, string? intent, int intervalMinutes = 0)
{
if (!DateTimeOffset.TryParse(execAtStr, out var execTime))
return "[添加失败] 时间格式解析错误,请使用 ISO 8601 格式,如 2026-03-20T15:30:00+08:00";
if (execTime < DateTimeOffset.Now && intervalMinutes == 0)
return $"[添加失败] 设定时间 {execTime:yyyy-MM-dd HH:mm:ss} 已过去,且不是周期任务。";
lock (tasksPath)
{
var tasks = new List<TaskItem>();
if (File.Exists(tasksPath))
{
try { tasks = JsonSerializer.Deserialize(File.ReadAllText(tasksPath, Encoding.UTF8), AppJsonContext.Default.ListTaskItem) ?? new(); } catch { }
}
var newTask = new TaskItem
{
Id = Guid.NewGuid().ToString("N"),
ExecuteAt = execTime.ToString("o"),
UserIntent = intent ?? "未提供具体意图",
Status = "pending",
IntervalMinutes = intervalMinutes,
Username = username // 👈 绑定到当前操作的用户
};
tasks.Add(newTask);
File.WriteAllText(tasksPath, JsonSerializer.Serialize(tasks, AppJsonContext.Default.ListTaskItem), Encoding.UTF8);
}
// 控制台输出顺手加上归属人
Console.ForegroundColor = ConsoleColor.Green;
string loopStr = intervalMinutes > 0 ? $" [周期: 每 {intervalMinutes} 分钟执行]" : " [单次执行]";
Console.WriteLine($"[调度中心] 成功创建任务: {execTime:yyyy-MM-dd HH:mm:ss} -> {intent}{loopStr} (归属: {username})");
Console.ResetColor();
return $"[定时任务已添加] PiPiClaw 已将任务持久化,将在 {execTime:yyyy-MM-dd HH:mm:ss} 触发执行。{loopStr} 用户的需求是:{intent}。系统会在底层调度,请不要再次重复调用添加任务。";
}
string RemoveScheduledTask(string username, string? taskId)
{
if (string.IsNullOrEmpty(taskId)) return "[删除失败] 必须提供 task_id";
lock (tasksPath)
{
if (!File.Exists(tasksPath)) return "[删除失败] 任务文件不存在";
var tasks = new List<TaskItem>();
try { tasks = JsonSerializer.Deserialize(File.ReadAllText(tasksPath, Encoding.UTF8), AppJsonContext.Default.ListTaskItem) ?? new(); } catch { }
// 👈 核心:只能删自己名下的任务
var targetNode = tasks.FirstOrDefault(t => t.Id == taskId && t.Username == username);
if (targetNode != null)
{
tasks.Remove(targetNode);
File.WriteAllText(tasksPath, JsonSerializer.Serialize(tasks, AppJsonContext.Default.ListTaskItem), Encoding.UTF8);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"\n[调度中心] 成功移除任务 (ID: {taskId}, 归属: {username})");
Console.ResetColor();
return $"[任务已删除] 成功移除了 ID 为 {taskId} 的任务。";
}
return $"[删除失败] 未在挂起队列中找到归属于你且 ID 为 {taskId} 的任务。";
}
}
// ========================== 8. 挂起任务顶层展示区 ==========================
void ShowPendingTasks()
{
if (!File.Exists(tasksPath)) return;
try
{
var tasks = new List<TaskItem>();
lock (tasksPath)
{
var tasksStr = File.ReadAllText(tasksPath, Encoding.UTF8);
if (!string.IsNullOrWhiteSpace(tasksStr)) tasks = JsonSerializer.Deserialize(tasksStr, AppJsonContext.Default.ListTaskItem) ?? new();
}
var pendingTasks = tasks.Where(t => t.Status == "pending").ToList();
if (pendingTasks.Count > 0)
{
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine("".PadLeft(20, '-') + "[ PiPiClaw 挂起任务 ] " + "".PadRight(20, '-') + "\n");
foreach (var t in pendingTasks)
{
if (!DateTimeOffset.TryParse(t.ExecuteAt, out var execTime)) continue;
var intent = string.IsNullOrEmpty(t.UserIntent) ? "未知" : t.UserIntent;
var diff = execTime - DateTimeOffset.Now;
int intervalMinutes = t.IntervalMinutes;
string loopDisplay = intervalMinutes > 0 ? $" [周期:每{intervalMinutes}分]" : "";
bool isDelayed = diff.TotalHours < 2;
string taskType = isDelayed ? "延时任务" : "定时任务";
string timeDisplay;
if (diff.TotalSeconds > 0)
{
if (diff.Days > 0) timeDisplay = $"倒计时 {diff.Days}天{diff.Hours}小时{diff.Minutes}分";
else if (diff.Hours > 0) timeDisplay = $"倒计时 {diff.Hours}小时{diff.Minutes}分{diff.Seconds}秒";
else timeDisplay = $"倒计时 {diff.Minutes}分{diff.Seconds}秒";
}
else timeDisplay = "即将触发执行...";
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write($" [{taskType}] ");
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine($"{execTime:MM-dd HH:mm:ss} ({timeDisplay}){loopDisplay}");
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine($" └─ [归属: {t.Username}] 需求: {intent} (ID: {t.Id})");
}
Console.ResetColor();
}
}
catch { /* 忽略解析错误 */ }
}
// ========================== 获取局域网 IP ==========================
string GetLocalIpAddress()
{
try
{
string? backupIp = null;
foreach (var item in NetworkInterface.GetAllNetworkInterfaces())
{
if (item.OperationalStatus != OperationalStatus.Up) continue;
if (item.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
var name = item.Name.ToLower();
var desc = item.Description.ToLower();
if (name.Contains("vmware") || name.Contains("virtual") || name.Contains("vbox") ||
desc.Contains("vmware") || desc.Contains("virtual") || desc.Contains("vpn") ||
desc.Contains("zerotier") || desc.Contains("radmin") || desc.Contains("tailscale"))
{
continue;
}
foreach (var ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
var ipStr = ip.Address.ToString();
if (ipStr.StartsWith("192.168.") || ipStr.StartsWith("10.") ||
(ipStr.StartsWith("172.") && !ipStr.StartsWith("172.16."))) // Docker 默认常在 172.17+
{
return ipStr;
}
if (string.IsNullOrEmpty(backupIp) && !ipStr.StartsWith("169.254."))
{
backupIp = ipStr;
}
}
}
}
return backupIp ?? "127.0.0.1";
}
catch
{
return "127.0.0.1";
}
}
// ========================== 9. 主交互死循环 ==========================
while (true)
{
ShowPendingTasks();
Console.ForegroundColor = ConsoleColor.Magenta;
string? input = null;
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
Console.Write("\n皮皮虾 > ");
input = Console.ReadLine();
}
if (input == null)
{
await Task.Delay(-1);
}
if (string.IsNullOrEmpty(input)) continue;
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase)) break;
await RunAgent(input);
}
return;
// ========================== 10. 核心 Agent 处理逻辑 ==========================
async Task<string> RunAgent(string inputMessage, bool isScheduledEvent = false, int modelIndex = 0, string username = "local", string caller = "")
{
var userLock = userLocks.GetOrAdd(username, _ => new SemaphoreSlim(100, 100));
await userLock.WaitAsync();
var liveStream = new List<PushMsg>();
userLiveStream[username] = liveStream;
Action<string, string> PushUpdate = (type, content) =>
{
var pm = new PushMsg { Type = type, Content = content };
lock (liveStream) liveStream.Add(pm);
if (userConnections.TryGetValue(username, out var conn)) conn(pm);
};
var historyPath = Path.Combine(recordsDir, $"{username}_history.json");
var history = GetHistory(username);
void SafeAddHistory(ChatMessage m)
{
lock (history)
{
history.Add(m.DeepClone());
SaveData(history, historyPath);
}
}
var currentModelCfg = (GlobalConfig.Models != null && GlobalConfig.Models.Count > modelIndex)
? GlobalConfig.Models[modelIndex]
: (GlobalConfig.Models?.FirstOrDefault() ?? new ModelConfig());
var activeModel = !string.IsNullOrEmpty(currentModelCfg.Model) ? currentModelCfg.Model : "qwen3.5-plus";
// 默认值改为不带后缀的 v1
var rawEndpoint = !string.IsNullOrEmpty(currentModelCfg.Endpoint) ? currentModelCfg.Endpoint : "https://dashscope.aliyuncs.com/compatible-mode/v1";
// 自动清洗可能残留的旧版后缀,提取纯净的 API Base
string apiBase = rawEndpoint.EndsWith("/chat/completions", StringComparison.OrdinalIgnoreCase)
? rawEndpoint.Substring(0, rawEndpoint.Length - 17)
: rawEndpoint;
apiBase = apiBase.TrimEnd('/');
// 聊天端点
string chatEndpoint = apiBase + "/chat/completions";
// 这里顺手为你后续的 Embedding 提前准备好变量
string embeddingEndpoint = apiBase + "/embeddings";
var activeApiKey = currentModelCfg.ApiKey;
using var taskCts = new CancellationTokenSource();
userCts[username] = taskCts;
string finalAIResponse = "";
try
{
var useFullContext = false;
var requireReset = false;
var userMsg = new ChatMessage { Role = "user", Content = inputMessage, Timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") };
SafeAddHistory(userMsg);
var isDone = false;
while (!isDone)
{
using var cts = new CancellationTokenSource();
var animTask = Think(username, cts.Token);
var currentTasksJson = "暂无定时任务";
if (File.Exists(tasksPath))
{
lock (tasksPath)
{
try
{
var allTasks = JsonSerializer.Deserialize(File.ReadAllText(tasksPath, Encoding.UTF8), AppJsonContext.Default.ListTaskItem) ?? new();
var userTasks = allTasks.Where(t => t.Username == username).ToList();
if (userTasks.Count > 0)
{
currentTasksJson = JsonSerializer.Serialize(userTasks, AppJsonContext.Default.ListTaskItem);
}
}
catch { }
}
}
var callerStr = !string.IsNullOrEmpty(caller)
? $"\n【任务来源追溯】:当前任务由友军【{caller}】指派。当任务彻底做完准备交付时,请**直接用自然语言输出最终结果**,系统底层会全自动将你的话作为工作报告回传给【{caller}】!绝对不要用 delegate_task 跑去向【{caller}】做最终汇报。(注:若执行中途遇到困难,需要向【{caller}】请教确认需求,仍可使用 delegate_task 联系对方)。\n"
: "";
var nodeIdentityStr = !string.IsNullOrEmpty(username)
? $"你当前是【{username}】皮皮虾。如【友军通讯录】中看到你自己!请直接用本地工具执行,绝对不要委派给自己!\n"
: "";
var peersStr = (GlobalConfig.PeerNodes != null && GlobalConfig.PeerNodes.Count > 0)
? string.Join("\n", GlobalConfig.PeerNodes.Select(p =>
$"- 【{p.Key}】皮皮虾\n 能力说明: 【{p.Value.Role}】{p.Value.Description}" +
(!string.IsNullOrWhiteSpace(p.Value.Resume) ? $"\n 详细介绍: {p.Value.Resume}" : "")))
: "暂无已知友军节点";
var customPrompt = !string.IsNullOrWhiteSpace(GlobalConfig.SystemPrompt)
? GlobalConfig.SystemPrompt
: "你是一个全能智能 Agent,代号 PiPiClaw (皮皮虾)。你的使命:以本地优先、安全可审计的方式完成用户提出的任何任务,不限于运维/开发/数据/知识检索。你可随时通过 Skill-Hub 安装技能扩展能力。";
var systemPromptText = $$"""
{{customPrompt}}
{{callerStr}}
【当前环境状态】
当前系统:{{RuntimeInformation.OSDescription}}。当前时间是 {{DateTimeOffset.Now:yyyy-MM-ddTHH:mm:sszzz}}。
{{sudoInstruction}}
【记忆管理架构】:
[技能调用与经验沉淀策略]
1. 检索:查阅下方已安装技能的摘要。
2. 实战:若需使用某技能,优先用 read_file 读取其目录下的 experience.txt(实战干货)。若没有,再去读 skill.md(官方文档)。
3. 沉淀与进化:当你【成功跑通】某技能的具体功能并解决报错后,必须将经验沉淀到 experience.txt。
- 强制 SOP:① 必须先 read_file 读取现有的 experience.txt。② 在脑内将新经验按【具体调用的方法/子命令】分类,与老经验进行合并、去重、纠错。③ 使用 write_file 将合并后的新内容完整覆写回去。
- 内容格式:绝对不要写废话!按 Markdown 结构记录:`### 方法名` -> `- 核心测试命令` -> `- 避坑/报错解决指南`。拒绝简单粗暴的流水账追加。
【身份认知】
{{nodeIdentityStr}}
【友军通讯录 (Peer Nodes)】:
当用户提的需求友军能力满足的时候,优先调用 delegate_task 工具,以下是友军的能力说明:
{{peersStr}}
【PiPiClaw 挂起的定时任务(包含 task_id,供你管理任务时参考)】:
{{currentTasksJson}}
【本地已安装的扩展技能及绝对路径说明】:
{{GetInstalledSkillsContext(username)}}
注意:本地技能优先级高于队友能力。如果本地没有这个技能再去找相关队友。
""";
var payloadMessages = new List<ChatMessage> { new ChatMessage { Role = "system", Content = systemPromptText } };
IEnumerable<ChatMessage> recentMessages;
if (useFullContext)
{
recentMessages = history;
}
else
{
var seenUser = 0;
var startIndex = 0;
for (var i = history.Count - 1; i >= 0; i--)
{
if (history[i].Role != "user") continue;
seenUser++;
if (seenUser <= 3) continue;
startIndex = i + 1;
break;
}
recentMessages = history.Skip(startIndex);
}
foreach (var m in recentMessages) payloadMessages.Add(m.DeepClone());
var payload = new LlmRequest
{
Model = activeModel,
Messages = payloadMessages,
Tools = toolsDoc.RootElement,
EnableSearch = true
};
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", activeApiKey);
string responseString = "";
bool isSuccess = false;
Exception? lastEx = null;
int maxRetries = 30; // 设置最大重试次数
for (int retry = 0; retry < maxRetries; retry++)
{
try
{
// 注意:每次重试需要重新生成 StringContent,避免流被重复读取导致报错
var content = new StringContent(JsonSerializer.Serialize(payload, AppJsonContext.Default.LlmRequest), Encoding.UTF8, "application/json");
var res = await client.PostAsync(chatEndpoint, content, taskCts.Token);
if (res.IsSuccessStatusCode)
{
responseString = await res.Content.ReadAsStringAsync(taskCts.Token);
isSuccess = true;
break; // 请求成功,跳出重试循环
}
int statusCode = (int)res.StatusCode;
// 如果网关返回 5xx 错误,手动抛出异常以触发重试
if (statusCode >= 500 && statusCode < 600)
{
throw new Exception($"网关返回 5xx 错误码 ({statusCode})");
}
else
{
var ret = res.EnsureSuccessStatusCode();
PushUpdate?.Invoke("final", $"{ret.StatusCode}:{ret.Content}");
}
}
catch (OperationCanceledException)
{
cts.Cancel(); await animTask;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(CancelledMsg); Console.ResetColor();
PushUpdate?.Invoke("final", CancelledMsg);
return CancelledMsg;
}
catch (Exception ex)
{
lastEx = ex;
if (retry < maxRetries - 1)
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine($"\n[网络抖动] {ex.Message},正在进行第 {retry + 1} 次重试...");
Console.ResetColor();
PushUpdate?.Invoke("tool_result", $"[网络抖动] 请求网关失败,准备第 {retry + 1} 次重试...");
await Task.Delay(2000, taskCts.Token);
}
}
}
if (!isSuccess)
{
cts.Cancel(); await animTask;
Console.ForegroundColor = ConsoleColor.Red;
var err = $"\n[网络错误] 请求 API 失败(已达最大重试次数 {maxRetries}): {lastEx?.Message}";
Console.WriteLine(err); Console.ResetColor();
PushUpdate?.Invoke("final", err);
return err;
}
var msg = JsonSerializer.Deserialize(responseString, AppJsonContext.Default.LlmResponse)?.Choices?.FirstOrDefault()?.Message;
if (msg != null)
{
if (msg.Content == "")
{
msg.Content = null;
}
if (msg.ReasoningContent == "")
{
msg.ReasoningContent = null;
}
msg.Timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
cts.Cancel();
await animTask;
if (msg == null) break;
SafeAddHistory(msg);
var toolCalls = msg.ToolCalls;
string thinkText = msg.ReasoningContent ?? msg.Content ?? "";
if (!string.IsNullOrWhiteSpace(thinkText) && toolCalls != null && toolCalls.Count > 0)
{
Console.ForegroundColor = ConsoleColor.DarkMagenta;
Console.WriteLine($"\n[思考过程] {thinkText}");
Console.ResetColor();
PushUpdate?.Invoke("thinking", thinkText); // 下发给前端
}
if (toolCalls != null && toolCalls.Count > 0)
{
foreach (var call in toolCalls)
{
var fnName = call.Function.Name;
var argsString = call.Function.Arguments;
JsonElement? tempArgs = null;
try { tempArgs = JsonDocument.Parse(argsString).RootElement; } catch { }
string GetStrProp(JsonElement? el, string key)
{
if (el.HasValue && el.Value.TryGetProperty(key, out var prop) && prop.ValueKind == JsonValueKind.String) return prop.GetString() ?? "";
return "";
}
bool GetBoolProp(JsonElement? el, string key)
{
if (el.HasValue && el.Value.TryGetProperty(key, out var prop) && (prop.ValueKind == JsonValueKind.True || prop.ValueKind == JsonValueKind.False)) return prop.GetBoolean();
return false;
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"\n[PiPiClaw 正在调用]: {fnName}");
Console.ResetColor();
string actionDesc = "";
Console.ForegroundColor = ConsoleColor.DarkCyan;
switch (fnName)
{
case "execute_command": actionDesc = $"执行: {GetStrProp(tempArgs, "command")} (is_background: {GetBoolProp(tempArgs, "is_background")})"; Console.WriteLine($"[Action] {actionDesc}"); break;
case "read_file": actionDesc = $"读取: {GetStrProp(tempArgs, "file_path")}"; Console.WriteLine($"[Action] {actionDesc}"); break;
case "write_file": actionDesc = $"写入: {GetStrProp(tempArgs, "file_path")}"; Console.WriteLine($"[Action] {actionDesc}"); break;
case "search_content": actionDesc = $"搜索: {GetStrProp(tempArgs, "keyword")}"; Console.WriteLine($"[Action] {actionDesc}"); break;
case "delegate_task": actionDesc = $"找同事: {GetStrProp(tempArgs, "user_name")}"; Console.WriteLine($"[Action] {actionDesc}"); break;
case "save_memory": actionDesc = $"写入记忆: {GetStrProp(tempArgs, "content")}"; Console.WriteLine($"[Action] {actionDesc}"); break;
case "recall_memory": actionDesc = $"检索记忆: {GetStrProp(tempArgs, "query")}"; Console.WriteLine($"[Action] {actionDesc}"); break;
default: actionDesc = $"调用参数: {argsString}"; break;
}
Console.ResetColor();
PushUpdate?.Invoke("tool", $"[调用工具] {fnName}\n{actionDesc}");
var result = "";
switch (fnName)
{
case "install_skill": result = await InstallSkill(GetStrProp(tempArgs, "slug"), username); break;
case "save_memory": result = await SaveMemoryAsync(username, GetStrProp(tempArgs, "content"), embeddingEndpoint, activeApiKey); break;
case "recall_memory": result = await RecallMemoryAsync(username, GetStrProp(tempArgs, "query"), embeddingEndpoint, activeApiKey); break;
case "finish_task":
requireReset = true;
result = "[系统提示] 上下文清理已预约,这将在你给出最后一句回复后执行。请现在用正常的自然语言向用户总结任务完成情况。";
try
{
// 直接删当前用户的历史记录文件,historyPath 已经是完整路径了
if (File.Exists(historyPath)) File.Delete(historyPath);
}
catch (Exception ex) { }
PushUpdate?.Invoke("clear_chat", "");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[内部状态] Agent 判定任务结束,已预约清理上下文...");
Console.ResetColor();
break;
case "add_scheduled_task":
{
int intervalMin = 0;
if (tempArgs.HasValue && tempArgs.Value.TryGetProperty("interval_minutes", out var intProp) && intProp.ValueKind == JsonValueKind.Number)
intervalMin = intProp.GetInt32();
// 👈 传入 username
result = AddScheduledTask(username, GetStrProp(tempArgs, "execute_at"), GetStrProp(tempArgs, "user_intent"), intervalMin);
break;
}
case "remove_scheduled_task":
result = RemoveScheduledTask(username, GetStrProp(tempArgs, "task_id"));
break;
case "self_update": result = await SelfUpdate(); break;
case "execute_command": result = await RunCmd(GetStrProp(tempArgs, "command"), PushUpdate, GetBoolProp(tempArgs, "is_background"), taskCts.Token); break;
case "delegate_task": result = await DelegateTaskAsync(username, GetStrProp(tempArgs, "user_name"), GetStrProp(tempArgs, "task_message")); break;
default:
result = fnName switch
{
"read_file" => ReadFile(GetStrProp(tempArgs, "file_path")),
"write_file" => WriteFile(GetStrProp(tempArgs, "file_path"), GetStrProp(tempArgs, "content"), GetStrProp(tempArgs, "old_content")),
"read_local_image" => ReadImg(GetStrProp(tempArgs, "file_path")),
"search_content" => SearchContent(GetStrProp(tempArgs, "directory"), GetStrProp(tempArgs, "keyword"), GetStrProp(tempArgs, "file_pattern")),
_ => "[未知工具] 系统不支持此工具。"
};
break;
}
if (fnName != "execute_command")
{
PushUpdate?.Invoke("tool_result", result);
}
var toolResultMsg = new ChatMessage
{
Role = "tool",
//Name = fnName,
Content = result,
ToolCallId = call.Id
};
SafeAddHistory(toolResultMsg);
}
}
else
{
finalAIResponse = msg.Content ?? "";
Console.ResetColor();
Console.WriteLine($"\n{finalAIResponse}");
Console.ResetColor();
PushUpdate?.Invoke("final", finalAIResponse);
isDone = true;
}
}
if (requireReset)
{
// 在清空前,抓取 AI 刚刚输出的最后一句有效内容(即最终工作报告)
var finalSummary = history.LastOrDefault(m => m.Role == "assistant" && !string.IsNullOrEmpty(m.Content));
history.Clear();
if (File.Exists(historyPath)) File.Delete(historyPath);
// 把这句报告重新塞入干净的记忆中并落盘,专门留给 Team 中控读取
if (finalSummary != null)
{
SafeAddHistory(userMsg);
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"\n✅ [生命周期] 用户 {username} 的任务上下文已全自动清理!(并保留了最终报告留底)");
Console.ResetColor();
}
if (selfUpdateRequested)
{
selfUpdateRequested = false;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[自动更新] 皮皮虾即将退出并由更新脚本完成替换重启,再见!");
Console.ResetColor();
await Task.Delay(1500);
Environment.Exit(0);
}
if (isScheduledEvent)
{
ShowPendingTasks();
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write("\n皮皮虾 > ");
Console.ResetColor();
}
}
finally
{
userLiveStream.TryRemove(username, out _);
userCts.TryRemove(username, out _);
userLock.Release();
}
return finalAIResponse;
}
// ========================== 记忆引擎与向量检索 ==========================
async Task<float[]?> GetEmbeddingAsync(string text, string endpoint, string apiKey)
{
try
{
var req = new EmbeddingRequest { Input = text };
var content = new StringContent(JsonSerializer.Serialize(req, AppJsonContext.Default.EmbeddingRequest), Encoding.UTF8, "application/json");
using var embedClient = new HttpClient();
embedClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
var res = await embedClient.PostAsync(endpoint, content);
if (!res.IsSuccessStatusCode) return null;
var resJson = await res.Content.ReadAsStringAsync();
var embedRes = JsonSerializer.Deserialize(resJson, AppJsonContext.Default.EmbeddingResponse);
return embedRes?.Data?.FirstOrDefault()?.Embedding;
}
catch { return null; }
}
float CosineSimilarity(float[] v1, float[] v2)
{
if (v1.Length != v2.Length) return 0;
float dot = 0, mag1 = 0, mag2 = 0;
for (int i = 0; i < v1.Length; i++)
{
dot += v1[i] * v2[i];
mag1 += v1[i] * v1[i];
mag2 += v2[i] * v2[i];
}
if (mag1 == 0 || mag2 == 0) return 0;
return dot / (float)(Math.Sqrt(mag1) * Math.Sqrt(mag2));
}
async Task<string> SaveMemoryAsync(string username, string content, string embedEndpoint, string apiKey)
{
if (string.IsNullOrWhiteSpace(content)) return "[记忆失败] 内容为空";
var vector = await GetEmbeddingAsync(content, embedEndpoint, apiKey);
if (vector == null) return "[记忆失败] 无法获取 Embedding 向量,请检查模型端点是否支持 /embeddings 接口。";
string memoryDir = Path.Combine(recordsDir, "memories");
if (!Directory.Exists(memoryDir)) Directory.CreateDirectory(memoryDir);
string memFile = Path.Combine(memoryDir, $"{username}_memories.json");
lock (memFile)
{
var memories = new List<MemoryItem>();
if (File.Exists(memFile))
{
try { memories = JsonSerializer.Deserialize(File.ReadAllText(memFile, Encoding.UTF8), AppJsonContext.Default.ListMemoryItem) ?? new(); } catch { }
}
memories.Add(new MemoryItem { Content = content, Vector = vector });
File.WriteAllText(memFile, JsonSerializer.Serialize(memories, AppJsonContext.Default.ListMemoryItem), Encoding.UTF8);
}
return $"[记忆已存储] 已将该事项转化为 {vector.Length} 维向量并存入你的长期记忆库。";
}
// 4. 提取记忆 (RAG 语义检索)
async Task<string> RecallMemoryAsync(string username, string query, string embedEndpoint, string apiKey)
{
if (string.IsNullOrWhiteSpace(query)) return "[检索失败] 查询关键字为空";
string memoryDir = Path.Combine(recordsDir, "memories");
string memFile = Path.Combine(memoryDir, $"{username}_memories.json");
if (!File.Exists(memFile)) return "[记忆库为空] 当前用户没有存储过任何长期记忆。";
var memories = new List<MemoryItem>();
lock (memFile)
{
try { memories = JsonSerializer.Deserialize(File.ReadAllText(memFile, Encoding.UTF8), AppJsonContext.Default.ListMemoryItem) ?? new(); } catch { }
}
if (memories.Count == 0) return "[记忆库为空] 当前用户没有存储过任何长期记忆。";
// 把用户的提问也转化为向量
var queryVector = await GetEmbeddingAsync(query, embedEndpoint, apiKey);
if (queryVector == null) return "[检索失败] 向量化查询词失败。";
// 遍历所有记忆,计算相似度
var results = memories
.Select(m => new { Memory = m, Score = CosineSimilarity(queryVector, m.Vector) })
.Where(x => x.Score > 0.4f) // 设置一个阈值,太低的不相关
.OrderByDescending(x => x.Score)
.Take(3) // 只提取最相关的 3 条记忆
.ToList();
if (results.Count == 0) return $"[未找到相关记忆] 关于“{query}”,记忆库中没有高度匹配的内容。";
var sb = new StringBuilder();
sb.AppendLine($"[成功检索到 {results.Count} 条高度相关的记忆]:");
foreach (var r in results)
{
sb.AppendLine($"- ({r.Memory.Timestamp}) {r.Memory.Content} (相似度: {r.Score:F2})");
}
return sb.ToString();
}
// ========================== 11. 定时调度器守护逻辑 ==========================
async Task ScheduleLoop()
{
while (true)
{
try
{
if (File.Exists(tasksPath))
{
var tasks = new List<TaskItem>();
lock (tasksPath)
{
try
{
var content = File.ReadAllText(tasksPath, Encoding.UTF8);
if (!string.IsNullOrWhiteSpace(content)) tasks = JsonSerializer.Deserialize(content, AppJsonContext.Default.ListTaskItem) ?? new();
}
catch { }
}
bool modified = false;
var pendingList = tasks.Where(t => t.Status == "pending").ToList();
foreach (var t in pendingList)
{
if (!DateTimeOffset.TryParse(t.ExecuteAt, out var execTime)) continue;
if (DateTimeOffset.Now < execTime) continue;
t.Status = "executing";
modified = true;
var intent = t.UserIntent;
var taskId = t.Id;
var taskUser = string.IsNullOrEmpty(t.Username) ? "local" : t.Username;
_ = Task.Run(async () =>
{
try
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine($"\n\n[🔔 皮皮虾唤醒] 正在接管系统执行预定需求: {intent} (归属: {taskUser})");
Console.ResetColor();
await RunAgent($"[系统级注入] 这是一个系统自动触发的定时任务。你之前设定了在此时执行该任务,用户的原始需求是:【{intent}】。请立刻处理,绝不要尝试手动重新添加定时任务,完成后调用 finish_task 结束。", true, 0, taskUser);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"\n[定时任务执行异常] {ex.Message}");
Console.ResetColor();
}
finally
{
lock (tasksPath)
{
try
{
var currentTasks = JsonSerializer.Deserialize(File.ReadAllText(tasksPath, Encoding.UTF8), AppJsonContext.Default.ListTaskItem) ?? new();
var taskToUpdate = currentTasks.FirstOrDefault(x => x.Id == taskId);
if (taskToUpdate != null)
{
int interval = taskToUpdate.IntervalMinutes;
if (interval > 0)
{
DateTimeOffset nextTime;
if (DateTimeOffset.TryParse(taskToUpdate.ExecuteAt, out var lastExecTime))
{
nextTime = lastExecTime.AddMinutes(interval);
while (nextTime <= DateTimeOffset.Now) nextTime = nextTime.AddMinutes(interval);
}
else nextTime = DateTimeOffset.Now.AddMinutes(interval);
taskToUpdate.ExecuteAt = nextTime.ToString("o");
taskToUpdate.Status = "pending";
}
else taskToUpdate.Status = "done";
File.WriteAllText(tasksPath, JsonSerializer.Serialize(currentTasks, AppJsonContext.Default.ListTaskItem), Encoding.UTF8);
}
}
catch { /* 忽略并发报错 */ }
}
}
});
}
if (modified)
{
lock (tasksPath) { File.WriteAllText(tasksPath, JsonSerializer.Serialize(tasks, AppJsonContext.Default.ListTaskItem), Encoding.UTF8); }
}
}
}
catch { /* 守护进程容错 */ }
await Task.Delay(1000);
}
}
// ========================== 12. 工具函数封装区域 ==========================
string GetInstalledSkillsContext(string username)
{
var skillsDir = Path.Combine(AppContext.BaseDirectory, "skills", username);
if (!Directory.Exists(skillsDir)) return "当前未安装任何专属技能";
var sb = new StringBuilder();
foreach (var dir in Directory.GetDirectories(skillsDir))
{
var slug = new DirectoryInfo(dir).Name;
var summaryPath = Path.Combine(dir, "summary.txt");
var absolutePath = Path.GetFullPath(dir).Replace("\\", "/");
sb.AppendLine($"- [{slug}] 绝对路径目录: {absolutePath}");
if (File.Exists(summaryPath))
{
try
{
sb.AppendLine($" 功能摘要: {File.ReadAllText(summaryPath, Encoding.UTF8).Trim()}");
sb.AppendLine($" (调用指引: 优先用 read_file 读取 {absolutePath}/experience.txt。若该经验文件不存在或无法解决问题,再去读 skill.md)");
sb.AppendLine($" (自我进化要求: 成功跑通该技能的某个具体方法或排坑后,【必须】先用 read_file 读取 {absolutePath}/experience.txt。在脑内将新经验按该“具体方法”合并去重,剔除冗余信息后,再用 write_file 结构化覆写回去。决不能不读文件就闭眼追加!)");
}
catch { }
}
else
{
sb.AppendLine($" 功能摘要: [未生成摘要]");
sb.AppendLine($" 说明:该技能已安装。请先 read_file 查看 {absolutePath}/skill.md,然后使用 write_file 在此目录下生成 summary.txt(一句话简介)。");
}
}
return sb.Length > 0 ? sb.ToString() : "当前未安装任何专属技能";
}
async Task Think(string username, CancellationToken ct)
{
// 【核心修复】:检测到输出被重定向(如 nohup 或写入文件)时,直接静默挂起,不再向日志狂刷字符
if (Console.IsOutputRedirected)
{
try { await Task.Delay(-1, ct); } catch { }
return;
}
Console.ForegroundColor = ConsoleColor.Cyan;
for (int i = 0; !ct.IsCancellationRequested; i++)
{
Console.Write($"\r {"-\\|/"[i % 4]} {username}皮皮虾正在思考中...");
try { await Task.Delay(100, ct); } catch { }
}
Console.Write("\r".PadRight(30) + "\r");
Console.ResetColor();
Console.CursorVisible = true;
}
void SaveData(List<ChatMessage> data, string path)
{
try { File.WriteAllText(path, JsonSerializer.Serialize(data, AppJsonContext.Default.ListChatMessage), Encoding.UTF8); } catch { }
}
string ReadPasswordHidden()
{
if (Console.IsInputRedirected || Console.IsOutputRedirected)
{
Console.WriteLine("[警告] 检测到非交互式终端,无法安全读取密码,请在 appsettings.json 中手动配置。");
return "";
}
var pwd = new StringBuilder();
while (true)
{
try
{
var i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter) break;
else if (i.Key == ConsoleKey.Backspace)
{
if (pwd.Length <= 0) continue;
pwd.Remove(pwd.Length - 1, 1); Console.Write("\b \b");
}
else if (i.KeyChar != '\u0000') { pwd.Append(i.KeyChar); Console.Write("*"); }
}
catch { break; } // 捕获 Linux 下可能抛出的异常
}
Console.WriteLine();
return pwd.ToString();
}
async Task<string> RunCmd(string? cmd, Action<string, string>? pushUpdate, bool isBackground = false, CancellationToken ct = default)
{
if (string.IsNullOrEmpty(cmd)) return "[执行失败] 命令为空";
var isWin = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);