跳到主要内容

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

浏览文件

claude-window-windows.ps1

160 行 · 8.6 KB历史下载
1#requires -Version 5.1
2<#
3.SYNOPSIS
4Save one PNG of the signed-in guest user's registered Claude Desktop window.
5.DESCRIPTION
6Run in 64-bit Windows PowerShell in an unlocked Hyper-V guest desktop session.
7Pass the VM ID obtained independently on the host. OutputPath must name a new
8.png directly inside this guest user's temporary directory. A failed capture
9does not publish a PNG.
10#>
11[CmdletBinding()]
12param([Guid]$ExpectedVMId = [Guid]::Empty, [string]$OutputPath)
13$ErrorActionPreference = 'Stop'
14. (Join-Path $PSScriptRoot 'claude-desktop-windows.ps1') -ExpectedVMId $ExpectedVMId
15
16$cageWindowSource = @'
17using System;
18using System.Collections.Generic;
19using System.Drawing;
20using System.Drawing.Imaging;
21using System.IO;
22using System.Runtime.InteropServices;
23using System.Text;
24using System.Threading.Tasks;
25
26public static class CageClaudeWindow {
27 [StructLayout(LayoutKind.Sequential)]
28 private struct Rect { public int left, top, right, bottom; }
29
30 [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr window);
31 [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr window);
32 [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr window, out Rect rect);
33 [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window, out uint process);
34 [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags);
35 [DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr window, int attr, out int value, int bytes);
36 [DllImport("user32.dll")] private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
37 [DllImport("user32.dll")] private static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access);
38 [DllImport("user32.dll")] private static extern bool CloseDesktop(IntPtr desktop);
39 [DllImport("user32.dll", CharSet=CharSet.Unicode)]
40 private static extern bool GetUserObjectInformation(IntPtr obj, int index, StringBuilder name, int size, out int needed);
41
42 public static bool IsDefaultInputDesktop() {
43 IntPtr desktop = OpenInputDesktop(0, false, 1); // DESKTOP_READOBJECTS
44 if (desktop == IntPtr.Zero) return false;
45 try {
46 var name = new StringBuilder(256);
47 int needed;
48 return GetUserObjectInformation(desktop, 2, name, name.Capacity * 2, out needed)
49 && String.Equals(name.ToString(), "Default", StringComparison.OrdinalIgnoreCase);
50 } finally { CloseDesktop(desktop); }
51 }
52
53 private static bool IsClaudeWindow(IntPtr window, uint pid) {
54 uint owner;
55 int cloaked;
56 return GetWindowThreadProcessId(window, out owner) != 0 && owner == pid
57 && IsWindowVisible(window) && !IsIconic(window)
58 && DwmGetWindowAttribute(window, 14, out cloaked, 4) == 0 && cloaked == 0;
59 }
60
61 public static string FrameProblem(int[] rgb) {
62 if (rgb.Length == 0) return "empty_frame";
63 int first = rgb[0];
64 bool black = true, varied = false;
65 foreach (int pixel in rgb) {
66 for (int shift = 0; shift <= 16; shift += 8) {
67 int value = (pixel >> shift) & 255;
68 if (value > 4) black = false;
69 if (Math.Abs(value - ((first >> shift) & 255)) > 4) varied = true;
70 }
71 }
72 return black ? "black_frame" : (varied ? null : "uniform_frame");
73 }
74
75 private static byte[] Capture(IntPtr window, uint pid) {
76 if (!IsClaudeWindow(window, pid)) throw new InvalidOperationException("no_visible_window");
77 IntPtr previousDpi = SetThreadDpiAwarenessContext(new IntPtr(-4)); // Per-monitor aware V2
78 try {
79 Rect bounds;
80 if (!GetClientRect(window, out bounds) || bounds.right <= 0 || bounds.bottom <= 0)
81 throw new InvalidOperationException("no_visible_window");
82 using (var bitmap = new Bitmap(bounds.right, bounds.bottom, PixelFormat.Format24bppRgb)) {
83 using (var graphics = Graphics.FromImage(bitmap)) {
84 graphics.Clear(Color.Black);
85 IntPtr dc = graphics.GetHdc();
86 try {
87 // PW_CLIENTONLY | PW_RENDERFULLCONTENT, also used by Chromium
88 // for its DirectComposition windows. Never read the desktop DC.
89 if (!PrintWindow(window, dc, 3)) throw new InvalidOperationException("window_render_failed");
90 } finally { graphics.ReleaseHdc(dc); }
91 }
92 if (!IsClaudeWindow(window, pid) || !IsDefaultInputDesktop())
93 throw new InvalidOperationException("window_or_desktop_changed_during_capture");
94 var samples = new List<int>();
95 for (int y = bitmap.Height / 20; y < bitmap.Height - bitmap.Height / 20; y += Math.Max(1, bitmap.Height / 128))
96 for (int x = bitmap.Width / 20; x < bitmap.Width - bitmap.Width / 20; x += Math.Max(1, bitmap.Width / 128))
97 samples.Add(bitmap.GetPixel(x, y).ToArgb());
98 var problem = FrameProblem(samples.ToArray());
99 if (problem != null) throw new InvalidOperationException(problem);
100 using (var png = new MemoryStream()) {
101 bitmap.Save(png, ImageFormat.Png);
102 return png.ToArray();
103 }
104 }
105 } finally { if (previousDpi != IntPtr.Zero) SetThreadDpiAwarenessContext(previousDpi); }
106 }
107
108 public static byte[] CaptureWithTimeout(IntPtr window, uint pid) {
109 // PrintWindow waits synchronously for the window owner. A late render
110 // has no filesystem side effects and cannot publish a stale PNG.
111 var task = Task.Run(() => Capture(window, pid));
112 if (Task.WaitAny(new Task[] { task }, 10000) < 0) throw new TimeoutException("window_render_timeout");
113 return task.GetAwaiter().GetResult();
114 }
115}
116'@
117
118function Get-ClaudeCapturePath([string]$path) {
119 if (!$path -or ![IO.Path]::IsPathRooted($path)) { throw 'Supply an absolute guest temporary .png path.' }
120 $full = [IO.Path]::GetFullPath($path)
121 $temp = [IO.Path]::GetTempPath().TrimEnd([IO.Path]::DirectorySeparatorChar)
122 if ([IO.Path]::GetDirectoryName($full) -ine $temp -or [IO.Path]::GetExtension($full) -ine '.png' -or
123 [IO.Path]::GetFileName($full).IndexOfAny([IO.Path]::GetInvalidFileNameChars()) -ge 0) {
124 throw 'OutputPath must be a PNG directly inside this guest user''s temporary directory.'
125 }
126 if (Test-Path -LiteralPath $full) { throw 'Select a new PNG path.' }
127 if ([Environment]::OSVersion.Platform -eq 'Win32NT' -and
128 [IO.DriveInfo]::new([IO.Path]::GetPathRoot($full)).DriveType -ne 'Fixed') {
129 throw 'Use the guest user''s local temporary drive.'
130 }
131 return $full
132}
133
134if ($MyInvocation.InvocationName -eq '.') { return }
135if ([Environment]::OSVersion.Platform -ne 'Win32NT' -or ![Environment]::Is64BitProcess -or $PSVersionTable.PSEdition -ne 'Desktop') {
136 throw 'Run this script in 64-bit Windows PowerShell 5.1 inside the guest.'
137}
138Assert-TargetGuest $ExpectedVMId
139$file = Get-ClaudeCapturePath $OutputPath
140$session = [Diagnostics.Process]::GetCurrentProcess().SessionId
141if ($session -eq 0 -or ![Environment]::UserInteractive -or
142 !(Get-Process -Name explorer -ErrorAction SilentlyContinue | Where-Object SessionId -eq $session)) {
143 throw 'requires_gui_login: Run in the signed-in guest user''s desktop session.'
144}
145if (!('CageClaudeWindow' -as [type])) { Add-Type -TypeDefinition $cageWindowSource -ReferencedAssemblies System.Drawing }
146if (![CageClaudeWindow]::IsDefaultInputDesktop()) { throw 'requires_gui_login: Unlock the guest desktop.' }
147$registered = Get-RegisteredClaude
148if (!$registered) { throw 'not_registered: Install the official x64 Claude MSIX for this guest user.' }
149$target = Get-Process -Name Claude -ErrorAction SilentlyContinue | Where-Object {
150 $_.SessionId -eq $session -and $_.MainWindowHandle -ne 0 -and $_.Path -eq $registered.Executable
151} | Select-Object -First 1
152if (!$target) { throw 'no_visible_window: Open Claude Desktop for this guest user.' }
153$png = [CageClaudeWindow]::CaptureWithTimeout($target.MainWindowHandle, $target.Id)
154$staged = Join-Path ([IO.Path]::GetDirectoryName($file)) ([IO.Path]::GetRandomFileName())
155$stream = [IO.File]::Open($staged, 'CreateNew', 'Write', 'None')
156try {
157 try { $stream.Write($png, 0, $png.Length) } finally { $stream.Dispose() }
158 [IO.File]::Move($staged, $file)
159} finally { [IO.File]::Delete($staged) }
160[pscustomobject]@{ Path = $file; Bytes = $png.Length; ProcessId = $target.Id; Version = $registered.Version } | ConvertTo-Json