Skip to content

Experience-Driven Black-Box Cost Control for Coding Agents

Windows: spawn te with a hidden console, and WMI's runner under pythonw

Grigory Pavlichenko3957d4eeb613
diff --git a/tests/test_winspawn.py b/tests/test_winspawn.py
new file mode 100644
index 0000000..30928e8
--- /dev/null
+++ b/tests/test_winspawn.py
@@ -0,0 +1,77 @@
+"""Windows' detached spawn: `te` runs with a hidden console, and the WMI runner with no window.
+
+`DETACHED_PROCESS` looks harmless here and is what opened a visible console window for every git
+or agent CLI call `te` made; WMI starting `python.exe` opened one more for the runner. Both are
+pinned by the arguments the spawn passes, so these run on any OS.
+"""
+import os
+import subprocess
+
+from tokeneconomizer.plugin import winspawn
+
+DETACHED_PROCESS = 0x00000008
+CREATE_NO_WINDOW = 0x08000000
+CREATE_BREAKAWAY_FROM_JOB = 0x01000000
+
+
+def test_te_gets_a_hidden_console_and_leaves_the_job(monkeypatch, tmp_path):
+ seen = {}
+
+ def popen(cmd, **kwargs):
+ seen.update(kwargs)
+
+ monkeypatch.setattr(winspawn.subprocess, "Popen", popen)
+ assert winspawn.spawn(["te"], str(tmp_path), {}, str(tmp_path / "te.log"))
+ flags = seen["creationflags"]
+ assert not flags & DETACHED_PROCESS
+ assert flags & CREATE_NO_WINDOW
+ assert flags & CREATE_BREAKAWAY_FROM_JOB
+
+
+def test_a_job_without_breakaway_goes_through_wmi(monkeypatch, tmp_path):
+ def popen(cmd, **kwargs):
+ raise OSError("access denied")
+
+ calls = []
+ monkeypatch.setattr(winspawn.subprocess, "Popen", popen)
+ monkeypatch.setattr(winspawn, "_spawn_wmi", lambda *args: calls.append(args) or True)
+ assert winspawn.spawn(["te"], str(tmp_path), {}, str(tmp_path / "te.log"))
+ assert len(calls) == 1
+
+
+def _interpreter(monkeypatch, tmp_path, name, beside):
+ for other in beside:
+ (tmp_path / other).write_text("")
+ monkeypatch.setattr(winspawn.sys, "executable", str(tmp_path / name))
+
+
+def test_the_runner_is_pythonw(monkeypatch, tmp_path):
+ _interpreter(monkeypatch, tmp_path, "python.exe", ["python.exe", "pythonw.exe"])
+ assert winspawn._windowless_python() == str(tmp_path / "pythonw.exe")
+
+
+def test_the_runner_matches_a_suffixed_interpreter(monkeypatch, tmp_path):
+ _interpreter(monkeypatch, tmp_path, "python3.13t.exe",
+ ["python3.13t.exe", "pythonw3.13t.exe", "pythonw.exe"])
+ assert winspawn._windowless_python() == str(tmp_path / "pythonw3.13t.exe")
+
+
+def test_the_runner_falls_back_to_this_interpreter(monkeypatch, tmp_path):
+ _interpreter(monkeypatch, tmp_path, "python.exe", ["python.exe"])
+ assert winspawn._windowless_python() == str(tmp_path / "python.exe")
+
+
+def test_wmi_starts_the_windowless_runner(monkeypatch, tmp_path):
+ _interpreter(monkeypatch, tmp_path, "python.exe", ["python.exe", "pythonw.exe"])
+ scripts = []
+
+ def run(cmd, **kwargs):
+ scripts.append(cmd[-1])
+ return subprocess.CompletedProcess(cmd, 0)
+
+ monkeypatch.setattr(winspawn.subprocess, "run", run)
+ assert winspawn._spawn_wmi(["te"], str(tmp_path), {}, str(tmp_path / "te.log"))
+ pythonw = subprocess.list2cmdline([str(tmp_path / "pythonw.exe")])
+ assert "CommandLine = '%s " % pythonw.replace("'", "''") in scripts[0]
+ for spec in tmp_path.glob("te-spawn-*.json"):
+ os.remove(spec)
diff --git a/tokeneconomizer/plugin/winspawn.py b/tokeneconomizer/plugin/winspawn.py
index db73cb6..5d5b447 100644
--- a/tokeneconomizer/plugin/winspawn.py
+++ b/tokeneconomizer/plugin/winspawn.py
@@ -1,14 +1,14 @@
"""Detached processes on Windows, where a hook's children die with it.
An agent runs each hook inside a Windows job object that kills every process in it when the hook
-returns, so `start_new_session` (a no-op on Windows) and `DETACHED_PROCESS` alone do not keep a
-spawned `te` alive. Two ways out, tried in order:
+returns, so `start_new_session` (a no-op on Windows) does not keep a spawned `te` alive. Two
+ways out, tried in order:
1. `CREATE_BREAKAWAY_FROM_JOB`, which works when the job allows breakaway;
2. otherwise WMI's `Win32_Process.Create`, whose process is a child of the WMI service and so
outside the job by construction. WMI passes neither the environment nor redirections, so
the command, its environment and its log are written to a spec file that this module, run
- as a script, reads back (`python winspawn.py <spec>`).
+ as a script, reads back (`pythonw winspawn.py <spec>`; `python` where there is no pythonw).
Run as a script, this file imports nothing from the package: the package may not be on
`sys.path` until the spec's `PYTHONPATH` is applied.
@@ -19,12 +19,28 @@ import subprocess
import sys
import tempfile
-_FLAGS = (0x00000008 # DETACHED_PROCESS
- | 0x00000200 # CREATE_NEW_PROCESS_GROUP
+# No DETACHED_PROCESS: it overrides CREATE_NO_WINDOW and leaves `te` with no console, so every
+# console child it runs (git, the agent's CLI) opens a visible window of its own. A hidden
+# console is inherited by those children instead.
+_FLAGS = (0x00000200 # CREATE_NEW_PROCESS_GROUP
| 0x08000000) # CREATE_NO_WINDOW
_BREAKAWAY = 0x01000000 # CREATE_BREAKAWAY_FROM_JOB
+def _windowless_python():
+ """pythonw beside this interpreter, which WMI can start without a console window: the one
+ named like it (`python3.13t.exe` -> `pythonw3.13t.exe`), else `pythonw.exe`."""
+ folder, name = os.path.split(sys.executable)
+ names = ["pythonw.exe"]
+ if name.lower().startswith("python"):
+ names.insert(0, "pythonw" + name[len("python"):])
+ for candidate in names:
+ exe = os.path.join(folder, candidate)
+ if os.path.isfile(exe):
+ return exe
+ return sys.executable
+
+
def spawn(cmd, cwd, env, log_path):
"""Start `cmd` so that it outlives the hook that started it. Returns whether it started."""
try:
@@ -42,7 +58,7 @@ def _spawn_wmi(cmd, cwd, env, log_path):
dir=os.path.dirname(log_path))
with os.fdopen(fd, "w") as fh:
json.dump({"cmd": cmd, "cwd": cwd, "env": env, "log": log_path}, fh)
- line = subprocess.list2cmdline([sys.executable, os.path.abspath(__file__), spec])
+ line = subprocess.list2cmdline([_windowless_python(), os.path.abspath(__file__), spec])
ps = ("$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments "
"@{ CommandLine = '%s'; CurrentDirectory = '%s' }; exit $r.ReturnValue"
% (line.replace("'", "''"), cwd.replace("'", "''")))