Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix: fall back for non-admin Windows task installs (#3437)
Matt Van Hornb95850945270
diff --git a/headroom/install/supervisors.py b/headroom/install/supervisors.pyindex 83f517576..3a0fe96af 100644--- a/headroom/install/supervisors.py+++ b/headroom/install/supervisors.py@@ -12,6 +12,7 @@ import tempfileimport timefrom datetime import datetimefrom pathlib import Path+from xml.etree import ElementTreefrom xml.sax.saxutils import escape as _xml_escapeimport click@@ -254,25 +255,43 @@ def _windows_current_user() -> str:return f"{domain}\\{user}" if domain else user-def _windows_task_xml(command: str, *, trigger_xml: str, scope: str) -> str:- """Render Task Scheduler XML that runs ``command`` without a visible window.+class _WindowsTaskRegistrationError(RuntimeError):+ """Task registration or read-back verification failed."""++ def __init__(self, message: str, *, task_created: bool = False) -> None:+ super().__init__(message)+ self.task_created = task_created+++def _windows_task_xml(+ command: str, *, trigger_xml: str, scope: str, logon_type: str | None = None+) -> str:+ """Render Task Scheduler XML for ``command`` and its requested principal.User-scope tasks use an S4U principal ("run whether user is logged on ornot", no stored password) so each run happens in a non-interactive session- and never draws a console window (issue #2453). System-scope tasks keep the- LocalSystem service account, which already has no desktop.+ and never draws a console window (issue #2453). Callers can explicitly use+ InteractiveToken as a session-scoped compatibility mode for locked-down+ user accounts.+ System-scope tasks keep the LocalSystem service account, which already has+ no desktop."""if scope == "system":+ if logon_type not in (None, "ServiceAccount"):+ raise ValueError("System-scope Windows tasks must use ServiceAccount")principal = (" <UserId>S-1-5-18</UserId>\n"" <LogonType>ServiceAccount</LogonType>\n"" <RunLevel>HighestAvailable</RunLevel>")else:+ logon_type = logon_type or "S4U"+ if logon_type not in ("S4U", "InteractiveToken"):+ raise ValueError(f"Unsupported user-scope Windows task logon type: {logon_type}")principal = (f" <UserId>{_xml_escape(_windows_current_user())}</UserId>\n"- " <LogonType>S4U</LogonType>\n"+ f" <LogonType>{logon_type}</LogonType>\n"" <RunLevel>LeastPrivilege</RunLevel>")return (@@ -318,18 +337,51 @@ def _windows_health_trigger() -> str:)-def _register_windows_task(name: str, xml: str) -> None:- """Register ``xml`` as scheduled task ``name`` via ``schtasks /XML``."""+def _register_windows_task(name: str, xml: str, *, expected_logon_type: str) -> None:+ """Register a task and verify its principal from Task Scheduler's XML."""# schtasks reads the XML from a file; UTF-16 matches the declared encoding.tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".xml", encoding="utf-16", delete=False)try:tmp.write(xml)tmp.close()- subprocess.run(- ["schtasks", "/Create", "/TN", name, "/XML", tmp.name, "/F"],- check=True,+ task_created = False+ try:+ subprocess.run(+ ["schtasks", "/Create", "/TN", name, "/XML", tmp.name, "/F"],+ check=True,+ )+ task_created = True+ query = subprocess.run(+ ["schtasks", "/Query", "/TN", name, "/XML"],+ check=True,+ capture_output=True,+ )+ except (OSError, subprocess.SubprocessError) as exc:+ raise _WindowsTaskRegistrationError(+ f"Could not register or verify Windows task {name!r}: {exc}",+ task_created=task_created,+ ) from exc++ try:+ task = ElementTree.fromstring(query.stdout or "")+ except ElementTree.ParseError as exc:+ raise _WindowsTaskRegistrationError(+ f"Could not parse registered Windows task {name!r}", task_created=True+ ) from exc++ logon_element = task.find(".//{*}LogonType")+ actual_logon_type = (+ logon_element.text.strip()+ if logon_element is not None and logon_element.text is not None+ else None)+ if actual_logon_type != expected_logon_type:+ raise _WindowsTaskRegistrationError(+ f"Windows task {name!r} requested {expected_logon_type} logon type, "+ f"but Task Scheduler registered {actual_logon_type or 'no logon type'}",+ task_created=True,+ )finally:try:os.unlink(tmp.name)@@ -337,6 +389,46 @@ def _register_windows_task(name: str, xml: str) -> None:pass+def _delete_windows_task(name: str) -> subprocess.CompletedProcess[str] | None:+ """Best-effort removal of a scheduled task."""++ try:+ return run(+ ["schtasks", "/Delete", "/TN", name, "/F"],+ capture_output=True,+ text=True,+ )+ except OSError:+ return None+++def _cleanup_windows_tasks_for_fallback(names: list[str], *, must_delete: set[str]) -> None:+ """Remove preferred tasks and fail if Task Scheduler still reports one."""++ for name in names:+ deletion = _delete_windows_task(name)+ if name in must_delete and (deletion is None or deletion.returncode != 0):+ raise _WindowsTaskRegistrationError(+ f"Could not clean up Windows task {name!r} before compatibility fallback"+ )++ try:+ query = run(+ ["schtasks", "/Query", "/TN", name, "/XML"],+ capture_output=True,+ text=True,+ )+ except OSError as exc:+ raise _WindowsTaskRegistrationError(+ f"Could not verify cleanup of Windows task {name!r}: {exc}"+ ) from exc++ if query.returncode == 0:+ raise _WindowsTaskRegistrationError(+ f"Could not clean up Windows task {name!r}; it remains registered"+ )++def install_supervisor(manifest: DeploymentManifest) -> list[ArtifactRecord]:"""Install service/task artifacts for the deployment."""@@ -443,18 +535,53 @@ def install_supervisor(manifest: DeploymentManifest) -> list[ArtifactRecord]:# Register from task XML (not schtasks flags) so the principal is S4U /# hidden — flag-created tasks use an interactive token and flash a# focus-stealing console on every run (issue #2453).- _register_windows_task(- startup_name,- _windows_task_xml(- startup_cmd, trigger_xml=_windows_boot_trigger(), scope=manifest.scope- ),- )- _register_windows_task(- health_name,- _windows_task_xml(- startup_cmd, trigger_xml=_windows_health_trigger(), scope=manifest.scope- ),- )+ preferred_logon_type = "ServiceAccount" if manifest.scope == "system" else "S4U"+ preferred_tasks = [+ (startup_name, _windows_boot_trigger()),+ (health_name, _windows_health_trigger()),+ ]+ registered_preferred_tasks: list[str] = []++ try:+ for name, trigger_xml in preferred_tasks:+ _register_windows_task(+ name,+ _windows_task_xml(+ startup_cmd,+ trigger_xml=trigger_xml,+ scope=manifest.scope,+ logon_type=preferred_logon_type,+ ),+ expected_logon_type=preferred_logon_type,+ )+ registered_preferred_tasks.append(name)+ except _WindowsTaskRegistrationError as exc:+ if manifest.scope == "system":+ raise+ must_delete = set(registered_preferred_tasks)+ if exc.task_created:+ must_delete.add(name)+ _cleanup_windows_tasks_for_fallback(+ [name for name, _trigger_xml in preferred_tasks], must_delete=must_delete+ )+ _register_windows_task(+ health_name,+ _windows_task_xml(+ startup_cmd,+ trigger_xml=_windows_health_trigger(),+ scope=manifest.scope,+ logon_type="InteractiveToken",+ ),+ expected_logon_type="InteractiveToken",+ )+ click.echo(+ "Warning: Windows Task Scheduler rejected logged-off recovery; "+ "using session-scoped health recovery. The health task runs every "+ "five minutes while you are logged on and will not run while you are logged off."+ )+ records.append(ArtifactRecord(kind="windows-task", path=health_name))+ return records+records.extend([ArtifactRecord(kind="windows-task", path=startup_name),@@ -632,13 +759,5 @@ def remove_supervisor(manifest: DeploymentManifest) -> None:text=True,)return- run(- ["schtasks", "/Delete", "/TN", f"{manifest.service_name}-startup", "/F"],- capture_output=True,- text=True,- )- run(- ["schtasks", "/Delete", "/TN", f"{manifest.service_name}-health", "/F"],- capture_output=True,- text=True,- )+ _delete_windows_task(f"{manifest.service_name}-startup")+ _delete_windows_task(f"{manifest.service_name}-health")diff --git a/tests/test_install/test_supervisors.py b/tests/test_install/test_supervisors.pyindex 60d1f85b1..a8700fb67 100644--- a/tests/test_install/test_supervisors.py+++ b/tests/test_install/test_supervisors.py@@ -1,5 +1,6 @@from __future__ import annotations+import subprocessfrom pathlib import Pathimport click@@ -11,11 +12,13 @@ from headroom.install.supervisors import (_linux_service_unit,_linux_task_spec,_macos_launchd_plist,+ _register_windows_task,_render_unix_runner,_render_windows_runner,_windows_boot_trigger,_windows_health_trigger,_windows_task_xml,+ _WindowsTaskRegistrationError,install_supervisor,remove_supervisor,render_runner_scripts,@@ -38,6 +41,20 @@ def test_windows_task_xml_user_scope_is_hidden_s4u() -> None:assert "<Command>C:\\tmp\\default\\ensure-headroom.cmd</Command>" in xml+def test_windows_task_xml_user_scope_supports_interactive_token() -> None:+ xml = _windows_task_xml(+ "C:\\tmp\\default\\ensure-headroom.cmd",+ trigger_xml=_windows_health_trigger(),+ scope="user",+ logon_type="InteractiveToken",+ )++ assert "<TimeTrigger>" in xml+ assert "<LogonType>InteractiveToken</LogonType>" in xml+ assert "<RunLevel>LeastPrivilege</RunLevel>" in xml+ assert "<Interval>PT5M</Interval>" in xml++def test_windows_task_xml_system_scope_uses_localsystem() -> None:xml = _windows_task_xml("C:\\tmp\\default\\ensure-headroom.cmd",@@ -49,6 +66,88 @@ def test_windows_task_xml_system_scope_uses_localsystem() -> None:assert "<BootTrigger>" in xml+def test_register_windows_task_verifies_queried_logon_type(monkeypatch) -> None:+ calls: list[list[str]] = []++ def fake_run(command: list[str], **kwargs):+ calls.append(command)+ if command[1] == "/Query":+ return _LaunchctlResult(+ stdout=(+ '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'+ "<Principals><Principal><LogonType>S4U</LogonType></Principal></Principals>"+ "</Task>"+ )+ )+ return _LaunchctlResult()++ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)++ _register_windows_task("headroom-default-health", "<Task />", expected_logon_type="S4U")++ assert calls[0][:4] == [+ "schtasks",+ "/Create",+ "/TN",+ "headroom-default-health",+ ]+ assert calls[1] == ["schtasks", "/Query", "/TN", "headroom-default-health", "/XML"]+++def test_register_windows_task_rejects_logon_type_downgrade(monkeypatch) -> None:+ def fake_run(command: list[str], **kwargs):+ if command[1] == "/Query":+ return _LaunchctlResult(+ stdout=(+ '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'+ "<Principals><Principal>"+ "<LogonType>InteractiveToken</LogonType>"+ "</Principal></Principals></Task>"+ )+ )+ return _LaunchctlResult()++ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)++ with pytest.raises(+ _WindowsTaskRegistrationError, match="requested S4U.*InteractiveToken"+ ) as exc_info:+ _register_windows_task("headroom-default-health", "<Task />", expected_logon_type="S4U")++ assert exc_info.value.task_created is True++[email protected]("failed_action", ["/Create", "/Query"])+def test_register_windows_task_wraps_schtasks_failures(monkeypatch, failed_action: str) -> None:+ calls: list[list[str]] = []++ def fake_run(command: list[str], **kwargs):+ calls.append(command)+ if command[1] == failed_action:+ raise subprocess.CalledProcessError(1, command)+ return _LaunchctlResult()++ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)++ with pytest.raises(+ _WindowsTaskRegistrationError, match="Could not register or verify"+ ) as exc_info:+ _register_windows_task("headroom-default-health", "<Task />", expected_logon_type="S4U")++ assert calls[-1][1] == failed_action+ assert exc_info.value.task_created is (failed_action == "/Query")+++def test_register_windows_task_rejects_malformed_queried_xml(monkeypatch) -> None:+ monkeypatch.setattr(+ "headroom.install.supervisors.subprocess.run",+ lambda command, **kwargs: _LaunchctlResult(stdout="<Task>"),+ )++ with pytest.raises(_WindowsTaskRegistrationError, match="Could not parse registered"):+ _register_windows_task("headroom-default-health", "<Task />", expected_logon_type="S4U")++def _manifest(*,profile: str = "default",@@ -353,6 +452,239 @@ def test_install_supervisor_linux_service_and_tasks(monkeypatch, tmp_path: Path)assert "@reboot ensure" in calls[-1][1]["input"]+def _stub_windows_task_install(monkeypatch, tmp_path: Path) -> None:+ run_script = tmp_path / "run-headroom.cmd"+ ensure_script = tmp_path / "ensure-headroom.cmd"+ monkeypatch.setattr(+ "headroom.install.supervisors.render_runner_scripts",+ lambda manifest: [+ type("Record", (), {"kind": "script", "path": str(run_script)})(),+ type("Record", (), {"kind": "script", "path": str(ensure_script)})(),+ ],+ )+ monkeypatch.setattr("headroom.install.supervisors.sys.platform", "win32")+ monkeypatch.setattr(+ "headroom.install.supervisors.windows_ensure_cmd_path",+ lambda profile: ensure_script,+ )+++def test_install_windows_user_tasks_prefers_verified_s4u(+ monkeypatch, tmp_path: Path, capsys+) -> None:+ _stub_windows_task_install(monkeypatch, tmp_path)+ registrations: list[tuple[str, str, str]] = []++ def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:+ registrations.append((name, xml, expected_logon_type))++ monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)++ records = install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))++ assert [(name, logon_type) for name, _xml, logon_type in registrations] == [+ ("headroom-default-startup", "S4U"),+ ("headroom-default-health", "S4U"),+ ]+ assert "<BootTrigger>" in registrations[0][1]+ assert "<TimeTrigger>" in registrations[1][1]+ assert [record.path for record in records if record.kind == "windows-task"] == [+ "headroom-default-startup",+ "headroom-default-health",+ ]+ assert "session-scoped" not in capsys.readouterr().out++[email protected]("failed_task", ["headroom-default-startup", "headroom-default-health"])+def test_install_windows_user_task_failure_cleans_up_and_falls_back(+ monkeypatch, tmp_path: Path, capsys, failed_task: str+) -> None:+ _stub_windows_task_install(monkeypatch, tmp_path)+ registrations: list[tuple[str, str, str]] = []+ deletions: list[str] = []++ def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:+ registrations.append((name, xml, expected_logon_type))+ if name == failed_task and expected_logon_type == "S4U":+ raise _WindowsTaskRegistrationError("registration denied")++ monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)+ monkeypatch.setattr(+ "headroom.install.supervisors._cleanup_windows_tasks_for_fallback",+ lambda names, must_delete: deletions.extend(names),+ )++ records = install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))++ assert deletions == ["headroom-default-startup", "headroom-default-health"]+ fallback_name, fallback_xml, fallback_logon_type = registrations[-1]+ assert fallback_name == "headroom-default-health"+ assert fallback_logon_type == "InteractiveToken"+ assert "<TimeTrigger>" in fallback_xml+ assert "<LogonType>InteractiveToken</LogonType>" in fallback_xml+ assert "<RunLevel>LeastPrivilege</RunLevel>" in fallback_xml+ assert "<Interval>PT5M</Interval>" in fallback_xml+ assert [record.path for record in records if record.kind == "windows-task"] == [+ "headroom-default-health"+ ]+ warning = capsys.readouterr().out+ assert "session-scoped" in warning+ assert "will not run while you are logged off" in warning+++def test_install_windows_user_task_silent_downgrade_uses_fallback(+ monkeypatch, tmp_path: Path, capsys+) -> None:+ _stub_windows_task_install(monkeypatch, tmp_path)+ registered_xml: dict[str, str] = {}+ query_count = 0+ calls: list[list[str]] = []++ def fake_run(command: list[str], **kwargs):+ nonlocal query_count+ calls.append(command)+ name = command[command.index("/TN") + 1]+ if command[1] == "/Create":+ registered_xml[name] = Path(command[command.index("/XML") + 1]).read_text(+ encoding="utf-16"+ )+ return _LaunchctlResult()+ if command[1] == "/Query":+ if name not in registered_xml:+ return _LaunchctlResult(+ 1, stderr="ERROR: The system cannot find the file specified."+ )+ query_count += 1+ xml = registered_xml[name]+ if query_count == 1:+ xml = xml.replace(+ "<LogonType>S4U</LogonType>", "<LogonType>InteractiveToken</LogonType>"+ )+ return _LaunchctlResult(stdout=xml)+ registered_xml.pop(name, None)+ return _LaunchctlResult()++ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)++ records = install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))++ deletes = [call for call in calls if call[1] == "/Delete"]+ assert [call[call.index("/TN") + 1] for call in deletes] == [+ "headroom-default-startup",+ "headroom-default-health",+ ]+ assert "headroom-default-startup" not in registered_xml+ assert "<LogonType>InteractiveToken</LogonType>" in registered_xml["headroom-default-health"]+ assert [record.path for record in records if record.kind == "windows-task"] == [+ "headroom-default-health"+ ]+ assert "session-scoped" in capsys.readouterr().out+++def test_install_windows_user_task_fallback_failure_propagates(+ monkeypatch, tmp_path: Path, capsys+) -> None:+ _stub_windows_task_install(monkeypatch, tmp_path)++ def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:+ raise _WindowsTaskRegistrationError(f"{expected_logon_type} registration denied")++ monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)+ monkeypatch.setattr(+ "headroom.install.supervisors._cleanup_windows_tasks_for_fallback",+ lambda names, must_delete: None,+ )++ with pytest.raises(_WindowsTaskRegistrationError, match="InteractiveToken registration denied"):+ install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))++ assert "session-scoped" not in capsys.readouterr().out+++ ("query_state", "error_match"),+ [+ ("survives", "remains registered"),+ ("delete_denied", "Could not clean up"),+ ],+)+def test_install_windows_user_task_cleanup_failure_prevents_fallback(+ monkeypatch, tmp_path: Path, capsys, query_state: str, error_match: str+) -> None:+ _stub_windows_task_install(monkeypatch, tmp_path)+ registrations: list[str] = []++ def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:+ registrations.append(expected_logon_type)+ raise _WindowsTaskRegistrationError("S4U registration denied", task_created=True)++ def fake_run(command: list[str], **kwargs):+ if query_state == "survives" and command[1] in ("/Delete", "/Query"):+ return _LaunchctlResult(stdout="<Task />")+ return _LaunchctlResult(1, stderr="ERROR: Access is denied.")++ monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)+ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)++ with pytest.raises(_WindowsTaskRegistrationError, match=error_match):+ install_supervisor(_manifest(supervisor=SupervisorKind.TASK.value))++ assert registrations == ["S4U"]+ assert "session-scoped" not in capsys.readouterr().out+++def test_install_windows_system_tasks_use_verified_service_account(+ monkeypatch, tmp_path: Path, capsys+) -> None:+ _stub_windows_task_install(monkeypatch, tmp_path)+ registrations: list[tuple[str, str, str]] = []++ def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:+ registrations.append((name, xml, expected_logon_type))++ monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)++ records = install_supervisor(_manifest(scope="system", supervisor=SupervisorKind.TASK.value))++ assert [(name, logon_type) for name, _xml, logon_type in registrations] == [+ ("headroom-default-startup", "ServiceAccount"),+ ("headroom-default-health", "ServiceAccount"),+ ]+ assert "<BootTrigger>" in registrations[0][1]+ assert "<TimeTrigger>" in registrations[1][1]+ assert all(+ "<LogonType>ServiceAccount</LogonType>" in xml for _name, xml, _type in registrations+ )+ assert all("<UserId>S-1-5-18</UserId>" in xml for _name, xml, _type in registrations)+ assert all(+ "<RunLevel>HighestAvailable</RunLevel>" in xml for _name, xml, _type in registrations+ )+ assert [record.path for record in records if record.kind == "windows-task"] == [+ "headroom-default-startup",+ "headroom-default-health",+ ]+ assert "session-scoped" not in capsys.readouterr().out+++def test_install_windows_system_task_failure_does_not_fall_back(+ monkeypatch, tmp_path: Path, capsys+) -> None:+ _stub_windows_task_install(monkeypatch, tmp_path)+ registrations: list[tuple[str, str]] = []++ def fake_register(name: str, xml: str, *, expected_logon_type: str) -> None:+ registrations.append((name, expected_logon_type))+ raise _WindowsTaskRegistrationError("system registration denied")++ monkeypatch.setattr("headroom.install.supervisors._register_windows_task", fake_register)++ with pytest.raises(_WindowsTaskRegistrationError, match="system registration denied"):+ install_supervisor(_manifest(scope="system", supervisor=SupervisorKind.TASK.value))++ assert registrations == [("headroom-default-startup", "ServiceAccount")]+ assert "session-scoped" not in capsys.readouterr().out++def test_install_supervisor_darwin_windows_and_unsupported(monkeypatch, tmp_path: Path) -> None:run_script = tmp_path / "run-headroom.sh"ensure_script = tmp_path / "ensure-headroom.sh"@@ -364,10 +696,20 @@ def test_install_supervisor_darwin_windows_and_unsupported(monkeypatch, tmp_path],)calls: list[list[str]] = []- monkeypatch.setattr(- "headroom.install.supervisors.subprocess.run",- lambda command, **kwargs: calls.append(command) or _LaunchctlResult(0),- )++ def fake_run(command, **kwargs):+ calls.append(command)+ if isinstance(command, list) and len(command) > 1 and command[1] == "/Query":+ return _LaunchctlResult(+ stdout=(+ '<Task xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">'+ "<Principals><Principal><LogonType>S4U</LogonType></Principal></Principals>"+ "</Task>"+ )+ )+ return _LaunchctlResult(0)++ monkeypatch.setattr("headroom.install.supervisors.subprocess.run", fake_run)monkeypatch.setattr("headroom.install.supervisors.os.getuid", lambda: 123, raising=False)plist_path = tmp_path / "com.headroom.default.plist"