@harness-reins/linux-x64 0.0.0-stage → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/reins/_internal/base_library.zip +0 -0
  2. package/dist/reins/_internal/harness_reins/_build.txt +1 -0
  3. package/dist/reins/_internal/harness_reins/assets/skills/claude/SKILL.md +144 -0
  4. package/dist/reins/_internal/harness_reins/assets/skills/codex/SKILL.md +88 -0
  5. package/dist/reins/_internal/harness_reins/assets/skills/pi/SKILL.md +98 -0
  6. package/dist/reins/_internal/harness_reins/assets/skills/reference/SKILL.md +812 -0
  7. package/dist/reins/_internal/harness_reins/assets/skills/reference/agents/openai.yaml +4 -0
  8. package/dist/reins/_internal/harness_reins/harness/codex/desktop/windows_assets/desktop-package-launch.py +263 -0
  9. package/dist/reins/_internal/harness_reins/harness/codex/desktop/windows_assets/invoke-desktop-package.ps1 +14 -0
  10. package/dist/reins/_internal/harness_reins/harness/codex/desktop/windows_assets/probe-desktop-launch.py +217 -0
  11. package/dist/reins/_internal/harness_reins/harness/codex/desktop/windows_assets/start-desktop-bridge.ps1 +449 -0
  12. package/dist/reins/_internal/harness_reins/harness/pi/extension/reins-callback.js +272 -0
  13. package/dist/reins/_internal/harness_reins/owners/windows_scheduler.ps1 +156 -0
  14. package/dist/reins/_internal/harness_reins/templates/test.md +38 -0
  15. package/dist/reins/_internal/harness_reins-0.9.2.dist-info/INSTALLER +1 -0
  16. package/dist/reins/_internal/harness_reins-0.9.2.dist-info/METADATA +18 -0
  17. package/dist/reins/_internal/harness_reins-0.9.2.dist-info/RECORD +199 -0
  18. package/dist/reins/_internal/harness_reins-0.9.2.dist-info/REQUESTED +0 -0
  19. package/dist/reins/_internal/harness_reins-0.9.2.dist-info/WHEEL +5 -0
  20. package/dist/reins/_internal/harness_reins-0.9.2.dist-info/direct_url.json +1 -0
  21. package/dist/reins/_internal/harness_reins-0.9.2.dist-info/entry_points.txt +3 -0
  22. package/dist/reins/_internal/harness_reins-0.9.2.dist-info/top_level.txt +1 -0
  23. package/dist/reins/_internal/lib-dynload/_bisect.cpython-312-x86_64-linux-gnu.so +0 -0
  24. package/dist/reins/_internal/lib-dynload/_blake2.cpython-312-x86_64-linux-gnu.so +0 -0
  25. package/dist/reins/_internal/lib-dynload/_bz2.cpython-312-x86_64-linux-gnu.so +0 -0
  26. package/dist/reins/_internal/lib-dynload/_codecs_cn.cpython-312-x86_64-linux-gnu.so +0 -0
  27. package/dist/reins/_internal/lib-dynload/_codecs_hk.cpython-312-x86_64-linux-gnu.so +0 -0
  28. package/dist/reins/_internal/lib-dynload/_codecs_iso2022.cpython-312-x86_64-linux-gnu.so +0 -0
  29. package/dist/reins/_internal/lib-dynload/_codecs_jp.cpython-312-x86_64-linux-gnu.so +0 -0
  30. package/dist/reins/_internal/lib-dynload/_codecs_kr.cpython-312-x86_64-linux-gnu.so +0 -0
  31. package/dist/reins/_internal/lib-dynload/_codecs_tw.cpython-312-x86_64-linux-gnu.so +0 -0
  32. package/dist/reins/_internal/lib-dynload/_contextvars.cpython-312-x86_64-linux-gnu.so +0 -0
  33. package/dist/reins/_internal/lib-dynload/_csv.cpython-312-x86_64-linux-gnu.so +0 -0
  34. package/dist/reins/_internal/lib-dynload/_ctypes.cpython-312-x86_64-linux-gnu.so +0 -0
  35. package/dist/reins/_internal/lib-dynload/_datetime.cpython-312-x86_64-linux-gnu.so +0 -0
  36. package/dist/reins/_internal/lib-dynload/_decimal.cpython-312-x86_64-linux-gnu.so +0 -0
  37. package/dist/reins/_internal/lib-dynload/_hashlib.cpython-312-x86_64-linux-gnu.so +0 -0
  38. package/dist/reins/_internal/lib-dynload/_heapq.cpython-312-x86_64-linux-gnu.so +0 -0
  39. package/dist/reins/_internal/lib-dynload/_json.cpython-312-x86_64-linux-gnu.so +0 -0
  40. package/dist/reins/_internal/lib-dynload/_lzma.cpython-312-x86_64-linux-gnu.so +0 -0
  41. package/dist/reins/_internal/lib-dynload/_md5.cpython-312-x86_64-linux-gnu.so +0 -0
  42. package/dist/reins/_internal/lib-dynload/_multibytecodec.cpython-312-x86_64-linux-gnu.so +0 -0
  43. package/dist/reins/_internal/lib-dynload/_opcode.cpython-312-x86_64-linux-gnu.so +0 -0
  44. package/dist/reins/_internal/lib-dynload/_pickle.cpython-312-x86_64-linux-gnu.so +0 -0
  45. package/dist/reins/_internal/lib-dynload/_posixsubprocess.cpython-312-x86_64-linux-gnu.so +0 -0
  46. package/dist/reins/_internal/lib-dynload/_random.cpython-312-x86_64-linux-gnu.so +0 -0
  47. package/dist/reins/_internal/lib-dynload/_sha1.cpython-312-x86_64-linux-gnu.so +0 -0
  48. package/dist/reins/_internal/lib-dynload/_sha2.cpython-312-x86_64-linux-gnu.so +0 -0
  49. package/dist/reins/_internal/lib-dynload/_sha3.cpython-312-x86_64-linux-gnu.so +0 -0
  50. package/dist/reins/_internal/lib-dynload/_socket.cpython-312-x86_64-linux-gnu.so +0 -0
  51. package/dist/reins/_internal/lib-dynload/_ssl.cpython-312-x86_64-linux-gnu.so +0 -0
  52. package/dist/reins/_internal/lib-dynload/_statistics.cpython-312-x86_64-linux-gnu.so +0 -0
  53. package/dist/reins/_internal/lib-dynload/_struct.cpython-312-x86_64-linux-gnu.so +0 -0
  54. package/dist/reins/_internal/lib-dynload/_uuid.cpython-312-x86_64-linux-gnu.so +0 -0
  55. package/dist/reins/_internal/lib-dynload/array.cpython-312-x86_64-linux-gnu.so +0 -0
  56. package/dist/reins/_internal/lib-dynload/binascii.cpython-312-x86_64-linux-gnu.so +0 -0
  57. package/dist/reins/_internal/lib-dynload/fcntl.cpython-312-x86_64-linux-gnu.so +0 -0
  58. package/dist/reins/_internal/lib-dynload/grp.cpython-312-x86_64-linux-gnu.so +0 -0
  59. package/dist/reins/_internal/lib-dynload/math.cpython-312-x86_64-linux-gnu.so +0 -0
  60. package/dist/reins/_internal/lib-dynload/pyexpat.cpython-312-x86_64-linux-gnu.so +0 -0
  61. package/dist/reins/_internal/lib-dynload/resource.cpython-312-x86_64-linux-gnu.so +0 -0
  62. package/dist/reins/_internal/lib-dynload/select.cpython-312-x86_64-linux-gnu.so +0 -0
  63. package/dist/reins/_internal/lib-dynload/termios.cpython-312-x86_64-linux-gnu.so +0 -0
  64. package/dist/reins/_internal/lib-dynload/unicodedata.cpython-312-x86_64-linux-gnu.so +0 -0
  65. package/dist/reins/_internal/lib-dynload/zlib.cpython-312-x86_64-linux-gnu.so +0 -0
  66. package/dist/reins/_internal/libbz2.so.1.0 +0 -0
  67. package/dist/reins/_internal/libcrypto.so.1.1 +0 -0
  68. package/dist/reins/_internal/libffi.so.7 +0 -0
  69. package/dist/reins/_internal/liblzma.so.5 +0 -0
  70. package/dist/reins/_internal/libpython3.12.so.1.0 +0 -0
  71. package/dist/reins/_internal/libssl.so.1.1 +0 -0
  72. package/dist/reins/_internal/libuuid.so.1 +0 -0
  73. package/dist/reins/_internal/libz.so.1 +0 -0
  74. package/dist/reins/_internal/yaml/_yaml.cpython-312-x86_64-linux-gnu.so +0 -0
  75. package/dist/reins/reins +0 -0
  76. package/package.json +14 -4
  77. package/README.md +0 -3
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "Harness Reins"
3
+ short_description: "Durable child agents, registered templates, callbacks"
4
+ default_prompt: "Use $harness-reins to delegate this task to a fresh child agent or arrange its completion callback."
@@ -0,0 +1,263 @@
1
+ """Experimental Desktop launcher for an explicitly supplied MSIX package context.
2
+
3
+ Invoke this helper with Windows' Invoke-CommandInDesktopPackage. That command
4
+ uses a debugging token, so success does not establish normal activation parity.
5
+ Only --request is accepted; environment overrides are never put on the command
6
+ line or written to the result. Check mode never runs the Desktop main thread.
7
+ """
8
+
9
+ import argparse
10
+ import ctypes
11
+ from ctypes import wintypes
12
+ import importlib.util
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+ import subprocess
17
+ import sys
18
+
19
+
20
+ ENVIRONMENT_KEYS = frozenset({
21
+ "CODEX_HOME",
22
+ "CODEX_CLI_PATH",
23
+ "CODEX_APP_SERVER_FORCE_CLI",
24
+ "CODEX_APP_SERVER_WS_URL",
25
+ "REINS_DESKTOP_REAL_CODEX",
26
+ "REINS_DESKTOP_BRIDGE_FILE",
27
+ "REINS_DESKTOP_APP_SERVER",
28
+ })
29
+ REQUEST_KEYS = frozenset({
30
+ "expected_package_full_name", "desktop_executable", "environment",
31
+ "result_file", "check_only",
32
+ })
33
+ INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
34
+
35
+
36
+ class PROCESSENTRY32W(ctypes.Structure):
37
+ _fields_ = [
38
+ ("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD),
39
+ ("th32ProcessID", wintypes.DWORD), ("th32DefaultHeapID", ctypes.c_size_t),
40
+ ("th32ModuleID", wintypes.DWORD), ("cntThreads", wintypes.DWORD),
41
+ ("th32ParentProcessID", wintypes.DWORD), ("pcPriClassBase", wintypes.LONG),
42
+ ("dwFlags", wintypes.DWORD), ("szExeFile", wintypes.WCHAR * 260),
43
+ ]
44
+
45
+
46
+ def current_package_full_name():
47
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
48
+ kernel.GetCurrentPackageFullName.argtypes = [ctypes.POINTER(wintypes.DWORD), wintypes.LPWSTR]
49
+ kernel.GetCurrentPackageFullName.restype = wintypes.LONG
50
+ length = wintypes.DWORD()
51
+ status = kernel.GetCurrentPackageFullName(ctypes.byref(length), None)
52
+ if status != 122 or not 1 < length.value <= 65536:
53
+ raise RuntimeError("The helper has no verifiable Windows package identity (status %d)" % status)
54
+ buffer = ctypes.create_unicode_buffer(length.value)
55
+ status = kernel.GetCurrentPackageFullName(ctypes.byref(length), buffer)
56
+ if status:
57
+ raise RuntimeError("Windows package identity lookup failed (status %d)" % status)
58
+ return buffer.value
59
+
60
+
61
+ def _normalized_image(path):
62
+ value = os.path.normcase(os.path.normpath(str(path)))
63
+ return value[4:] if value.startswith("\\\\?\\") else value
64
+
65
+
66
+ def existing_desktop_processes(executable):
67
+ """Read exact executable paths; never stop an existing process.
68
+
69
+ A same-named process whose identity cannot be read is a conservative error.
70
+ This snapshot cannot prevent another independent launcher from racing us;
71
+ the Desktop's own single-instance behavior remains authoritative.
72
+ """
73
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
74
+ kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
75
+ kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
76
+ kernel.Process32FirstW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)]
77
+ kernel.Process32FirstW.restype = wintypes.BOOL
78
+ kernel.Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)]
79
+ kernel.Process32NextW.restype = wintypes.BOOL
80
+ kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
81
+ kernel.OpenProcess.restype = wintypes.HANDLE
82
+ kernel.QueryFullProcessImageNameW.argtypes = [
83
+ wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)
84
+ ]
85
+ kernel.QueryFullProcessImageNameW.restype = wintypes.BOOL
86
+ kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
87
+ kernel.WaitForSingleObject.restype = wintypes.DWORD
88
+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]
89
+ kernel.CloseHandle.restype = wintypes.BOOL
90
+ snapshot = kernel.CreateToolhelp32Snapshot(2, 0) # TH32CS_SNAPPROCESS
91
+ if snapshot == INVALID_HANDLE_VALUE:
92
+ raise ctypes.WinError(ctypes.get_last_error())
93
+ found = []
94
+ try:
95
+ entry = PROCESSENTRY32W()
96
+ entry.dwSize = ctypes.sizeof(entry)
97
+ valid = kernel.Process32FirstW(snapshot, ctypes.byref(entry))
98
+ count = 0
99
+ while valid:
100
+ count += 1
101
+ if count > 65536:
102
+ raise RuntimeError("Windows process snapshot exceeded its safety bound")
103
+ if entry.szExeFile.casefold() == executable.name.casefold():
104
+ # Native handles pin process identity through the path query.
105
+ handle = kernel.OpenProcess(0x00100000 | 0x1000, False, entry.th32ProcessID)
106
+ if not handle:
107
+ code = ctypes.get_last_error()
108
+ if code != 87: # A process that already exited may be absent.
109
+ raise RuntimeError("Cannot verify a same-named Desktop process (Win32 %d)" % code)
110
+ else:
111
+ try:
112
+ waited = kernel.WaitForSingleObject(handle, 0)
113
+ if waited == 258: # WAIT_TIMEOUT: still running
114
+ size = wintypes.DWORD(32768)
115
+ image = ctypes.create_unicode_buffer(size.value)
116
+ if not kernel.QueryFullProcessImageNameW(handle, 0, image, ctypes.byref(size)):
117
+ raise ctypes.WinError(ctypes.get_last_error())
118
+ if _normalized_image(image.value) == _normalized_image(executable):
119
+ found.append(int(entry.th32ProcessID))
120
+ elif waited != 0:
121
+ raise RuntimeError("Cannot verify whether a same-named Desktop process is alive")
122
+ finally:
123
+ kernel.CloseHandle(handle)
124
+ valid = kernel.Process32NextW(snapshot, ctypes.byref(entry))
125
+ code = ctypes.get_last_error()
126
+ if code != 18: # ERROR_NO_MORE_FILES
127
+ raise ctypes.WinError(code)
128
+ finally:
129
+ kernel.CloseHandle(snapshot)
130
+ return found
131
+
132
+
133
+ def _no_duplicate_keys(pairs):
134
+ result = {}
135
+ for key, value in pairs:
136
+ if key in result:
137
+ raise ValueError("Duplicate request field")
138
+ result[key] = value
139
+ return result
140
+
141
+
142
+ def read_request(request_file):
143
+ if not request_file.is_absolute() or request_file.suffix.lower() != ".json":
144
+ raise ValueError("The request must be an absolute JSON file path")
145
+ request_file = request_file.resolve(strict=True)
146
+ with request_file.open("rb") as stream:
147
+ raw = stream.read(65537)
148
+ if len(raw) > 65536:
149
+ raise ValueError("The request exceeds 64 KiB")
150
+ request = json.loads(raw.decode("utf-8-sig"), object_pairs_hook=_no_duplicate_keys)
151
+ if not isinstance(request, dict):
152
+ raise ValueError("The request must be an object")
153
+ result_name = request.get("result_file")
154
+ if not isinstance(result_name, str) or "\0" in result_name:
155
+ raise ValueError("The result path must be an absolute path named result.json")
156
+ result_file = Path(result_name)
157
+ if (not result_file.is_absolute() or result_file.name != "result.json"
158
+ or result_file.resolve().parent != request_file.parent
159
+ or result_file.resolve() == request_file):
160
+ raise ValueError("The result must be result.json in the request directory")
161
+ # Do not overwrite a prior result or follow an existing result symlink.
162
+ if result_file.exists() or result_file.is_symlink():
163
+ raise ValueError("The result already exists; use a fresh request directory")
164
+ return request, result_file
165
+
166
+
167
+ def validate_request(request):
168
+ if request.keys() != REQUEST_KEYS:
169
+ raise ValueError("The request must contain exactly the five documented fields")
170
+ expected = request["expected_package_full_name"]
171
+ if not isinstance(expected, str) or not expected or "\0" in expected:
172
+ raise ValueError("Expected package identity must be a nonempty string")
173
+ actual = current_package_full_name()
174
+ if actual != expected:
175
+ raise RuntimeError("Windows package identity does not match the expected package")
176
+ executable = request["desktop_executable"]
177
+ if not isinstance(executable, str) or "\0" in executable:
178
+ raise ValueError("Desktop executable must be an absolute .exe path")
179
+ executable = Path(executable)
180
+ if not executable.is_absolute() or executable.suffix.lower() != ".exe" or not executable.is_file():
181
+ raise ValueError("Desktop executable must be an existing absolute .exe path")
182
+ if type(request["check_only"]) is not bool:
183
+ raise ValueError("check_only must be a JSON boolean")
184
+ overrides = request["environment"]
185
+ if not isinstance(overrides, dict) or overrides.keys() != ENVIRONMENT_KEYS:
186
+ raise ValueError("Environment must contain exactly the seven documented overrides")
187
+ for value in overrides.values():
188
+ if value is not None and (not isinstance(value, str) or "\0" in value or len(value) > 32767):
189
+ raise ValueError("Environment override values must be bounded strings or null")
190
+ return actual, executable, overrides
191
+
192
+
193
+ def launch(request):
194
+ package, executable, overrides = validate_request(request)
195
+ # These settings affect this short-lived helper and its child only. Never
196
+ # edit user/machine environment variables, registry, or shell settings.
197
+ saved = {key: os.environ.get(key) for key in overrides}
198
+ try:
199
+ for key, value in overrides.items():
200
+ if value is None:
201
+ os.environ.pop(key, None)
202
+ else:
203
+ os.environ[key] = value
204
+ source = Path(__file__).resolve().with_name("probe-desktop-launch.py")
205
+ specification = importlib.util.spec_from_file_location("desktop_native_probe", source)
206
+ helper = importlib.util.module_from_spec(specification)
207
+ specification.loader.exec_module(helper)
208
+ native_probe, code = helper.probe(str(executable))
209
+ result = {"ok": False, "package_full_name": package, "native_launch_probe": native_probe}
210
+ if code or not native_probe["cleanup_complete"] or not native_probe["can_create_suspended"]:
211
+ result.update(error_type="NativeLaunchProbeError", message="Desktop suspended creation or cleanup failed")
212
+ return result
213
+ if (native_probe.get("child_package_query_status") != 0
214
+ or native_probe.get("child_package_full_name") != package):
215
+ result.update(error_type="PackageIdentityError",
216
+ message="The suspended Desktop child did not retain the expected Windows package identity")
217
+ return result
218
+ if not request["check_only"]:
219
+ if existing_desktop_processes(executable):
220
+ raise RuntimeError("The exact Desktop executable is already running; no new instance was started")
221
+ process = subprocess.Popen([str(executable)], cwd=str(executable.parent),
222
+ env=os.environ.copy(), close_fds=True)
223
+ result["desktop_pid"] = process.pid
224
+ result["ok"] = True
225
+ return result
226
+ finally:
227
+ for key, value in saved.items():
228
+ if value is None:
229
+ os.environ.pop(key, None)
230
+ else:
231
+ os.environ[key] = value
232
+
233
+
234
+ def main(argv=None):
235
+ parser = argparse.ArgumentParser(description=__doc__)
236
+ parser.add_argument("--request", required=True, help="Absolute path to a private request JSON file")
237
+ args = parser.parse_args(argv)
238
+ result_file = None
239
+ try:
240
+ if os.name != "nt":
241
+ raise RuntimeError("This helper runs only on Windows")
242
+ request, result_file = read_request(Path(args.request))
243
+ result = launch(request)
244
+ except Exception as error:
245
+ result = {"ok": False, "error_type": type(error).__name__, "message": str(error)}
246
+ if result_file is None:
247
+ # Do not guess a destination from an invalid request or print secrets.
248
+ print("Invalid package launch request: " + result["message"], file=sys.stderr)
249
+ return 1
250
+ try:
251
+ # One closed write, no rename/replace: package filesystem virtualization
252
+ # can deny replacement even when creating files here is permitted.
253
+ with result_file.open("x", encoding="utf-8") as stream:
254
+ json.dump(result, stream, ensure_ascii=True)
255
+ stream.write("\n")
256
+ except OSError as error:
257
+ print("Cannot write package launch result (Win32 %s)" % getattr(error, "winerror", None), file=sys.stderr)
258
+ return 1
259
+ return 0 if result["ok"] else 1
260
+
261
+
262
+ if __name__ == "__main__":
263
+ sys.exit(main())
@@ -0,0 +1,14 @@
1
+ <# Windows PowerShell 5.1 facade for the Appx diagnostic cmdlet. #>
2
+ [CmdletBinding()]
3
+ param(
4
+ [Parameter(Mandatory = $true)][string]$PackageFamilyName,
5
+ [Parameter(Mandatory = $true)][string]$Python,
6
+ [Parameter(Mandatory = $true)][string]$Helper,
7
+ [Parameter(Mandatory = $true)][string]$RequestFile
8
+ )
9
+ $ErrorActionPreference = 'Stop'
10
+ # The main script selects the installed manifest's App identity. Only this
11
+ # windowless, short-lived diagnostic helper is explicitly given package context.
12
+ # Do not use PreventBreakaway: child ownership follows the normal Windows rules.
13
+ Invoke-CommandInDesktopPackage -PackageFamilyName $PackageFamilyName -AppId 'App' `
14
+ -Command $Python -Args ('"{0}" --request "{1}"' -f $Helper, $RequestFile) | Out-Null
@@ -0,0 +1,217 @@
1
+ """Diagnose CreateProcess permissions without running any executable code.
2
+
3
+ The only child this probe can create starts suspended. It is never resumed and
4
+ is terminated through its returned process handle before the probe exits.
5
+ """
6
+
7
+ import argparse
8
+ import ctypes
9
+ from ctypes import wintypes
10
+ import json
11
+ import os
12
+ from pathlib import Path
13
+ import subprocess
14
+ import sys
15
+
16
+
17
+ CREATE_SUSPENDED = 0x00000004
18
+ CREATE_UNICODE_ENVIRONMENT = 0x00000400
19
+ CREATE_NO_WINDOW = 0x08000000
20
+ STARTF_USESHOWWINDOW = 0x00000001
21
+ WAIT_OBJECT_0 = 0
22
+ WAIT_TIMEOUT = 258
23
+ WAIT_FAILED = 0xFFFFFFFF
24
+
25
+
26
+ class STARTUPINFOW(ctypes.Structure):
27
+ _fields_ = [
28
+ ("cb", wintypes.DWORD),
29
+ ("lpReserved", wintypes.LPWSTR),
30
+ ("lpDesktop", wintypes.LPWSTR),
31
+ ("lpTitle", wintypes.LPWSTR),
32
+ ("dwX", wintypes.DWORD),
33
+ ("dwY", wintypes.DWORD),
34
+ ("dwXSize", wintypes.DWORD),
35
+ ("dwYSize", wintypes.DWORD),
36
+ ("dwXCountChars", wintypes.DWORD),
37
+ ("dwYCountChars", wintypes.DWORD),
38
+ ("dwFillAttribute", wintypes.DWORD),
39
+ ("dwFlags", wintypes.DWORD),
40
+ ("wShowWindow", wintypes.WORD),
41
+ ("cbReserved2", wintypes.WORD),
42
+ ("lpReserved2", ctypes.POINTER(wintypes.BYTE)),
43
+ ("hStdInput", wintypes.HANDLE),
44
+ ("hStdOutput", wintypes.HANDLE),
45
+ ("hStdError", wintypes.HANDLE),
46
+ ]
47
+
48
+
49
+ class PROCESS_INFORMATION(ctypes.Structure):
50
+ _fields_ = [
51
+ ("hProcess", wintypes.HANDLE),
52
+ ("hThread", wintypes.HANDLE),
53
+ ("dwProcessId", wintypes.DWORD),
54
+ ("dwThreadId", wintypes.DWORD),
55
+ ]
56
+
57
+
58
+ def _kernel32():
59
+ kernel = ctypes.WinDLL("kernel32", use_last_error=True)
60
+ kernel.GetCurrentProcess.argtypes = []
61
+ kernel.GetCurrentProcess.restype = wintypes.HANDLE
62
+ kernel.IsProcessInJob.argtypes = [
63
+ wintypes.HANDLE, wintypes.HANDLE, ctypes.POINTER(wintypes.BOOL)
64
+ ]
65
+ kernel.IsProcessInJob.restype = wintypes.BOOL
66
+ kernel.CreateProcessW.argtypes = [
67
+ wintypes.LPCWSTR,
68
+ wintypes.LPWSTR,
69
+ ctypes.c_void_p,
70
+ ctypes.c_void_p,
71
+ wintypes.BOOL,
72
+ wintypes.DWORD,
73
+ ctypes.c_void_p,
74
+ wintypes.LPCWSTR,
75
+ ctypes.POINTER(STARTUPINFOW),
76
+ ctypes.POINTER(PROCESS_INFORMATION),
77
+ ]
78
+ kernel.CreateProcessW.restype = wintypes.BOOL
79
+ kernel.GetPackageFullName.argtypes = [
80
+ wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD), wintypes.LPWSTR
81
+ ]
82
+ kernel.GetPackageFullName.restype = wintypes.LONG
83
+ kernel.TerminateProcess.argtypes = [wintypes.HANDLE, wintypes.UINT]
84
+ kernel.TerminateProcess.restype = wintypes.BOOL
85
+ kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
86
+ kernel.WaitForSingleObject.restype = wintypes.DWORD
87
+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]
88
+ kernel.CloseHandle.restype = wintypes.BOOL
89
+ return kernel
90
+
91
+
92
+ def _error_text(code):
93
+ return ctypes.FormatError(code).strip()
94
+
95
+
96
+ def _child_package_identity(kernel, handle):
97
+ """Read the exact suspended child's package identity without resuming it."""
98
+ length = wintypes.DWORD()
99
+ status = int(kernel.GetPackageFullName(handle, ctypes.byref(length), None))
100
+ if status != 122 or not 1 < length.value <= 65536: # ERROR_INSUFFICIENT_BUFFER
101
+ return None, status
102
+ name = ctypes.create_unicode_buffer(length.value)
103
+ status = int(kernel.GetPackageFullName(handle, ctypes.byref(length), name))
104
+ if status:
105
+ return None, status
106
+ return name.value or None, status
107
+
108
+
109
+ def _cleanup(kernel, child):
110
+ """Terminate and close only the exact handles returned by CreateProcessW."""
111
+ errors = []
112
+ terminated = False
113
+ try:
114
+ terminate_error = 0
115
+ if not kernel.TerminateProcess(child.hProcess, 1):
116
+ terminate_error = ctypes.get_last_error()
117
+ wait_result = kernel.WaitForSingleObject(child.hProcess, 5000)
118
+ if wait_result == WAIT_OBJECT_0:
119
+ # A separate process may already have terminated this suspended
120
+ # child. A signaled process handle also establishes safe cleanup.
121
+ terminated = True
122
+ elif wait_result == WAIT_TIMEOUT:
123
+ errors.append("the suspended child did not exit within 5 seconds")
124
+ elif wait_result == WAIT_FAILED:
125
+ code = ctypes.get_last_error()
126
+ errors.append("waiting for termination failed: %s (%d)" % (_error_text(code), code))
127
+ else:
128
+ errors.append("unexpected process wait result: %d" % wait_result)
129
+ if terminate_error and not terminated:
130
+ errors.append("TerminateProcess failed: %s (%d)" % (_error_text(terminate_error), terminate_error))
131
+ finally:
132
+ for label, handle in (("thread", child.hThread), ("process", child.hProcess)):
133
+ if handle and not kernel.CloseHandle(handle):
134
+ code = ctypes.get_last_error()
135
+ errors.append("closing the %s handle failed: %s (%d)" % (label, _error_text(code), code))
136
+ if errors:
137
+ raise RuntimeError("cleanup of suspended probe PID %d failed: %s" % (child.dwProcessId, "; ".join(errors)))
138
+ return terminated
139
+
140
+
141
+ def probe(executable):
142
+ result = {
143
+ "executable": executable,
144
+ "can_create_suspended": False,
145
+ "native_error_code": 0,
146
+ "native_error_message": "",
147
+ "current_process_in_job": None,
148
+ "child_package_full_name": None,
149
+ "child_package_query_status": None,
150
+ "probe_resumed": False,
151
+ "cleanup_complete": True,
152
+ }
153
+ try:
154
+ kernel = _kernel32()
155
+ in_job = wintypes.BOOL()
156
+ if not kernel.IsProcessInJob(kernel.GetCurrentProcess(), None, ctypes.byref(in_job)):
157
+ code = ctypes.get_last_error()
158
+ raise OSError(code, "IsProcessInJob failed: " + _error_text(code))
159
+ result["current_process_in_job"] = bool(in_job.value)
160
+ startup = STARTUPINFOW()
161
+ startup.cb = ctypes.sizeof(startup)
162
+ startup.dwFlags = STARTF_USESHOWWINDOW
163
+ startup.wShowWindow = 0
164
+ child = PROCESS_INFORMATION()
165
+ command_line = ctypes.create_unicode_buffer(subprocess.list2cmdline([executable]))
166
+ try:
167
+ created = kernel.CreateProcessW(
168
+ executable,
169
+ command_line,
170
+ None,
171
+ None,
172
+ False,
173
+ CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW,
174
+ None, # Inherit the caller's environment without reading or printing it.
175
+ str(Path(executable).parent),
176
+ ctypes.byref(startup),
177
+ ctypes.byref(child),
178
+ )
179
+ if not created:
180
+ code = ctypes.get_last_error()
181
+ result["native_error_code"] = code
182
+ result["native_error_message"] = _error_text(code)
183
+ else:
184
+ result["can_create_suspended"] = True
185
+ name, status = _child_package_identity(kernel, child.hProcess)
186
+ result["child_package_full_name"] = name
187
+ result["child_package_query_status"] = status
188
+ finally:
189
+ # Inspect the out-parameter even when Python raises immediately
190
+ # after the native call has supplied the new child's handles.
191
+ if child.hProcess:
192
+ result["cleanup_complete"] = False
193
+ result["cleanup_complete"] = _cleanup(kernel, child)
194
+ return result, 0
195
+ except (Exception, KeyboardInterrupt) as error:
196
+ print("Suspended launch probe failed: %s" % (str(error) or type(error).__name__), file=sys.stderr)
197
+ return result, 1
198
+
199
+
200
+ def main():
201
+ parser = argparse.ArgumentParser(description=__doc__)
202
+ parser.add_argument("executable", help="Absolute path to one Windows .exe file")
203
+ args = parser.parse_args()
204
+ if os.name != "nt":
205
+ parser.error("this diagnostic runs only on Windows")
206
+ if sys.version_info < (3, 9):
207
+ parser.error("Python 3.9 or newer is required")
208
+ executable = Path(args.executable)
209
+ if not executable.is_absolute() or executable.suffix.lower() != ".exe":
210
+ parser.error("executable must be an absolute .exe path")
211
+ result, returncode = probe(str(executable))
212
+ print(json.dumps(result, ensure_ascii=True))
213
+ return returncode
214
+
215
+
216
+ if __name__ == "__main__":
217
+ sys.exit(main())