跳到主要内容

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

浏览文件

TerminalRpc.cs

241 行 · 15.9 KB历史下载
1using System.ComponentModel;
2using System.Runtime.InteropServices;
3using System.Runtime.CompilerServices;
4using System.Text;
5using System.Text.Json.Nodes;
6using Microsoft.Win32.SafeHandles;
7
8namespace Cage.GuestClipboard;
9
10// The authenticated GUI relay owns this terminal. Commands and project paths are
11// never accepted from the wire; a future project grant must be resolved here.
12internal static class TerminalRpc
13{
14 internal sealed record Launch(string Executable, string[] Arguments, string Directory, Dictionary<string, string> Environment);
15 private static readonly SemaphoreSlim Slots = new(12, 12);
16 [ModuleInitializer]
17 internal static void Register() => GuestOperations.Register("terminal", Run);
18 internal static string PowerShellPath()
19 {
20 var pwsh=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"PowerShell","7","pwsh.exe");
21 return File.Exists(pwsh)?pwsh:Path.Combine(Environment.SystemDirectory,"WindowsPowerShell","v1.0","powershell.exe");
22 }
23 internal static Task Run(Stream stream, CancellationToken token, Func<bool> sessionAvailable) => RunCore(stream, token, sessionAvailable, null);
24 internal static Task RunWithLaunch(Stream stream, CancellationToken token, Func<bool> sessionAvailable, Launch launch) => RunCore(stream, token, sessionAvailable, launch);
25 private static async Task RunCore(Stream stream, CancellationToken token, Func<bool> sessionAvailable, Launch? launch)
26 {
27 if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login");
28 if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("terminal_limit");
29 using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(token);
30 using var writes = new SemaphoreSlim(1, 1);
31 NativeTerminal? terminal = null;
32 Task? output = null, inputs = null, guard = null;
33 Task<int>? exited = null;
34 Action<string, string>? revoked = null;
35 Action? projectAvailable = null;
36 async Task Send(JsonObject value)
37 {
38 await writes.WaitAsync(lifetime.Token);
39 try { await Protocol.Write(stream, value, lifetime.Token); } finally { writes.Release(); }
40 }
41 try
42 {
43 var open = await Protocol.Read(stream, 65536, lifetime.Token) ?? throw new EndOfStreamException();
44 if (open["action"]?.GetValue<string>() != "open" || open["shell"]?.GetValue<string>() != (launch is null ? "powershell" : "claude") || !sessionAvailable())
45 throw new InvalidDataException("terminal_request_invalid");
46 var directory = open["workspace"]?.GetValue<string>() switch
47 {
48 "home" => Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
49 "project" => ProjectRpc.Resolve(open["project_id"]?.GetValue<string>() ?? "", open["grant"]?.GetValue<string>() ?? ""),
50 _ => throw new InvalidDataException("terminal_request_invalid")
51 };
52 if (launch is not null && !Path.GetFullPath(launch.Directory).Equals(Path.GetFullPath(directory), StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("terminal_directory_invalid");
53 if (open["workspace"]?.GetValue<string>() == "project")
54 {
55 var id = open["project_id"]!.GetValue<string>(); var grant = open["grant"]!.GetValue<string>();
56 revoked = (removed, oldGrant) => { if (removed == id && oldGrant == grant) lifetime.Cancel(); };
57 ProjectRpc.Revoked += revoked;
58 projectAvailable = () => ProjectRpc.Resolve(id, grant);
59 projectAvailable();
60 }
61 terminal = new NativeTerminal(Size(open, "cols"), Size(open, "rows"), directory, launch);
62 await Send(new JsonObject { ["ready"] = true });
63 output = Task.Run(async () =>
64 {
65 var buffer = new byte[32 << 10]; int count;
66 // ConPTY shutdown needs a live drain even after the viewer stops.
67 while ((count = await terminal.Output.ReadAsync(buffer, CancellationToken.None)) != 0)
68 {
69 if (lifetime.IsCancellationRequested) continue;
70 try { await Send(new JsonObject { ["data"] = Convert.ToBase64String(buffer, 0, count) }); }
71 catch { lifetime.Cancel(); }
72 }
73 });
74 inputs = Task.Run(async () =>
75 {
76 while (await Protocol.Read(stream, 100 << 10, lifetime.Token) is { } value)
77 {
78 if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login");
79 lifetime.Token.ThrowIfCancellationRequested(); projectAvailable?.Invoke();
80 switch (value["action"]?.GetValue<string>())
81 {
82 case "input":
83 var bytes = Convert.FromBase64String(value["data"]?.GetValue<string>() ?? "");
84 if (bytes.Length > 64 << 10) throw new InvalidDataException("terminal_input_limit");
85 await terminal.Input.WriteAsync(bytes, lifetime.Token); await terminal.Input.FlushAsync(lifetime.Token); break;
86 case "resize": terminal.Resize(Size(value, "cols"), Size(value, "rows")); break;
87 case "close": return;
88 default: throw new InvalidDataException("terminal_request_invalid");
89 }
90 }
91 }, lifetime.Token);
92 guard = Task.Run(async () =>
93 {
94 while (!lifetime.IsCancellationRequested)
95 {
96 await Task.Delay(100, lifetime.Token);
97 if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login");
98 }
99 }, lifetime.Token);
100 exited = Task.Run(terminal.Wait);
101 var first = await Task.WhenAny(inputs, exited, guard, output);
102 if (first == exited || first == output)
103 {
104 if (first == output) { await output; terminal.KillOwnJob(); }
105 var code = await exited;
106 terminal.KillOwnJob();
107 terminal.CloseConsole();
108 await output;
109 await Send(new JsonObject { ["exit"] = code });
110 }
111 else await first;
112 }
113 finally
114 {
115 lifetime.Cancel(); terminal?.Stop();
116 if (revoked is not null) ProjectRpc.Revoked -= revoked;
117 foreach (var task in new Task?[] { inputs, output, guard, exited })
118 if (task is not null) try { await task; } catch { /* teardown observes every worker */ }
119 terminal?.Dispose(); Slots.Release();
120 }
121 }
122 private static short Size(JsonObject value, string name)
123 {
124 var size = value[name]?.GetValue<int>() ?? 0;
125 var maximum = name == "cols" ? 599 : 500;
126 if (size < 1 || size > maximum) throw new InvalidDataException("terminal_size_invalid");
127 return (short)size;
128 }
129
130 private sealed class NativeTerminal : IDisposable
131 {
132 internal FileStream Input { get; }
133 internal FileStream Output { get; }
134 private nint console, process, job;
135 private readonly object gate = new();
136 private int disposed;
137 internal NativeTerminal(short cols, short rows, string directory, Launch? launch)
138 {
139 SafeFileHandle? inputRead = null, inputWrite = null, outputRead = null, outputWrite = null;
140 nint attributes = 0, environment = 0;
141 try
142 {
143 Check(CreatePipe(out inputRead, out inputWrite, 0, 0));
144 Check(CreatePipe(out outputRead, out outputWrite, 0, 0));
145 Marshal.ThrowExceptionForHR(CreatePseudoConsole(new Coord(cols, rows), inputRead, outputWrite, 0, out console));
146 nuint bytes = 0; InitializeProcThreadAttributeList(0, 1, 0, ref bytes);
147 attributes = Marshal.AllocHGlobal((nint)bytes);
148 Check(InitializeProcThreadAttributeList(attributes, 1, 0, ref bytes));
149 Check(UpdateProcThreadAttribute(attributes, 0, 0x00020016, console, (nuint)IntPtr.Size, 0, 0));
150 var startup = new StartupInfoEx(); startup.Startup.cb = Marshal.SizeOf<StartupInfoEx>();
151 startup.Startup.flags = 0x100; startup.Attributes = attributes;
152 var shell = PowerShellPath();
153 var arguments = new[] { "-NoLogo" };
154 if (launch is not null)
155 {
156 shell = launch.Executable; arguments = launch.Arguments;
157 environment = Marshal.StringToHGlobalUni(string.Join('\0', launch.Environment.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase).Select(x => x.Key + "=" + x.Value)) + "\0\0");
158 }
159 if (!File.Exists(shell)) throw new InvalidDataException("terminal_shell_missing");
160 job = CreateJobObject(0, null); Check(job != 0);
161 var limits = new JobLimits(); limits.Basic.flags = 0x2000; // KILL_ON_JOB_CLOSE
162 Check(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf<JobLimits>()));
163 Check(CreateProcess(shell, new StringBuilder(string.Join(' ', new[] { shell }.Concat(arguments).Select(QuoteArgument))), 0, 0, false,
164 0x00080000 | 0x00000400 | 0x00000004, environment, directory, ref startup, out var created));
165 process = created.Process;
166 try
167 {
168 Check(AssignProcessToJobObject(job, process));
169 if (ResumeThread(created.Thread) == uint.MaxValue) throw new Win32Exception();
170 }
171 catch { TerminateProcess(process, 1); throw; }
172 finally { CloseHandle(created.Thread); }
173 Input = new FileStream(inputWrite, FileAccess.Write, 65536, false); inputWrite = null;
174 Output = new FileStream(outputRead, FileAccess.Read, 65536, false); outputRead = null;
175 }
176 catch { Dispose(); throw; }
177 finally
178 {
179 inputRead?.Dispose(); inputWrite?.Dispose(); outputRead?.Dispose(); outputWrite?.Dispose();
180 if (attributes != 0) { DeleteProcThreadAttributeList(attributes); Marshal.FreeHGlobal(attributes); }
181 if (environment != 0) Marshal.FreeHGlobal(environment);
182 }
183 }
184 internal void Resize(short cols, short rows) { lock (gate) { if (console == 0) throw new ObjectDisposedException(nameof(NativeTerminal)); Marshal.ThrowExceptionForHR(ResizePseudoConsole(console, new Coord(cols, rows))); } }
185 internal int Wait()
186 {
187 var handle = process;
188 if (handle == 0 || WaitForSingleObject(handle, uint.MaxValue) != 0 || !GetExitCodeProcess(handle, out var code)) throw new Win32Exception();
189 return unchecked((int)code);
190 }
191 internal void CloseConsole() { lock (gate) { if (console != 0) { ClosePseudoConsole(console); console = 0; } } }
192 internal void KillOwnJob() { lock (gate) { if (job != 0) { CloseHandle(job); job = 0; } } }
193 internal void Stop()
194 {
195 if (Interlocked.Exchange(ref disposed, 1) != 0) return;
196 KillOwnJob();
197 Input?.Dispose();
198 // Keep output readable until ConPTY flushes; the active output pump drains it.
199 CloseConsole(); Output?.Dispose();
200 }
201 public void Dispose()
202 {
203 Stop();
204 if (process != 0) { CloseHandle(process); process = 0; }
205 }
206 private static void Check(bool value) { if (!value) throw new Win32Exception(Marshal.GetLastWin32Error()); }
207 }
208 internal static string QuoteArgument(string value)
209 {
210 var result = new StringBuilder("\""); int slashes = 0;
211 foreach (var c in value)
212 {
213 if (c == '\\') { slashes++; continue; }
214 result.Append('\\', c == '"' ? slashes * 2 + 1 : slashes); result.Append(c); slashes = 0;
215 }
216 return result.Append('\\', slashes * 2).Append('"').ToString();
217 }
218 [StructLayout(LayoutKind.Sequential)] private readonly struct Coord(short x, short y) { internal readonly short X = x, Y = y; }
219 [StructLayout(LayoutKind.Sequential)] private struct StartupInfo { internal int cb; internal nint reserved, desktop, title; internal int x,y,xSize,ySize,xChars,yChars,fill,flags; internal short show,reserved2Size; internal nint reserved2,input,output,error; }
220 [StructLayout(LayoutKind.Sequential)] private struct StartupInfoEx { internal StartupInfo Startup; internal nint Attributes; }
221 [StructLayout(LayoutKind.Sequential)] private struct ProcessInfo { internal nint Process, Thread; internal uint ProcessId, ThreadId; }
222 [StructLayout(LayoutKind.Sequential)] private struct BasicLimits { internal long processTime,jobTime; internal uint flags; internal nuint minWorkingSet,maxWorkingSet; internal uint activeProcessLimit; internal nuint affinity; internal uint priority,scheduling; }
223 [StructLayout(LayoutKind.Sequential)] private struct IoCounters { internal ulong readOperations,writeOperations,otherOperations,readBytes,writeBytes,otherBytes; }
224 [StructLayout(LayoutKind.Sequential)] private struct JobLimits { internal BasicLimits Basic; internal IoCounters Io; internal nuint processMemory,jobMemory,peakProcessMemory,peakJobMemory; }
225 [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool CreatePipe(out SafeFileHandle read,out SafeFileHandle write,nint attributes,uint size);
226 [DllImport("kernel32.dll")] private static extern int CreatePseudoConsole(Coord size,SafeFileHandle input,SafeFileHandle output,uint flags,out nint console);
227 [DllImport("kernel32.dll")] private static extern int ResizePseudoConsole(nint console,Coord size);
228 [DllImport("kernel32.dll")] private static extern void ClosePseudoConsole(nint console);
229 [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool InitializeProcThreadAttributeList(nint list,int count,uint flags,ref nuint size);
230 [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool UpdateProcThreadAttribute(nint list,uint flags,nuint attribute,nint value,nuint size,nint previous,nint returned);
231 [DllImport("kernel32.dll")] private static extern void DeleteProcThreadAttributeList(nint list);
232 [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool CreateProcess(string app,StringBuilder command,nint processAttributes,nint threadAttributes,bool inherit,uint flags,nint environment,string directory,ref StartupInfoEx startup,out ProcessInfo process);
233 [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] private static extern nint CreateJobObject(nint attributes,string? name);
234 [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool SetInformationJobObject(nint job,int kind,ref JobLimits limits,uint size);
235 [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool AssignProcessToJobObject(nint job,nint process);
236 [DllImport("kernel32.dll",SetLastError=true)] private static extern uint ResumeThread(nint thread);
237 [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool TerminateProcess(nint process,uint code);
238 [DllImport("kernel32.dll",SetLastError=true)] private static extern uint WaitForSingleObject(nint handle,uint milliseconds);
239 [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool GetExitCodeProcess(nint process,out uint code);
240 [DllImport("kernel32.dll")] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(nint handle);
241}