@harness-reins/linux-x64 0.9.2 → 0.10.1

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.
@@ -1 +1 @@
1
- 50d79f84e35f
1
+ 57cb49c9d757
@@ -8,7 +8,7 @@ description: Run long jobs (training, benchmarks, builds, test suites, deploymen
8
8
  Reins hands a long command to an independent OS task owner (systemd on Linux, launchd on macOS,
9
9
  Task Scheduler on Windows; `screen` as fallback) and queues a callback when it exits. When this
10
10
  thread is idle, Reins delivers the callback **as a new turn in this same thread**: `codex exec
11
- resume` for CLI sessions, the shared App Server for Codex Desktop. You do not wait for it; you end
11
+ resume` for CLI sessions, the native `codex queue` command for normally started Codex Desktop. You do not wait for it; you end
12
12
  your turn and the result comes back to you.
13
13
 
14
14
  The full reference (all flags, platforms, Desktop modes, recovery and goals) is in
@@ -50,40 +50,25 @@ Registration maintains only the following index; preserve the surrounding instru
50
50
  ### Callback modes (0.7.1 preview)
51
51
 
52
52
  `--callback-mode auto` recognizes the current Codex Desktop origin marker and
53
- selects `desktop`; other origins select `cli`. Use an explicit mode if the host
53
+ selects `codex-queue`; other origins select `cli`. Use an explicit mode if the host
54
54
  omits that marker. A historical session source is not its current owner.
55
- `desktop` requires a verified shared Core and never silently falls back to a
56
- second CLI writer. An unavailable Desktop connection refuses a new `run` or
57
- `agent` before task admission. `done` still preserves already completed work.
58
- Do not force CLI mode to conceal a Desktop ownership conflict.
55
+ `codex-queue` publishes once using the public Codex CLI queue and waits for the receiving thread to ACK. No custom Desktop launcher or idle-status polling is needed. Keep the receiving chat open. A queued command is not proof of receipt; retain uncertain submissions without replay. The binary and Codex profile are frozen at submission.
56
+
57
+ Do not start Desktop through a launcher; `reins setup` no longer generates one and an
58
+ old copy only prints this advice. `--callback-mode desktop` is retired and refused for new
59
+ work. A saved `desktop` callback that is blocked keeps its result: move it with
60
+ `reins retry --id ID --callback-mode codex-queue`, which does not rerun the workload.
61
+ A blocked route refuses a new `run` or `agent` before task admission. `done` still
62
+ preserves already completed work. Do not force CLI mode to conceal an ownership conflict.
59
63
 
60
64
  `manual` explicitly saves results/callbacks for later receipt and does not start
61
65
  an Agent automatically. Choose it only when the user accepts this limitation.
62
- On Mac and Windows, `reins setup` automatically generates a private double-click
63
- launcher bound to the installed Python and current profile: `.command` on Mac,
64
- `.cmd` plus `.ps1` on Windows. `setup --desktop-app PATH` selects a Mac `.app`
65
- or Windows `.exe`; `--no-desktop-launcher` skips generation. Missing Desktop does
66
- not block CLI setup. Mac discovers the app during preparation; Windows resolves
67
- the Store manifest and matching Core during launch/preflight. Windows helpers
68
- ship inside the wheel; do not depend on a checkout or its examples directory.
69
- Generated absolute paths belong to that machine; regenerate them after moving
70
- the Python installation rather than copying another user's files.
71
- `reins desktop prepare` is available for later configuration changes;
72
- `reins desktop launch --check-only` checks launch blockers, and `reins desktop launch`
73
- requires existing Desktop work to be saved and the app closed. Obtain permission
74
- before interrupting active Desktop work. Preparation and checks need no restart.
75
- Windows defaults to direct startup. `setup --desktop-launch-mode package-context`
76
- or `desktop prepare --launch-mode package-context --force` saves the explicitly
77
- chosen experimental Store route. Never silently fall back to this diagnostic
78
- context after an access-denied failure. `--check-only` uses the existing suspended
79
- creation/cleanup probe; it is not GUI/tool/callback acceptance. Ordinary setup
80
- only generates files and performs no native GUI creation probe.
81
66
 
82
67
  Read `doctor`'s separate `callback` field. `owner_reachable` is a read-only
83
68
  observation, not proof of end-to-end receipt. Sandboxed tools may need authorized
84
69
  ordinary-user execution to inspect native peers; never weaken identity checks.
85
- After repairing a known failed handoff, `reins retry --id ID --callback-mode desktop`
86
- requeues the original callback without rerunning its workload. Unknown submission
70
+ After repairing a known failed handoff, `reins retry --id ID` (add `--callback-mode codex-queue`
71
+ to change route) requeues the original callback without rerunning its workload. Unknown submission
87
72
  outcomes, active deliveries, ACKs and cancellations prevent ordinary retry.
88
73
  Inspect manual results in the bound session before ACK, and label that receipt
89
74
  as manual rather than a successful autonomous callback test.
@@ -214,7 +199,7 @@ without this automatic check.
214
199
 
215
200
  ```bash
216
201
  # Install screen only if using the compatibility backend.
217
- python3 -m pip install "git+https://github.com/lz59970062/harness-reins.git@codex/macos-desktop-callback"
202
+ python3 -m pip install "git+https://github.com/lz59970062/harness-reins.git"
218
203
  reins setup --force --enable --now
219
204
  ```
220
205
 
@@ -259,7 +244,7 @@ the ordinary logged-in user's Task Scheduler session. `--backend auto` and
259
244
  from the release checkout in PowerShell without activating the venv:
260
245
 
261
246
  ```powershell
262
- git clone --branch codex/macos-desktop-callback --depth 1 https://github.com/lz59970062/harness-reins.git
247
+ git clone --depth 1 https://github.com/lz59970062/harness-reins.git
263
248
  Set-Location harness-reins
264
249
  py -3 -m venv .venv
265
250
  & .\.venv\Scripts\python.exe -m pip install .
@@ -284,17 +269,10 @@ receipt only, not goal completion. Never replace the target with another session
284
269
  A live Windows test with Codex 0.153.4 could not resume its open Desktop session:
285
270
  the CLI reported `already has an active writer`. Ending an Agent turn does not
286
271
  guarantee that Desktop releases this owner. Preserve the failed callback and
287
- report this transport limitation; do not delete Codex's writer lock, forge an
288
- ACK, change the bound session or rerun the business work. Native workload and
272
+ report this transport limitation or move it to `codex-queue`; do not delete Codex's
273
+ writer lock, forge an ACK, change the bound session or rerun the business work. Native workload and
289
274
  fake-Agent delivery tests do not establish live original-session receipt.
290
275
 
291
- For the experimental bridge, follow the repository's `docs/windows-desktop-bridge.md`.
292
- It requires Desktop and Reins to use one App Server and the explicit
293
- `REINS_DESKTOP_BRIDGE_FILE` metadata path. Never guess a port or
294
- expose an unauthenticated App Server. The supplied launcher refuses a running
295
- Desktop; switching its connection requires closing active Desktop work first.
296
- After explicit bridge selection, connection failure must not fall back to CLI.
297
-
298
276
  New private files/directories grant only the current user and SYSTEM access.
299
277
  Do not weaken those ACLs to work around an Agent sandbox's restricted token;
300
278
  authorized native setup/tests may need an ordinary user process outside that
@@ -11,7 +11,20 @@ const digest = (value) => crypto.createHash("sha256").update(value).digest("hex"
11
11
 
12
12
  function canonical(value) {
13
13
  if (typeof value !== "string" || !path.isAbsolute(value)) throw new Error("An absolute session file is required");
14
- return norm(fs.existsSync(value) ? fs.realpathSync(value) : path.resolve(value));
14
+ return resolved(value);
15
+ }
16
+
17
+ // Like Python's Path.resolve(): follow symlinks through the part that exists, so
18
+ // paths recorded here match the ones Reins compares them with (/var on macOS
19
+ // is a symlink to /private/var).
20
+ function resolved(value) {
21
+ let head = path.resolve(value);
22
+ const tail = [];
23
+ while (!fs.existsSync(head) && path.dirname(head) !== head) {
24
+ tail.unshift(path.basename(head));
25
+ head = path.dirname(head);
26
+ }
27
+ return norm(path.join(fs.existsSync(head) ? fs.realpathSync(head) : head, ...tail));
15
28
  }
16
29
 
17
30
  function privateDirectory(directory) {
@@ -163,7 +176,7 @@ export default function ltcCallback(pi) {
163
176
  if (!file) return; // --no-session children have no callback owner.
164
177
  const session = canonical(file);
165
178
  const profile = canonical(path.resolve(process.env.PI_CODING_AGENT_DIR || path.join(os.homedir(), ".pi", "agent")));
166
- const root = path.resolve(process.env.REINS_PI_CHANNEL_ROOT || path.join(profile, "harness-reins", "channels"));
179
+ const root = resolved(process.env.REINS_PI_CHANNEL_ROOT || path.join(profile, "harness-reins", "channels"));
167
180
  if (process.platform === "win32" && !fs.existsSync(root)) {
168
181
  throw new Error("Install the extension with Reins to initialize private Windows channel permissions");
169
182
  }
package/dist/reins/reins CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@harness-reins/linux-x64",
3
- "version": "0.9.2",
3
+ "version": "0.10.1",
4
4
  "description": "Prebuilt Harness Reins binary for linux-x64",
5
5
  "license": "MIT",
6
6
  "os": [
@@ -1,263 +0,0 @@
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())
@@ -1,14 +0,0 @@
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
@@ -1,217 +0,0 @@
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())