跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

ResourcesRpc.cs

41 行 · 2.7 KB历史下载
1using System.Diagnostics;
2using System.Runtime.CompilerServices;
3using System.Runtime.InteropServices;
4using System.Text.Json.Nodes;
5
6namespace Cage.GuestClipboard;
7
8internal static class ResourcesRpc
9{
10 [ModuleInitializer]
11 internal static void Register() { if (GuestOperations.Names.Contains("resources")) GuestOperations.Register("resources", Run); }
12 internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available)
13 {
14 if (!available()) throw new InvalidDataException("requires_gui_login");
15 var input = await Protocol.Read(stream, 4096, token) ?? throw new EndOfStreamException();
16 if (input["action"]?.GetValue<string>() != "sample") throw new InvalidDataException("resource_operation_invalid");
17 if (!GetSystemTimes(out var idleBefore, out var kernelBefore, out var userBefore)) throw new InvalidDataException("resource_sample_failed");
18 await Task.Delay(150, token);
19 if (!available() || !GetSystemTimes(out var idle, out var kernel, out var user)) throw new InvalidDataException("requires_gui_login");
20 var state = new MemoryStatus { Length = (uint)Marshal.SizeOf<MemoryStatus>() };
21 if (!GlobalMemoryStatusEx(ref state) || state.AvailablePhysical > state.TotalPhysical) throw new InvalidDataException("resource_sample_failed");
22 var total = kernel + user - kernelBefore - userBefore;
23 var idleDelta = idle - idleBefore;
24 var cpu = total == 0 ? 0 : Math.Clamp(100.0 * (total - Math.Min(total, idleDelta)) / total, 0, 100);
25 var now = DateTimeOffset.UtcNow;
26 await Protocol.Write(stream, new()
27 {
28 ["version"] = 1, ["pid"] = Environment.ProcessId, ["cpus"] = Environment.ProcessorCount,
29 ["updated_at"] = now.ToString("O"), ["observed_at"] = now.ToString("O"), ["cpu_percent"] = cpu,
30 ["guest"] = new JsonObject { ["total_bytes"] = state.TotalPhysical, ["available_bytes"] = state.AvailablePhysical },
31 ["unavailable_observations"] = new JsonArray("oom_kills", "memory_stall_percent", "swap_total_bytes", "swap_free_bytes", "host_pressure")
32 }, token);
33 }
34 [StructLayout(LayoutKind.Sequential)] private struct MemoryStatus
35 {
36 internal uint Length, Load;
37 internal ulong TotalPhysical, AvailablePhysical, TotalPageFile, AvailablePageFile, TotalVirtual, AvailableVirtual, AvailableExtendedVirtual;
38 }
39 [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GlobalMemoryStatusEx(ref MemoryStatus status);
40 [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetSystemTimes(out ulong idle, out ulong kernel, out ulong user);
41}