__init__.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. """Locate and execute the bundled dsh CLI shipped with the Python SDK runtime.
  2. Two runtime carriers coexist under ``runtime/``, both injected by the repo's
  3. ``scripts/build-exe-for-python-sdk.ts`` build (neither is checked into git):
  4. - **exe (production)**: single-file Node executables named
  5. ``deepseek-harness-sdk-runtime-<platform>-<arch>`` for Linux/macOS and an
  6. ``.exe`` counterpart for Windows. Each has a sibling ripgrep executable;
  7. macOS also uses a sibling ``-spawn-helper``. The target machine needs no
  8. Node installation.
  9. - **node (dev-only)**: the full deploy closure under ``runtime/node/``
  10. (``package.json`` + ``node_modules/``), executed as ``node
  11. runtime/node/node_modules/@deepseek-ai/dsh/lib/bin.js`` on a
  12. system Node >= 22.19. It is the current checkout's source build, never
  13. selected automatically, and excluded from wheel/sdist distributions.
  14. Both carriers execute the same dsh command grammar. The Python SDK selects the
  15. ``sdk`` profile and requires an explicit Harness home; the installed ``dsh``
  16. console command requires ``DSH_HOME`` for the same reason.
  17. """
  18. from __future__ import annotations
  19. import os
  20. import platform
  21. import shutil
  22. import subprocess
  23. import sys
  24. from pathlib import Path
  25. PACKAGE_METADATA_FILENAME = "deepseek-harness-runtime.json"
  26. RUNTIME_MODE_ENV_VAR = "DSH_RUNTIME_MODE"
  27. _PLATFORM_TAGS = {"linux": "linux", "darwin": "macos", "win32": "win"}
  28. _ARCH_TAGS = {"x86_64": "x64", "amd64": "x64", "arm64": "arm64", "aarch64": "arm64"}
  29. _EXE_ACQUISITION_HINT = (
  30. "Two ways to get the executable: run `scripts/build-exe-for-python-sdk.ts` (via tsx) in a "
  31. "deepseek-harness checkout, or install the matching `deepseek-harness-runtime-bin` platform "
  32. "wheel retained by the `build-exe-for-python-sdk` CI workflow. For local development "
  33. "against a repo source build, explicitly select the dev-only node carrier with "
  34. f"{RUNTIME_MODE_ENV_VAR}=node (or resolve_bundled_launch_args('node'))."
  35. )
  36. def bundled_package_dir() -> Path:
  37. """Root directory of the installed runtime package data (the directory of this module)."""
  38. root = Path(__file__).resolve().parent
  39. metadata = root / PACKAGE_METADATA_FILENAME
  40. if not metadata.is_file():
  41. raise FileNotFoundError(f"deepseek-harness-runtime-bin is missing {metadata}")
  42. return root
  43. def bundled_runtime_path() -> Path:
  44. """Absolute path of the bundled single-file runtime executable for the current platform.
  45. Raises FileNotFoundError when the platform is unsupported, the executable
  46. has not been placed into this package, the required ripgrep sidecar is
  47. missing, or the required macOS spawn helper is missing; the message names
  48. the acquisition routes (acquisition strategy is deliberately separate from
  49. this lookup interface, so an on-demand download can replace it without
  50. touching callers).
  51. """
  52. tag = _current_platform_tag()
  53. extension = ".exe" if tag.startswith("win-") else ""
  54. path = bundled_package_dir() / "runtime" / f"deepseek-harness-sdk-runtime-{tag}{extension}"
  55. if not path.is_file():
  56. raise FileNotFoundError(
  57. f"deepseek-harness-runtime-bin is missing the runtime executable at {path}. "
  58. + _EXE_ACQUISITION_HINT
  59. )
  60. ripgrep = (
  61. path.with_name(f"{path.stem}-rg.exe")
  62. if tag.startswith("win-")
  63. else Path(f"{path}-rg")
  64. )
  65. if not ripgrep.is_file():
  66. raise FileNotFoundError(
  67. f"deepseek-harness-runtime-bin is missing the ripgrep sidecar at {ripgrep}. "
  68. + _EXE_ACQUISITION_HINT
  69. )
  70. if tag.startswith("macos-"):
  71. helper = Path(f"{path}-spawn-helper")
  72. if not helper.is_file():
  73. raise FileNotFoundError(
  74. f"deepseek-harness-runtime-bin is missing the node-pty spawn helper at {helper}. "
  75. + _EXE_ACQUISITION_HINT
  76. )
  77. return path
  78. def resolve_bundled_launch_args(mode: str | None = None) -> tuple[str, ...]:
  79. """The argv tuple that launches the bundled runtime.
  80. Mode selection: the explicit ``mode`` argument wins, then the
  81. ``DSH_RUNTIME_MODE`` environment variable (``exe`` | ``node``), then
  82. automatic resolution. Automatic resolution finds the production exe ONLY —
  83. the dev-only node carrier must be selected explicitly so a production
  84. deployment can never silently ride on a source build. Returns
  85. ``(exe_path,)`` in exe mode and ``(node_path, bin_js_path)`` in node mode;
  86. raises FileNotFoundError when the selected carrier is unavailable and
  87. ValueError for an unknown mode value.
  88. """
  89. selected = mode if mode is not None else os.environ.get(RUNTIME_MODE_ENV_VAR)
  90. if selected is None or selected == "exe":
  91. return (str(bundled_runtime_path()),)
  92. if selected == "node":
  93. return _node_launch_args()
  94. raise ValueError(
  95. f"unsupported DeepSeek Harness runtime mode {selected!r}: expected 'exe' or 'node' "
  96. f"(explicit argument or ${RUNTIME_MODE_ENV_VAR})"
  97. )
  98. def _current_platform_tag() -> str:
  99. plat = _PLATFORM_TAGS.get(sys.platform)
  100. arch = _ARCH_TAGS.get(platform.machine().lower())
  101. if (
  102. plat is None
  103. or arch is None
  104. or (plat == "win" and arch != "x64")
  105. ):
  106. raise FileNotFoundError(
  107. "no bundled DeepSeek Harness SDK runtime exists for this platform "
  108. f"(sys.platform={sys.platform!r}, machine={platform.machine()!r}); supported: "
  109. "Linux x64/arm64, macOS x64/arm64, and Windows x64. " + _EXE_ACQUISITION_HINT
  110. )
  111. return f"{plat}-{arch}"
  112. def _node_launch_args() -> tuple[str, str]:
  113. node_root = bundled_package_dir() / "runtime" / "node"
  114. bin_js = (
  115. node_root
  116. / "node_modules"
  117. / "@deepseek-ai"
  118. / "dsh"
  119. / "lib"
  120. / "bin.js"
  121. )
  122. if not bin_js.is_file():
  123. raise FileNotFoundError(
  124. f"the dev-only node runtime closure is missing at {node_root} "
  125. f"(no {bin_js}); run `scripts/build-exe-for-python-sdk.ts` in a deepseek-harness "
  126. "checkout, which builds and copies the deploy closure here. The node carrier "
  127. "is for repo-local development only — production uses the single-file exe."
  128. )
  129. node = shutil.which("node")
  130. if node is None:
  131. raise FileNotFoundError(
  132. "the node runtime mode needs a system `node` (>=22.19) on PATH; "
  133. "install Node.js or use the exe mode"
  134. )
  135. return (node, str(bin_js))
  136. def main() -> None:
  137. """Launch the CLI with explicit DSH_HOME; wait on Windows, replace the process on POSIX."""
  138. if not os.environ.get("DSH_HOME", "").strip():
  139. print(
  140. "dsh: the Python runtime command requires an explicit DSH_HOME; "
  141. "it never uses ~/.dsh implicitly",
  142. file=sys.stderr,
  143. )
  144. raise SystemExit(2)
  145. argv = (*resolve_bundled_launch_args(), *sys.argv[1:])
  146. if sys.platform == "win32":
  147. # Windows CRT exec does not replace the process; wait and preserve the runtime status.
  148. raise SystemExit(subprocess.run(argv, env=os.environ).returncode)
  149. os.execvpe(argv[0], argv, os.environ)
  150. __all__ = [
  151. "PACKAGE_METADATA_FILENAME",
  152. "RUNTIME_MODE_ENV_VAR",
  153. "bundled_package_dir",
  154. "bundled_runtime_path",
  155. "main",
  156. "resolve_bundled_launch_args",
  157. ]