Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
1680 lines (1509 loc) · 86 KB
/
Copy pathProgram.cs
File metadata and controls
1680 lines (1509 loc) · 86 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;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Nodes;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using static System.Int32;
// 设置当前目录为程序运行目录
Directory.SetCurrentDirectory(AppContext.BaseDirectory);
// 获取配置文件的函数
string GetConfig(string key, string def = "")
{
var envValue = Environment.GetEnvironmentVariable(key);
if (envValue != null) return envValue;
if (!File.Exists("appsettings.json")) return def;
try
{
var json = JsonNode.Parse(File.ReadAllText("appsettings.json"));
var jsonValue = json?[key]?.ToString();
if (jsonValue != null) return jsonValue;
}
catch { /* 忽略解析错误 */ }
return def;
}
// ========================== 1. 基础配置与初始化 ==========================
if (!File.Exists("appsettings.json"))
{
var defaultConfig = new JsonObject
{
["ApiKey"] = "your_api_key_here",
["Model"] = "qwen3.5-plus",
["Endpoint"] = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
["SudoPassword"] = "" // 新增:自动运维密码配置
};
var options = new JsonSerializerOptions { WriteIndented = true };
File.WriteAllText("appsettings.json", defaultConfig.ToJsonString(options), Encoding.UTF8);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("检测到首次运行,已自动生成默认的 appsettings.json 文件。");
Console.ResetColor();
}
// 注册字符编码提供程序以支持 GBK
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;
// ========================== 2. 初始化 Tools (大模型工具箱) ==========================
var tools = JsonNode.Parse("""
[
{ "type": "function", "function": { "name": "execute_command", "description": "执行终端命令", "parameters": { "type": "object", "properties": { "command": { "type": "string" } }, "required": ["command"] } } },
{ "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": "search_skill", "description": "当用户要求安装、查找或添加某个特定技能时执行此功能。根据关键词从 Skill-hub 搜索技能。注意:当用户说要“自我构建”或“编写”技能时,不要执行此功能。", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "用户想要搜索或安装的技能关键词,例如 'calendar', 'weather' 等" } }, "required": ["query"] } } },
{ "type": "function", "function": { "name": "install_skill", "description": "安装 单个 Skill-hub 或者 从第三方的技能,并根据包含的 MD 文件自动了解对接方式。", "parameters": { "type": "object", "properties": { "slug": { "type": "string", "description": "技能列表中的slug字段只需传入这个字段即可" } }, "required": ["slug"] } } }
]
""");
// ========================== 3. 读取并检查 ApiKey ==========================
var apiKey = GetConfig("ApiKey");
if (string.IsNullOrEmpty(apiKey) || apiKey.Contains("your"))
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("\n检测到未配置 ApiKey。请输入真实的 ApiKey (直接回车退出程序)");
Console.WriteLine("获取 ApiKey 地址:https://bailian.console.aliyun.com/cn-beijing?tab=model#/api-key");
Console.Write("ApiKey: ");
Console.ResetColor();
apiKey = Console.ReadLine()?.Trim();
if (string.IsNullOrEmpty(apiKey)) return;
try
{
var json = JsonNode.Parse(File.ReadAllText("appsettings.json"))!.AsObject();
json["ApiKey"] = apiKey;
var options = new JsonSerializerOptions { WriteIndented = true };
File.WriteAllText("appsettings.json", json.ToJsonString(options), Encoding.UTF8);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("✅ ApiKey 已自动保存到 appsettings.json,以后无需重复输入!\n");
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[保存失败] 无法写入配置文件: {ex.Message}");
Console.ResetColor();
return;
}
}
Console.Clear();
// ========================== Logo & 简介 ==========================
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine(@"
____ _ ____ _ ______ _
| _ \ (_)| _ \ (_)/ ____|| |
| |_) | _ | |_) | _ | | | | __ _ __ __
| __/ | || __/ | || | | | / _ |\ \ /\ / /
| | | || | | || |____ | | | (_| | \ V V /
|_| |_||_| |_| \______|____\__,_| \_/\_/
");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"皮皮虾已就绪。当前模型:[ {GetConfig("Model", "qwen3.5-plus")} ]");
Console.WriteLine("PiPiClaw | 跨平台自动化运维框架 (带持久化调度) \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 权限处理 ==========================
// 优先从 appsettings.json 读取已保存的密码
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 checkpointPath = "pi_history.json";
string tasksPath = "pi_scheduled_tasks.json";
JsonArray fullHistory = new JsonArray();
// 初始化定时任务文件
lock (tasksPath)
{
if (!File.Exists(tasksPath)) File.WriteAllText(tasksPath, "[]", Encoding.UTF8);
}
// 尝试恢复上次任务
if (File.Exists(checkpointPath))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("\n[PiPiClaw] 发现上次未完成的任务存档。是否继续执行上次的任务?(Y/N): ");
var key = Console.ReadKey().Key;
Console.WriteLine();
Console.ResetColor();
if (key == ConsoleKey.Y)
{
try
{
var savedState = JsonNode.Parse(File.ReadAllText(checkpointPath))?.AsArray();
if (savedState != null) fullHistory = savedState;
Console.WriteLine($"✅ 记忆已恢复!\n");
}
catch { File.Delete(checkpointPath); }
}
else
{
File.Delete(checkpointPath);
}
}
using var client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(10);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
// Agent 并发锁,防止定时任务和用户输入冲突
var agentLock = new SemaphoreSlim(1, 1);
// ========================== 6. 启动后台服务 (调度 + WebUI) ==========================
_ = Task.Run(ScheduleLoop);
_ = Task.Run(StartWebManager); // 轻量级 Web 服务器
// ========================== 7. 定时任务管理逻辑 ==========================
string AddScheduledTask(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 = JsonNode.Parse(File.ReadAllText(tasksPath, Encoding.UTF8))?.AsArray() ?? new JsonArray();
var newTask = new JsonObject
{
["id"] = Guid.NewGuid().ToString("N"),
["execute_at"] = execTime.ToString("o"),
["user_intent"] = intent ?? "未提供具体意图",
["status"] = "pending",
["interval_minutes"] = intervalMinutes
};
tasks.Add(newTask);
File.WriteAllText(tasksPath, tasks.ToJsonString(new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8);
}
Console.ForegroundColor = ConsoleColor.Green;
string loopStr = intervalMinutes > 0 ? $" [周期: 每 {intervalMinutes} 分钟执行]" : " [单次执行]";
Console.WriteLine($"[调度中心] 成功创建任务: {execTime:yyyy-MM-dd HH:mm:ss} -> {intent}{loopStr}");
Console.ResetColor();
return $"[定时任务已添加] PiPiClaw 已将任务持久化,将在 {execTime:yyyy-MM-dd HH:mm:ss} 触发执行。{loopStr} 用户的需求是:{intent}。系统会在底层调度,请不要再次重复调用添加任务。";
}
string RemoveScheduledTask(string? taskId)
{
if (string.IsNullOrEmpty(taskId)) return "[删除失败] 必须提供 task_id";
lock (tasksPath)
{
if (!File.Exists(tasksPath)) return "[删除失败] 任务文件不存在";
var tasks = JsonNode.Parse(File.ReadAllText(tasksPath, Encoding.UTF8))?.AsArray();
if (tasks == null) return "[删除失败] 无法解析任务列表";
var targetNode = tasks.FirstOrDefault(t => t?["id"]?.ToString() == taskId);
if (targetNode != null)
{
tasks.Remove(targetNode);
File.WriteAllText(tasksPath, tasks.ToJsonString(new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"\n[调度中心] 成功移除任务 (ID: {taskId})");
Console.ResetColor();
return $"[任务已删除] 成功移除了 ID 为 {taskId} 的任务。";
}
return $"[删除失败] 未在挂起队列中找到 ID 为 {taskId} 的任务。";
}
}
// ========================== 8. 挂起任务顶层展示区 ==========================
void ShowPendingTasks()
{
if (!File.Exists(tasksPath)) return;
try
{
JsonArray? tasks = null;
lock (tasksPath)
{
var tasksStr = File.ReadAllText(tasksPath, Encoding.UTF8);
if (!string.IsNullOrWhiteSpace(tasksStr))
{
tasks = JsonNode.Parse(tasksStr)?.AsArray();
}
}
if (tasks == null) return;
var pendingTasks = tasks.Where(t => t?["status"]?.ToString() == "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?["execute_at"]?.ToString(), out var execTime)) continue;
var intent = t?["user_intent"]?.ToString() ?? "未知";
var diff = execTime - DateTimeOffset.Now;
int intervalMinutes = 0;
if (t?["interval_minutes"] != null) TryParse(t["interval_minutes"]?.ToString(), out 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($" └─ 需求: {intent} (ID: {t?["id"]})");
}
Console.ResetColor();
}
}
catch { /* 忽略解析错误 */ }
}
// ========================== 9. 主交互死循环 ==========================
while (true)
{
ShowPendingTasks();
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write("\n皮皮虾 > ");
Console.ResetColor();
var input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) continue;
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase)) break;
await RunAgent(input);
}
return;
// ========================== 10. 核心 Agent 处理逻辑 ==========================
// 增加了 onUpdate 委托,用于实时将状态推送到前端流
async Task<string> RunAgent(string inputMessage, bool isScheduledEvent = false, Action<string, string>? onUpdate = null)
{
await agentLock.WaitAsync();
string finalAIResponse = "";
try
{
var useFullContext = false;
var requireReset = false;
var userMsg = new JsonObject { ["role"] = "user", ["content"] = inputMessage };
fullHistory.Add(userMsg.DeepClone());
SaveData(fullHistory, checkpointPath);
var isDone = false;
while (!isDone)
{
using var cts = new CancellationTokenSource();
var animTask = Think(cts.Token);
var currentTasksJson = "暂无定时任务";
if (File.Exists(tasksPath))
{
lock (tasksPath)
{
try { currentTasksJson = File.ReadAllText(tasksPath, Encoding.UTF8); } catch { }
}
}
var systemPromptText = $"""
你是一个高级运维自动化 Agent,代号 PiPiClaw (皮皮虾)。当前系统:{RuntimeInformation.OSDescription}。
{sudoInstruction}
【记忆管理架构】:
1. 为节省Token,你的短时记忆默认只保留最近几次的对话记录。
2. 当任务彻底完成时调用 finish_task 清理环境。
3. [技能调用策略] 下方列表包含了本地已安装的技能和简短摘要。当用户的需求需要用到某个技能时,你必须先调用 read_file 工具,读取该技能目录下的 skill.md 文件以获取完整的对接文档,然后再根据文档指导进行下一步操作。绝对不要凭空猜测调用方式!
【PiPiClaw 挂起的定时任务(包含 task_id,供你管理任务时参考)】:
{currentTasksJson}
【本地已安装的扩展技能及绝对路径说明】:
{GetInstalledSkillsContext()}
""";
JsonArray payloadMessages =
[
new JsonObject { ["role"] = "system", ["content"] = systemPromptText }
];
IEnumerable<JsonNode?> recentMessages;
if (useFullContext)
{
recentMessages = fullHistory;
}
else
{
var seenUser = 0;
var startIndex = 0;
for (var i = fullHistory.Count - 1; i >= 0; i--)
{
if (fullHistory[i]?["role"]?.ToString() != "user") continue;
seenUser++;
if (seenUser <= 3) continue;
startIndex = i + 1;
break;
}
recentMessages = fullHistory.Skip(startIndex);
}
foreach (var m in recentMessages) payloadMessages.Add(m!.DeepClone());
var payload = new JsonObject
{
["model"] = GetConfig("Model", "qwen3.5-plus"),
["messages"] = payloadMessages,
["tools"] = tools!.DeepClone(),
["enable_search"] = true
};
var apiKeyToUse = GetConfig("ApiKey");
var endpointToUse = GetConfig("Endpoint", "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKeyToUse);
var content = new StringContent(payload.ToJsonString(), Encoding.UTF8, "application/json");
HttpResponseMessage res;
try
{
res = await client.PostAsync(endpointToUse, content);
res.EnsureSuccessStatusCode();
}
catch(Exception ex)
{
cts.Cancel();
await animTask;
Console.ForegroundColor = ConsoleColor.Red;
var err = $"\n[网络错误] 请求 API 失败: {ex.Message}";
Console.WriteLine(err);
Console.ResetColor();
onUpdate?.Invoke("final", err);
return err;
}
var responseString = await res.Content.ReadAsStringAsync();
var msg = JsonNode.Parse(responseString)?["choices"]?[0]?["message"];
cts.Cancel();
await animTask;
if (msg == null) break;
fullHistory.Add(msg.DeepClone());
SaveData(fullHistory, checkpointPath);
var toolCalls = msg["tool_calls"]?.AsArray();
if (toolCalls != null && toolCalls.Count > 0)
{
foreach (var call in toolCalls)
{
var fnName = call["function"]?["name"]?.ToString() ?? "";
var argsString = call["function"]?["arguments"]?.ToString() ?? "{}";
JsonNode? tempArgs = null;
try { tempArgs = JsonNode.Parse(argsString); } catch { tempArgs = new JsonObject(); }
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"\n[PiPiClaw 正在调用]: {fnName}");
Console.ResetColor();
// 构建给前端看的精简动作描述
string actionDesc = "";
Console.ForegroundColor = ConsoleColor.DarkCyan;
switch (fnName)
{
case "execute_command":
actionDesc = $"执行命令: {tempArgs?["command"]}";
Console.WriteLine($"[Action] {actionDesc}");
break;
case "read_file":
actionDesc = $"正在读取文件: {tempArgs?["file_path"]}";
Console.WriteLine($"[Action] {actionDesc}");
break;
case "write_file":
actionDesc = $"正在写入文件: {tempArgs?["file_path"]}";
Console.WriteLine($"[Action] {actionDesc}");
break;
case "search_content":
actionDesc = $"全局搜索关键字: {tempArgs?["keyword"]}";
Console.WriteLine($"[Action] {actionDesc}");
break;
default:
actionDesc = $"调用参数: {argsString}";
break;
}
Console.ResetColor();
// 推送工具开始执行事件
onUpdate?.Invoke("tool", $"[调用工具] {fnName}\n{actionDesc}");
var result = "";
switch (fnName)
{
case "search_skill":
result = await SearchSkill(tempArgs?["query"]?.ToString());
break;
case "install_skill":
result = await InstallSkill(tempArgs?["slug"]?.ToString());
break;
case "finish_task":
requireReset = true;
result = "[系统提示] 上下文清理已预约,这将在你给出最后一句回复后执行。请现在用正常的自然语言向用户总结任务完成情况。";
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[内部状态] Agent 判定任务结束,已预约清理上下文...");
Console.ResetColor();
break;
case "add_scheduled_task":
{
var intervalMin = 0;
if (tempArgs?["interval_minutes"] != null)
{
TryParse(tempArgs["interval_minutes"]?.ToString(), out intervalMin);
}
result = AddScheduledTask(tempArgs?["execute_at"]?.ToString(), tempArgs?["user_intent"]?.ToString(), intervalMin);
break;
}
case "remove_scheduled_task":
result = RemoveScheduledTask(tempArgs?["task_id"]?.ToString());
break;
default:
result = fnName switch
{
"execute_command" => RunCmd(tempArgs?["command"]?.ToString()),
"read_file" => ReadFile(tempArgs?["file_path"]?.ToString()),
"write_file" => WriteFile(tempArgs?["file_path"]?.ToString(), tempArgs?["content"]?.ToString(), tempArgs?["old_content"]?.ToString()),
"read_local_image" => ReadImg(tempArgs?["file_path"]?.ToString()),
"search_content" => SearchContent(tempArgs?["directory"]?.ToString(), tempArgs?["keyword"]?.ToString(), tempArgs?["file_pattern"]?.ToString()),
_ => "[未知工具] 系统不支持此工具。"
};
break;
}
// 推送工具执行结果
onUpdate?.Invoke("tool_result", result);
var toolResultMsg = new JsonObject
{
["role"] = "tool",
["name"] = fnName,
["content"] = result,
["tool_call_id"] = call["id"]?.ToString()
};
fullHistory.Add(toolResultMsg.DeepClone());
SaveData(fullHistory, checkpointPath);
}
}
else
{
finalAIResponse = msg["content"]?.ToString() ?? "";
Console.ResetColor();
Console.WriteLine($"\n{finalAIResponse}");
Console.ResetColor();
onUpdate?.Invoke("final", finalAIResponse); // 推送最终回答
isDone = true;
}
}
if (requireReset)
{
fullHistory.Clear();
if (File.Exists(checkpointPath)) File.Delete(checkpointPath);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\n✅ [生命周期] 本次任务上下文已全自动清理!PiPiClaw 已就绪,随时接收新任务。");
Console.ResetColor();
}
if (isScheduledEvent)
{
ShowPendingTasks();
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write("\n皮皮虾 > ");
Console.ResetColor();
}
}
finally
{
agentLock.Release();
}
return finalAIResponse;
}
// ========================== 11. 定时调度器守护逻辑 ==========================
async Task ScheduleLoop()
{
while (true)
{
try
{
if (File.Exists(tasksPath))
{
JsonArray? tasks = null;
lock (tasksPath)
{
try
{
var content = File.ReadAllText(tasksPath, Encoding.UTF8);
if(!string.IsNullOrWhiteSpace(content)) tasks = JsonNode.Parse(content)?.AsArray();
} catch { }
}
bool modified = false;
if (tasks != null)
{
var pendingList = tasks.Where(t => t?["status"]?.ToString() == "pending").ToList();
foreach (var t in pendingList)
{
if (t == null || !DateTimeOffset.TryParse(t["execute_at"]?.ToString(), out var execTime)) continue;
if (DateTimeOffset.Now < execTime) continue;
t["status"] = "executing";
modified = true;
var intent = t["user_intent"]?.ToString() ?? "";
var taskId = t["id"]?.ToString() ?? "";
_ = Task.Run(async () =>
{
try
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine($"\n\n[🔔 皮皮虾唤醒] 正在接管系统执行预定需求: {intent}");
Console.ResetColor();
await RunAgent($"[系统级注入] 这是一个系统自动触发的定时任务。你之前设定了在此时执行该任务,用户的原始需求是:【{intent}】。请立刻处理,绝不要尝试手动重新添加定时任务,完成后调用 finish_task 结束。", true);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"\n[定时任务执行异常] {ex.Message}");
Console.ResetColor();
}
finally
{
lock (tasksPath)
{
try
{
var currentTasks = JsonNode.Parse(File.ReadAllText(tasksPath, Encoding.UTF8))?.AsArray();
var taskToUpdate = currentTasks?.FirstOrDefault(x => x?["id"]?.ToString() == taskId);
if (taskToUpdate != null)
{
int interval = 0;
if (taskToUpdate["interval_minutes"] != null)
{
TryParse(taskToUpdate["interval_minutes"]?.ToString(), out interval);
}
if (interval > 0)
{
DateTimeOffset nextTime;
if (DateTimeOffset.TryParse(taskToUpdate["execute_at"]?.ToString(), out var lastExecTime))
{
nextTime = lastExecTime.AddMinutes(interval);
while (nextTime <= DateTimeOffset.Now)
{
nextTime = nextTime.AddMinutes(interval);
}
}
else
{
nextTime = DateTimeOffset.Now.AddMinutes(interval);
}
taskToUpdate["execute_at"] = nextTime.ToString("o");
taskToUpdate["status"] = "pending";
}
else
{
taskToUpdate["status"] = "done";
}
File.WriteAllText(tasksPath, currentTasks?.ToJsonString(new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8);
}
}
catch { /* 忽略并发报错 */ }
}
}
});
}
if (modified)
{
lock (tasksPath)
{
File.WriteAllText(tasksPath, tasks.ToJsonString(new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8);
}
}
}
}
}
catch { /* 守护进程容错 */ }
await Task.Delay(1000);
}
}
// ========================== 12. 工具函数封装区域 ==========================
string GetInstalledSkillsContext()
{
var skillsDir = Path.Combine(AppContext.BaseDirectory, "skills");
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}/skill.md)");
} catch { }
}
else
{
sb.AppendLine($" 技能功能摘要: [未生成摘要]");
sb.AppendLine($" 说明:该技能已安装。请先 read_file 查看 {absolutePath}/skill.md,然后使用 write_file 在此目录下生成一个名为 summary.txt 的文件,里面只写一句话功能概括即可。");
}
}
return sb.Length > 0 ? sb.ToString() : "当前未安装任何技能";
}
async Task Think(CancellationToken ct)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.CursorVisible = false;
for (int i = 0; !ct.IsCancellationRequested; i++)
{
Console.Write($"\r {"-\\|/"[i % 4]} 皮皮虾正在思考中...");
try { await Task.Delay(100, ct); } catch { }
}
Console.Write("\r".PadRight(30) + "\r");
Console.ResetColor();
Console.CursorVisible = true;
}
void SaveData(JsonArray data, string path)
{
try { File.WriteAllText(path, data.ToJsonString(new JsonSerializerOptions { WriteIndented = true }), Encoding.UTF8); } catch { }
}
string ReadPasswordHidden()
{
var pwd = new StringBuilder();
while (true)
{
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("*"); }
}
Console.WriteLine();
return pwd.ToString();
}
string RunCmd(string? cmd)
{
if (string.IsNullOrEmpty(cmd)) return "[执行失败] 命令为空";
var isWin = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
var askPassPath = "";
// 如果发现是非 Windows 环境,且包含 sudo 命令,且尚未提供密码,则在此时按需拦截询问密码
if (!isWin && cmd.Contains("sudo ") && !cmd.Contains("-S") && string.IsNullOrEmpty(sudoPassword))
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write("\n[提权拦截] 当前任务需要 sudo 权限,请输入密码(回车确认,输入内容不可见): ");
Console.ResetColor();
sudoPassword = ReadPasswordHidden();
}
if (!string.IsNullOrEmpty(sudoPassword))
{
switch (isWin)
{
case false:
{
askPassPath = Path.Combine(Path.GetTempPath(), $"pi_askpass_{Guid.NewGuid():N}.sh");
var safePwd = sudoPassword.Replace("'", "'\\''");
File.WriteAllText(askPassPath, $"#!/bin/bash\necho '{safePwd}'\n");
using (var chmodProc = Process.Start(new ProcessStartInfo("chmod", $"+x {askPassPath}") { CreateNoWindow = true }))
{
chmodProc?.WaitForExit();
}
if (cmd.Contains("sudo ") && !cmd.Contains("-S"))
{
cmd = cmd.Replace("sudo ", $"echo '{safePwd}' | sudo -S ");
}
break;
}
case true when (cmd.Contains("sudo ") || cmd.Contains("runas ")):
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[底层拦截] 警告:Windows 环境下检测到类 sudo 提权命令。PiPiClaw 无法全自动提供密码。请确保以管理员身份运行本程序。");
Console.ResetColor();
break;
}
}
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine($"[执行中] {cmd}");
Console.ResetColor();
var consoleEncoding = isWin ? Encoding.GetEncoding("GBK") : new UTF8Encoding(false);
using var p = new Process();
p.StartInfo = new ProcessStartInfo(isWin ? "cmd.exe" : "/bin/bash", isWin ? $"/c {cmd}" : $"-c \"{cmd}\"")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
StandardOutputEncoding = consoleEncoding,
StandardErrorEncoding = consoleEncoding
};
if (!isWin && !string.IsNullOrEmpty(askPassPath)) p.StartInfo.EnvironmentVariables["SUDO_ASKPASS"] = askPassPath;
var outputBuilder = new StringBuilder();
var errorBuilder = new StringBuilder();
p.OutputDataReceived += (sender, e) =>
{
if (e.Data == null) return;
Console.WriteLine(e.Data); outputBuilder.AppendLine(e.Data);
};
p.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null) return;
Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(e.Data); Console.ResetColor(); errorBuilder.AppendLine(e.Data);
};
try
{
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();
}
catch (Exception ex) { return $"[执行异常] {ex.Message}"; }
finally { if (!string.IsNullOrEmpty(askPassPath) && File.Exists(askPassPath)) try { File.Delete(askPassPath); } catch { } }
var errLines = errorBuilder.ToString().Split(["\r\n", "\r", "\n"], StringSplitOptions.None);
var outLines = outputBuilder.ToString().Split(["\r\n", "\r", "\n"], StringSplitOptions.None);
var compressedErr = UniversalLogCompressor.CompressLogs(errLines);
var compressedOut = UniversalLogCompressor.CompressLogs(outLines);
var finalErr = string.Join("\n", compressedErr).Trim();
var finalOut = string.Join("\n", compressedOut).Trim();
return !string.IsNullOrWhiteSpace(finalErr)
? $"[标准错误/进度信息]\n{finalErr}\n[标准输出]\n{finalOut}"
: finalOut;
}
string ReadFile(string? path)
{
if (path == null || !File.Exists(path)) return "[文件不存在]";
try { return ReadTextSmart(path, out _); }
catch (Exception ex) { return $"[读取失败] {ex.Message}"; }
}
string WriteFile(string? path, string? content, string? oldContent = null)
{
if (path == null) return "[写入失败] 路径为空";
try
{
var dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
Encoding targetEncoding = new UTF8Encoding(false);
var currentText = File.Exists(path) ? ReadTextSmart(path, out targetEncoding) : "";
if (File.Exists(path) && !string.IsNullOrEmpty(oldContent))
{
var normalizedCurrent = currentText.Replace("\r\n", "\n");
var normalizedOld = oldContent.Replace("\r\n", "\n");
var normalizedNew = content?.Replace("\r\n", "\n") ?? "";
if (!normalizedCurrent.Contains(normalizedOld)) return "[修改失败] 未精准匹配到 old_content,请确认内容。如果你不确定,请先 read_file 查看完整内容。";
var finalContent = normalizedCurrent.Replace(normalizedOld, normalizedNew);
File.WriteAllText(path, finalContent.Replace("\n", Environment.NewLine), targetEncoding);
return $"[修改成功] 文件局部已更新:{path}";
}
File.WriteAllText(path, content ?? "", targetEncoding);
return $"[写入成功] 文件已全量保存:{path}";
}
catch (Exception ex) { return $"[写入/修改失败] {ex.Message}"; }
}
string ReadTextSmart(string path, out Encoding detectedEncoding)
{
var bytes = File.ReadAllBytes(path);
try
{
detectedEncoding = new UTF8Encoding(false, true);
return detectedEncoding.GetString(bytes);
}
catch
{
detectedEncoding = Encoding.GetEncoding("GBK");
return detectedEncoding.GetString(bytes);
}
}
string ReadImg(string? path)
{
if (string.IsNullOrEmpty(path) || !File.Exists(path)) return "[文件不存在]";
try
{
var b = File.ReadAllBytes(path);
var ext = Path.GetExtension(path).TrimStart('.').ToLower();
if (ext == "jpg") ext = "jpeg";
return b.Length > 2000000 ? "[图片过大] 请上传小于 2MB 的图片" : $"data:image/{ext};base64,{Convert.ToBase64String(b)}";
}
catch (Exception ex) { return $"[读取失败] {ex.Message}"; }
}
string SearchContent(string? dir, string? keyword, string? pattern)
{
dir = string.IsNullOrEmpty(dir) ? "." : dir; pattern = string.IsNullOrEmpty(pattern) ? "*.*" : pattern;
if (string.IsNullOrEmpty(keyword)) return "[搜索失败] 关键字为空";
if (!Directory.Exists(dir)) return "[搜索失败] 目录不存在";
try
{
var results = new StringBuilder(); var matchCount = 0;
foreach (var file in Directory.EnumerateFiles(dir, pattern, SearchOption.AllDirectories))
{
if (file.Contains($"{Path.DirectorySeparatorChar}.git") || file.Contains($"{Path.DirectorySeparatorChar}bin") || file.Contains($"{Path.DirectorySeparatorChar}obj")) continue;
try
{
if (ReadTextSmart(file, out _).Contains(keyword))
{
results.AppendLine($"- {file}"); matchCount++;
if (matchCount >= 20) { results.AppendLine("...[结果过多已截断,请提供更精确的关键字]..."); break; }
}
}
catch { }
}
return matchCount == 0 ? $"[未找到] 关键字 '{keyword}'" : $"[搜索成功] 匹配到以下文件:\n{results}";
}
catch (Exception ex) { return $"[异常] {ex.Message}"; }
}
// ========================== 13. 技能拓展功能 ==========================
async Task<string> SearchSkill(string? query)
{
if (string.IsNullOrEmpty(query)) return "❌ 搜索关键词不能为空";
var sb = new StringBuilder();
sb.AppendLine($"🚀 正在为您搜索技能: '{query}' ...");
using var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate };
using var searchClient = new HttpClient(handler);
searchClient.DefaultRequestHeaders.Add("User-Agent", "skills-store-cli/0.1");
searchClient.DefaultRequestHeaders.Host = "skillhub.ai";
try
{
string escapedQuery = Uri.EscapeDataString(query);
string url = $"http://lb-3zbg86f6-0gwe3n7q8t4sv2za.clb.gz-tencentclb.com/api/v1/search?q={escapedQuery}&limit=10";
var response = await searchClient.GetAsync(url);
if (!response.IsSuccessStatusCode) return $"❌ 搜索请求失败,状态码: {response.StatusCode}";
var jsonString = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(jsonString);
var root = doc.RootElement;
if (root.TryGetProperty("results", out var resultsProp) && resultsProp.ValueKind == JsonValueKind.Array)
{
int count = resultsProp.GetArrayLength();
if (count == 0) return $"⚠️ 未找到与 '{query}' 相关的技能,请尝试其他关键词。";
sb.AppendLine($"✅ 找到 {count} 个相关技能:\n");
foreach (var item in resultsProp.EnumerateArray())
{
string slug = item.TryGetProperty("slug", out var s) ? s.GetString() ?? "未知" : "未知";
string name = item.TryGetProperty("name", out var n) ? n.GetString() ?? "未知" : "未知";
string desc = item.TryGetProperty("description", out var d) ? d.GetString() ?? "无描述" :
(item.TryGetProperty("summary", out var sum) ? sum.GetString() ?? "无描述" : "无描述");
sb.AppendLine($"- 标识 (Slug): {slug}");
sb.AppendLine($" 名称 (Name): {name}");
sb.AppendLine($" 描述 (Desc): {desc}");
sb.AppendLine(" -------------------------");
}
sb.AppendLine("\n💡 请询问用户要安装以上哪一个技能,或者直接根据语境调用 install_skill 安装逻辑。");
}
else return "❌ 解析技能数据失败:返回的数据格式不包含 results 数组。";
}
catch (Exception ex) { return $"❌ 搜索过程发生异常: {ex.Message}"; }