Coverage for src/ai_shell/standalone.py: 97%
90 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-17 21:40 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-17 21:40 +0000
1"""Standalone single-file executable support (PyInstaller).
3Provides runtime helpers for running ``ai-shell`` as a frozen single-file
4binary (where ``sys.frozen`` is set and bundled files live in an ephemeral
5``sys._MEIPASS`` directory) and the build CLI used in CI and local builds to
6produce standalone executables without requiring ``pip`` or PyPI on target
7machines.
8"""
10from __future__ import annotations
12import argparse
13import os
14import platform
15import shutil
16import sys
17import tempfile
18from collections.abc import Mapping
19from pathlib import Path
21from ai_shell import __version__
24def is_frozen() -> bool:
25 """Return True when running from a frozen PyInstaller bundle."""
26 return bool(getattr(sys, "frozen", False))
29def detached_subprocess_env(
30 environ: Mapping[str, str] | None = None,
31) -> dict[str, str] | None:
32 """Environment for a detached child process spawned by a frozen binary.
34 A PyInstaller ``--onefile`` executable unpacks its bundled runtime into a
35 temporary ``_MEI*`` directory and removes that directory when the parent
36 process exits. Setting ``PYINSTALLER_RESET_ENVIRONMENT=1`` ensures any
37 detached child process (such as ``ai_shell.cdp_relay``) initializes its own
38 independent runtime directory instead of inheriting the expiring one.
40 Returns ``None`` when not running from a frozen bundle so callers leave the
41 default subprocess environment untouched.
42 """
43 if not is_frozen():
44 return None
45 base = os.environ if environ is None else environ
46 return {**base, "PYINSTALLER_RESET_ENVIRONMENT": "1"}
49def persistent_asset_path(
50 bundled_path: Path,
51 relative_dest: str,
52 *,
53 cache_root: Path | None = None,
54) -> Path:
55 """Return a host-persistent path for an asset that Docker bind-mounts.
57 In a standard Python install, *bundled_path* lives inside ``site-packages``
58 on disk and can be bind-mounted directly into long-running containers.
59 In a frozen ``--onefile`` binary, *bundled_path* lives inside the temporary
60 ``_MEI*`` directory that is deleted as soon as the CLI process exits.
61 Staging the asset under ``~/.cache/ai-shell/runtime-assets/<version>/``
62 keeps bind mounts valid for detached containers and across container
63 restarts.
64 """
65 if not is_frozen() or not bundled_path.exists():
66 return bundled_path
68 root = (
69 cache_root
70 if cache_root is not None
71 else Path.home() / ".cache" / "ai-shell" / "runtime-assets"
72 )
73 target = root / __version__ / relative_dest
75 if bundled_path.is_dir():
76 target.parent.mkdir(parents=True, exist_ok=True)
77 shutil.copytree(bundled_path, target, dirs_exist_ok=True)
78 return target
80 target.parent.mkdir(parents=True, exist_ok=True)
81 shutil.copy2(bundled_path, target)
82 return target
85def binary_artifact_name(
86 system: str | None = None,
87 machine: str | None = None,
88) -> str:
89 """Return the canonical release artifact filename for the target platform."""
90 raw_sys = (system or platform.system()).strip().lower()
91 raw_arch = (machine or platform.machine()).strip().lower()
93 os_map = {
94 "linux": "linux",
95 "darwin": "macos",
96 "macos": "macos",
97 "windows": "windows",
98 "win32": "windows",
99 }
100 arch_map = {
101 "x86_64": "x86_64",
102 "amd64": "x86_64",
103 "aarch64": "arm64",
104 "arm64": "arm64",
105 }
107 norm_os = os_map.get(raw_sys, raw_sys or "unknown")
108 norm_arch = arch_map.get(raw_arch, raw_arch or "unknown")
109 suffix = ".exe" if norm_os == "windows" else ""
110 return f"ai-shell-{norm_os}-{norm_arch}{suffix}"
113def default_entry_script() -> Path:
114 """Return the path to the CLI entry script used by PyInstaller."""
115 return Path(__file__).resolve().parent / "cli" / "__main__.py"
118def pyinstaller_args(
119 *,
120 output: Path | None = None,
121 entry_script: Path | None = None,
122 workpath: Path | None = None,
123 specpath: Path | None = None,
124) -> list[str]:
125 """Build the PyInstaller argument list for a single-file ``ai-shell`` binary."""
126 target = output if output is not None else Path("dist") / "ai-shell"
127 script = entry_script if entry_script is not None else default_entry_script()
129 name = target.stem if target.suffix.lower() == ".exe" else target.name
130 dist_dir = target.parent if str(target.parent) else Path(".")
132 args = [
133 "--onefile",
134 "--clean",
135 "--noconfirm",
136 "--name",
137 name,
138 "--distpath",
139 str(dist_dir),
140 "--collect-submodules",
141 "ai_shell",
142 "--collect-data",
143 "ai_shell",
144 "--collect-submodules",
145 "rich._unicode_data",
146 "--copy-metadata",
147 "augint-shell",
148 ]
149 for mod in (
150 "tkinter",
151 "_tkinter",
152 "pytest",
153 "mypy",
154 "ruff",
155 "semgrep",
156 "bandit",
157 "pdoc",
158 ):
159 args.extend(["--exclude-module", mod])
160 if workpath is not None:
161 args.extend(["--workpath", str(workpath)])
162 if specpath is not None:
163 args.extend(["--specpath", str(specpath)])
164 args.append(str(script))
165 return args
168def build_standalone_binary(output: Path | None = None) -> Path:
169 """Compile ``ai-shell`` into a standalone single-file binary using PyInstaller."""
170 import importlib
172 try:
173 pyinstaller_main = importlib.import_module("PyInstaller.__main__")
174 except ImportError as exc:
175 raise RuntimeError(
176 "PyInstaller is required to build the standalone binary. "
177 "Run with: uv run --with pyinstaller python -m ai_shell.standalone"
178 ) from exc
180 if output is None:
181 exe_name = "ai-shell.exe" if platform.system() == "Windows" else "ai-shell"
182 target = Path("dist") / exe_name
183 else:
184 target = output
186 target.parent.mkdir(parents=True, exist_ok=True)
188 with tempfile.TemporaryDirectory(prefix="ai-shell-pyinstaller-") as tmp_dir:
189 tmp_path = Path(tmp_dir)
190 args = pyinstaller_args(
191 output=target,
192 workpath=tmp_path / "build",
193 specpath=tmp_path / "spec",
194 )
195 pyinstaller_main.run(args)
197 expected = target
198 if (
199 platform.system() == "Windows"
200 and expected.suffix.lower() != ".exe"
201 and not expected.exists()
202 and expected.with_suffix(".exe").exists()
203 ):
204 expected = expected.with_suffix(".exe")
206 if not expected.is_file():
207 raise RuntimeError(f"Standalone binary was not created at {expected}")
208 return expected
211def main(argv: list[str] | None = None) -> int:
212 """CLI entrypoint for building the standalone ``ai-shell`` executable."""
213 parser = argparse.ArgumentParser(
214 prog="python -m ai_shell.standalone",
215 description="Build a standalone single-file ai-shell executable.",
216 )
217 parser.add_argument(
218 "--output",
219 "-o",
220 type=Path,
221 default=None,
222 help="Output path for the compiled binary (default: dist/ai-shell[.exe]).",
223 )
224 parser.add_argument(
225 "--artifact-name",
226 action="store_true",
227 help="Print the platform-specific release artifact filename and exit.",
228 )
229 args = parser.parse_args(argv)
231 if args.artifact_name:
232 print(binary_artifact_name())
233 return 0
235 try:
236 built = build_standalone_binary(args.output)
237 except RuntimeError as exc:
238 print(f"Error: {exc}", file=sys.stderr)
239 return 1
241 print(f"Built standalone binary: {built}")
242 return 0
245if __name__ == "__main__": # pragma: no cover
246 sys.exit(main())