__init__.py 7.0 KB

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