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
4798 lines (4495 loc) · 232 KB
/
Copy pathProgram.cs
File metadata and controls
4798 lines (4495 loc) · 232 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.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
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": "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"] } } },
{ "type": "function", "function": { "name": "delegate_task", "description": "向通讯录中的其他友军指派任务。请务必传入关联的 task_id!,禁止向你自己指派任务。", "parameters": { "type": "object", "properties": { "user_name": { "type": "string" }, "task_message": { "type": "string" }, "task_id": { "type": "string", "description": "任务的8位ID" } }, "required": ["user_name", "task_message", "task_id"] } } }
]
""");
//在没有找到合适的 搜索 api 之前先注释
// { "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": "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
? "以cmd最高权限运行控制台程序。"
: "如果遇到提权(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 = "", string teamUrl = "", string sop = "", string taskId = "")
{
var userLock = userLocks.GetOrAdd(username, _ => new SemaphoreSlim(100, 100));
await userLock.WaitAsync();
if (!string.IsNullOrEmpty(taskId) && !string.IsNullOrEmpty(teamUrl))
{
_ = Task.Run(async () =>
{
try
{
var updatePayload = $"{{\"tasks\": [{{\"id\": \"{taskId}\", \"status\": \"doing\"}}]}}";
using var statusReq = new HttpRequestMessage(HttpMethod.Post, $"{teamUrl.TrimEnd('/')}/api/board");
statusReq.Content = new StringContent(updatePayload, Encoding.UTF8, "application/json");
await client.SendAsync(statusReq);
}
catch { }
});
}
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;
var error400Count = 0;
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 agentWorkspace = Path.Combine(AppContext.BaseDirectory, "workspaces", username);
if (!Directory.Exists(agentWorkspace)) Directory.CreateDirectory(agentWorkspace);
var absoluteWorkspace = Path.GetFullPath(agentWorkspace).Replace("\\", "/");
var callerStr = !string.IsNullOrEmpty(caller)
? $"\n【任务来源追溯】:当前任务由友军【{caller}】指派。当任务彻底做完准备交付时,请**直接用自然语言输出最终结果**,系统底层会全自动将你的话作为工作报告回传给【{caller}】!绝对不要用 delegate_task 跑去向【{caller}】做最终汇报。(注:若执行中途遇到困难,需要向【{caller}】请教确认需求,仍可使用 delegate_task 联系对方)。\n"
: "";
var companySopStr = !string.IsNullOrWhiteSpace(sop)
? $"\n【公司最高主旨与工作流流程说明】\n\t{sop}"
: "";
var nodeIdentityStr = !string.IsNullOrEmpty(username)
? $"你当前是【{username}】皮皮虾"
: "";
var contactsContext = "";
if (!string.IsNullOrEmpty(username) && GlobalConfig.PeerNodes != null &&
GlobalConfig.PeerNodes.TryGetValue(username, out var myInfo) &&
myInfo.Contacts != null && myInfo.Contacts.Count > 0)
{
var sbContacts = new StringBuilder();
sbContacts.AppendLine("【你的专属通讯录与友军能力清单 (可用 delegate_task 委派)】");
foreach (var cName in myInfo.Contacts)
{
if (!GlobalConfig.PeerNodes.TryGetValue(cName, out var cInfo)) continue;
sbContacts.Append($"- 姓名: {cName}, 岗位: {cInfo.Role}, 能力说明: {cInfo.Description}");
// 👇 动态扫描该队友名下已安装的技能包摘要
var peerSkillsDir = Path.Combine(AppContext.BaseDirectory, "skills", cName);
var skillSummaries = new List<string>();
if (Directory.Exists(peerSkillsDir))
{
foreach (var dir in Directory.GetDirectories(peerSkillsDir))
{
var slug = new DirectoryInfo(dir).Name;
var summaryPath = Path.Combine(dir, "summary.txt");
if (File.Exists(summaryPath))
{
try
{
var summaryText = File.ReadAllText(summaryPath, Encoding.UTF8).Trim();
skillSummaries.Add($"[{slug}: {summaryText}]");
}
catch { }
}
else
{
skillSummaries.Add($"[{slug}: 暂无描述]");
}
}
}
if (skillSummaries.Count > 0)
{
sbContacts.Append($", 已装载的底层工具包: {string.Join(", ", skillSummaries)}");
}
else
{
sbContacts.Append(", 已装载的底层工具包: 无特殊技能");
}
sbContacts.AppendLine(); // 换行收尾
}
sbContacts.AppendLine("(请根据上述队友的专长和【已装载的底层工具包】,自主决定是否需要使用 delegate_task 工具向他们分包任务、求助或交接工作结果!)");
contactsContext = sbContacts.ToString();
}
else
{
// 如果没有勾选联系人,保留原有的保底提示词
contactsContext = "【任务委派与沟通】\n用户(老板)可能会在需求中指定“你可以找谁配合”。如果你知道对方名字,请直接使用 delegate_task 工具呼叫对方。";
}
var customPrompt = "";
if (string.IsNullOrEmpty(nodeIdentityStr))
{
customPrompt = !string.IsNullOrWhiteSpace(GlobalConfig.SystemPrompt)
? GlobalConfig.SystemPrompt
: "";
}
var boardContext = "暂无进行中的项目看板信息";
if (!string.IsNullOrEmpty(teamUrl))
{
try
{
var boardJson = await client.GetStringAsync($"{teamUrl.TrimEnd('/')}/api/board", taskCts.Token);
// 👉 这里改为解析 ListProjectBoard
var projects = JsonSerializer.Deserialize(boardJson, AppJsonContext.Default.ListProjectBoard);
if (projects != null && projects.Count > 0)
{
var sb = new StringBuilder();
sb.AppendLine("【当前并行中的项目列表】");
foreach (var p in projects)
{
sb.AppendLine($"\n--- 项目: {p.ProjectName} ---");
if (p.Tasks != null)
{
foreach (var t in p.Tasks)
{
sb.AppendLine($"- [ID: {t.Id}] [{t.Status.ToUpper()}] {t.Title} (负责人: {t.Assignee})");
// 👇 加上这一段!把已完成任务的产出结果,共享给全员!
if (t.Status.Equals("done", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(t.Result))
{
sb.AppendLine($" └─ 交付结果: {t.Result}");
}
}
}
}
boardContext = sb.ToString();
}
}
catch { }
}
var systemPromptText = $"""
{customPrompt}
{companySopStr}
{callerStr}
【当前环境状态】
当前系统:{RuntimeInformation.OSDescription}。当前时间是 {DateTimeOffset.Now:yyyy-MM-ddTHH:mm:sszzz}。
{sudoInstruction}
【记忆管理架构】:
[技能调用与经验沉淀策略]
1. 检索:查阅下方已安装技能的摘要。
2. 实战:优先用 read_file 读取技能目录下的 experience.txt。
3. 沉淀:成功跑通某技能后,将新经验按该“具体方法”合并去重,并写回 experience.txt。
【身份认知】
{nodeIdentityStr}
{contactsContext}
【PiPiClaw 挂起的定时任务(包含 task_id,供参考)】:
{currentTasksJson}
【本地已安装的扩展技能及绝对路径说明】:
{GetInstalledSkillsContext(username)}
优先调用本地技能。
【身份认知与沙盒边界限制】
{nodeIdentityStr}
【你的物理边界与专属工作区】
你的专属安全工作区绝对路径是:{absoluteWorkspace}
1. 你的终端命令(execute_command)默认会直接在该目录下启动执行。
2. 你编写的所有代码、生成的数据、分析报告等,【必须且只能】保存在这个工作区内!
3. 严禁窥探、修改属于其他节点(同事)的 workspace 或 skills 目录!否则将被判定为越权违规操作!
【记忆与上下文折叠机制 (极其重要)】
1. 注意:你每次回复时,必须先使用 <Summary>摘要文本</Summary> 标签包裹 10 到 20 字的本轮执行摘要,然后再输出给用户的详细正文。
2. 若被折叠的上下文中提及了结果文件,优先调用 readfile 去读取。切勿重复执行已做过的命令。
""";
var payloadMessages = new List<ChatMessage> { new() { Role = "system", Content = systemPromptText } };
var clonedHistory = history.Select(m => m.DeepClone()).ToList();
int totalUserTurns = clonedHistory.Count(m => m.Role == "user");
int turnsToFold = totalUserTurns - 4;
if (turnsToFold > 0)
{
int currentTurn = 0;
var optimizedHistory = new List<ChatMessage>();
var turnBuffer = new List<ChatMessage>();
for (int i = 0; i < clonedHistory.Count; i++)
{
var mssage = clonedHistory[i];
if (mssage.Role == "user") currentTurn++;
if (currentTurn <= turnsToFold)
{
if (mssage.Role == "user")
{
optimizedHistory.Add(mssage);
turnBuffer.Clear();
}
else
{
turnBuffer.Add(mssage);
bool isTurnEnd = (i == clonedHistory.Count - 1) || (clonedHistory[i + 1].Role == "user");
if (isTurnEnd && turnBuffer.Count > 0)
{
string sumText = "未知历史回合";
var sumMsg = turnBuffer.LastOrDefault(m => m.Role == "assistant" && m.Content != null && m.Content.Contains("<Summary>"));
if (sumMsg != null)
{
string sTag = "<Summary>"; string eTag = "</Summary>";
int sIdx = sumMsg.Content.IndexOf(sTag, StringComparison.OrdinalIgnoreCase);
int eIdx = sumMsg.Content.IndexOf(eTag, StringComparison.OrdinalIgnoreCase);
if (sIdx >= 0 && eIdx > sIdx)
{
sumText = sumMsg.Content.Substring(sIdx + sTag.Length, eIdx - sIdx - sTag.Length).Trim();
}
}
var sb = new StringBuilder();
sb.AppendLine($"【摘要 Key】: {sumText}");
sb.AppendLine("【详细折叠上下文 Content】:");
foreach (var tb in turnBuffer)
{
if (tb.Role == "assistant")
{
if (tb.ToolCalls != null && tb.ToolCalls.Count > 0)
{
sb.AppendLine($"\n[AI 调用工具]: {string.Join(", ", tb.ToolCalls.Select(tc => tc.Function.Name))}");
sb.AppendLine($"[参数/思考]: {tb.ReasoningContent ?? tb.Content ?? "无"}");
}
else
{
sb.AppendLine($"\n[AI 回复结论]: {tb.Content}");
}
}
else if (tb.Role == "tool")
{
sb.AppendLine($"[工具执行结果]:\n{tb.Content}");
}
}
string detailDir = Path.Combine(recordsDir, "details", username);
Directory.CreateDirectory(detailDir);
string hash = Convert.ToHexString(System.Security.Cryptography.MD5.HashData(Encoding.UTF8.GetBytes(sumText + sb.Length))).Substring(0, 8);
string safeKey = string.Join("_", sumText.Split(Path.GetInvalidFileNameChars())).Replace(" ", "_");
if (safeKey.Length > 30) safeKey = safeKey.Substring(0, 30);
string fileName = $"fold_{safeKey}_{hash}.txt";
string filePath = Path.Combine(detailDir, "folds", fileName);
if (!Directory.Exists(Path.Combine(detailDir, "folds")))
Directory.CreateDirectory(Path.Combine(detailDir, "folds"));
if (!File.Exists(filePath))
{
File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8);
}
optimizedHistory.Add(new ChatMessage
{
Role = "assistant",
Content = $"[旧轮次已折叠]\n摘要内容: {sumText}\n(注: 次记录已放置 {filePath} 文件中。通过 readfile 读取这个摘要的详细记录。"
});
turnBuffer.Clear();
}
}
}
else
{
if (mssage.Role == "assistant") mssage.ReasoningContent = "已省略";
optimizedHistory.Add(mssage);
}
}
payloadMessages.AddRange(optimizedHistory);
}
else
{
// 如果还不到折叠阈值,不需要折叠,但照样清理 reasoning_content
foreach (var m in clonedHistory)
{
if (m.Role == "assistant") m.ReasoningContent = "已省略";
payloadMessages.Add(m);
}
}
// =================================================================================
var payload = new LlmRequest
{
Model = activeModel,
Messages = payloadMessages,
Tools = toolsDoc.RootElement,
EnableSearch = true
};
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("User-Agent", "pipiclaw");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", activeApiKey);
string responseString = "";
bool isSuccess = false;
Exception? lastEx = null;
int maxRetries = 30000; // 设置最大重试次数
for (int retry = 0; retry < maxRetries; retry++)
{
try
{
// 注意:每次重试需要重新生成 StringContent,避免流被重复读取导致报错
var options = new JsonSerializerOptions
{
// 【核心配置】放宽转义限制,让中文和常用符号原样输出
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
// 【AOT 必备】挂载你的 Source Generator 上下文
TypeInfoResolver = AppJsonContext.Default
};
var content = new StringContent(JsonSerializer.Serialize(payload, options), 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;
// 核心判断:拦截 400 错误
bool is400Error = (ex is HttpRequestException httpEx && httpEx.StatusCode == System.Net.HttpStatusCode.BadRequest)
|| ex.Message.Contains("400");
if (is400Error)
{
error400Count++;
if (error400Count >= 10)
{
break; // 满 10 次,立刻跳出这个 retry 循环,交给下面的逻辑去回滚
}
}
if (retry < maxRetries - 1)
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine($"\n[网络抖动/请求异常] {ex.Message},正在进行第 {retry + 1} 次重试...");
Console.ResetColor();
PushUpdate?.Invoke("tool_result", $"[请求异常] 请求网关失败,准备第 {retry + 1} 次重试...{ex.Message}");
await Task.Delay(2000, taskCts.Token);
}
}
}
if (error400Count >= 10)
{
cts.Cancel(); await animTask;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[系统拦截] 连续 10 次 400 错误!判定上一轮上下文已严重污染,正在砍掉历史记录回滚...");
Console.ResetColor();
PushUpdate?.Invoke("tool_result", "[系统操作] 上下文被API拒绝,已强行切除毒化记录,回到上一步重试...");
lock (history)
{
while (history.Count > 0 && history.Last().Role == "tool")
{
history.RemoveAt(history.Count - 1);
}
if (history.Count > 0 && history.Last().Role == "assistant")
{
history.RemoveAt(history.Count - 1);
}
SaveData(history, historyPath);
}
error400Count = 0;
continue;
}
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;
}
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 result = "";
try
{
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}");
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"), GetStrProp(tempArgs, "task_id"), teamUrl, sop); 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);
}
}
catch (Exception)
{
Console.WriteLine();
}
var toolResultMsg = new ChatMessage
{
Role = "tool",
//Name = fnName,
Content = result,
ToolCallId = call.Id
};
SafeAddHistory(toolResultMsg);
}
}
else
{
finalAIResponse = msg.Content ?? "";
string startTag = "<Summary>";
string endTag = "</Summary>";
int startIdx = finalAIResponse.IndexOf(startTag, StringComparison.OrdinalIgnoreCase);
int endIdx = finalAIResponse.IndexOf(endTag, StringComparison.OrdinalIgnoreCase);
if (startIdx >= 0 && endIdx > startIdx)
{
string summary = finalAIResponse.Substring(startIdx + startTag.Length, endIdx - startIdx - startTag.Length).Trim();
string detail = finalAIResponse.Remove(startIdx, endIdx + endTag.Length - startIdx).Trim();
string detailDir = Path.Combine(recordsDir, "details", username);
Directory.CreateDirectory(detailDir);
string detailFile = Path.Combine(detailDir, $"detail_{DateTime.Now:yyyyMMdd_HHmmss}_{Guid.NewGuid().ToString("N").Substring(0, 6)}.txt");
File.WriteAllText(detailFile, $"【用户原始需求】\n{inputMessage}\n\n【AI详细执行与回复过程】\n{finalAIResponse}", Encoding.UTF8);
finalAIResponse = string.IsNullOrWhiteSpace(detail) ? "已完成处理 (详细结果请查看日志)" : detail;
}
Console.ResetColor();
Console.WriteLine($"\n{finalAIResponse}");
Console.ResetColor();
PushUpdate?.Invoke("final", finalAIResponse);
isDone = true;
}
}
// 【新增:整个思维与执行链条全部跑完,自动向看板回传 done 状态与结果报告】
if (!string.IsNullOrEmpty(taskId) && !string.IsNullOrEmpty(teamUrl))
{
_ = Task.Run(async () =>
{
try
{
var updateObj = new ProjectBoard
{
Tasks = new List<ProjectTask> {
new ProjectTask {
Id = taskId,
Status = "done",
Result = finalAIResponse
}
}
};
var taskJson = JsonSerializer.Serialize(updateObj, AppJsonContext.Default.ProjectBoard);
using var req = new HttpRequestMessage(HttpMethod.Post, $"{teamUrl.TrimEnd('/')}/api/board");
req.Content = new StringContent(taskJson, Encoding.UTF8, "application/json");
var res = await client.SendAsync(req);
if (res.IsSuccessStatusCode)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"\n[系统联动] 任务 {taskId} 执行完毕,已全自动将状态同步为 done 并提交工作结果!");
Console.ResetColor();
}