Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions packages/prime-tunnel/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Prime Intellect

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
51 changes: 51 additions & 0 deletions packages/prime-tunnel/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Prime Tunnel SDK

Expose local services via secure tunnels on Prime infrastructure.

## Installation

```bash
uv pip install prime-tunnel
```

Or with pip:

```bash
pip install prime-tunnel
```

## Quick Start

```python
from prime_tunnel import Tunnel

# Create and start a tunnel
async with Tunnel(local_port=8765) as tunnel:
print(f"Tunnel URL: {tunnel.url}")
# Your local service on port 8765 is now accessible at tunnel.url
```

## CLI Usage

```bash
# Start a tunnel
prime tunnel start --port 8765

# List active tunnels
prime tunnel list

# Get tunnel status
prime tunnel status <tunnel_id>
```

## Documentation

Full API reference: https://github.com/PrimeIntellect-ai/prime-cli/tree/main/packages/prime-tunnel

## Related Packages

- **`prime`** - Full CLI + SDK with pods, inference, and more (includes this package)

## License

MIT License - see LICENSE file for details
62 changes: 62 additions & 0 deletions packages/prime-tunnel/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
[project]
name = "prime-tunnel"
# Version is single-sourced from src/prime_tunnel/__init__.py via Hatch
dynamic = ["version"]
description = "Prime Intellect Tunnel SDK - Expose local services via secure tunnels"
readme = "README.md"
requires-python = ">=3.10"
license = {text = "MIT"}
authors = [
{ name = "Prime Intellect", email = "contact@primeintellect.ai" }
]
dependencies = [
"httpx>=0.25.0",
"pydantic>=2.0.0",
"tenacity>=8.0.0",
]
keywords = ["tunnel", "reverse-proxy", "networking", "frp", "sdk"]
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Topic :: Software Development :: Libraries :: Python Modules"
]

[project.urls]
Homepage = "https://github.com/PrimeIntellect-ai/prime-cli"
Documentation = "https://github.com/PrimeIntellect-ai/prime-cli/tree/main/packages/prime-tunnel"
Repository = "https://github.com/PrimeIntellect-ai/prime-cli.git"

[project.optional-dependencies]
dev = [
"pytest>=7.0.0",
"pytest-xdist>=3.0.0",
"pytest-asyncio>=0.23.0",
"ruff>=0.13.1",
]

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.version]
path = "src/prime_tunnel/__init__.py"

[tool.hatch.build.targets.wheel]
packages = ["src/prime_tunnel"]

[tool.pytest.ini_options]
addopts = "-v"
testpaths = ["tests"]

[tool.ruff]
line-length = 100
target-version = "py310"

[tool.ruff.lint]
extend-select = ["E", "F", "I"]
30 changes: 30 additions & 0 deletions packages/prime-tunnel/src/prime_tunnel/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Prime Tunnel SDK - Expose local services via secure tunnels."""

__version__ = "0.1.0"

from prime_tunnel.core import Config, TunnelClient
from prime_tunnel.exceptions import (
TunnelAuthError,
TunnelConnectionError,
TunnelError,
TunnelTimeoutError,
)
from prime_tunnel.models import TunnelConfig, TunnelInfo
from prime_tunnel.tunnel import Tunnel

__all__ = [
"__version__",
# Core
"Config",
"TunnelClient",
# Main interface
"Tunnel",
# Models
"TunnelConfig",
"TunnelInfo",
# Exceptions
"TunnelError",
"TunnelAuthError",
"TunnelConnectionError",
"TunnelTimeoutError",
]
155 changes: 155 additions & 0 deletions packages/prime-tunnel/src/prime_tunnel/binary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import hashlib
import os
import platform
import shutil
import stat
import tarfile
import tempfile
from pathlib import Path

import httpx

from prime_tunnel.core.config import Config
from prime_tunnel.exceptions import BinaryDownloadError

FRPC_VERSION = "0.66.0"
FRPC_URLS = {
(
"Darwin",
"arm64",
): f"https://github.com/fatedier/frp/releases/download/v{FRPC_VERSION}/frp_{FRPC_VERSION}_darwin_arm64.tar.gz",
(
"Darwin",
"x86_64",
): f"https://github.com/fatedier/frp/releases/download/v{FRPC_VERSION}/frp_{FRPC_VERSION}_darwin_amd64.tar.gz",
(
"Linux",
"x86_64",
): f"https://github.com/fatedier/frp/releases/download/v{FRPC_VERSION}/frp_{FRPC_VERSION}_linux_amd64.tar.gz",
(
"Linux",
"aarch64",
): f"https://github.com/fatedier/frp/releases/download/v{FRPC_VERSION}/frp_{FRPC_VERSION}_linux_arm64.tar.gz",
(
"Linux",
"arm64",
): f"https://github.com/fatedier/frp/releases/download/v{FRPC_VERSION}/frp_{FRPC_VERSION}_linux_arm64.tar.gz",
}
FRPC_CHECKSUMS = {
("Darwin", "arm64"): None, # TODO: Add checksums
("Darwin", "x86_64"): None,
("Linux", "x86_64"): None,
("Linux", "aarch64"): None,
("Linux", "arm64"): None,
}


def _get_platform_key() -> tuple[str, str]:
system = platform.system()
machine = platform.machine()

if machine in ("AMD64", "x86_64"):
machine = "x86_64"
elif machine in ("arm64", "aarch64"):
machine = "arm64" if system == "Darwin" else "aarch64"

return (system, machine)


def _download_frpc(dest: Path) -> None:
platform_key = _get_platform_key()
url = FRPC_URLS.get(platform_key)

if not url:
raise BinaryDownloadError(f"Unsupported platform: {platform_key[0]} {platform_key[1]}")

expected_checksum = FRPC_CHECKSUMS.get(platform_key)

with tempfile.TemporaryDirectory() as tmpdir:
tmpdir_path = Path(tmpdir)
archive_path = tmpdir_path / "frp.tar.gz"

try:
with httpx.stream("GET", url, follow_redirects=True, timeout=120.0) as response:
response.raise_for_status()
with open(archive_path, "wb") as f:
for chunk in response.iter_bytes(chunk_size=8192):
f.write(chunk)

except httpx.HTTPError as e:
raise BinaryDownloadError(f"Failed to download frpc: {e}") from e

if expected_checksum:
actual_checksum = _compute_sha256(archive_path)
if actual_checksum != expected_checksum:
raise BinaryDownloadError(
f"Checksum mismatch: expected {expected_checksum}, got {actual_checksum}"
)

try:
with tarfile.open(archive_path, "r:gz") as tar:
for member in tar.getmembers():
if member.name.endswith("/frpc") or member.name == "frpc":
member.name = "frpc"
tar.extract(member, tmpdir_path)
break
else:
raise BinaryDownloadError("frpc binary not found in archive")

except tarfile.TarError as e:
raise BinaryDownloadError(f"Failed to extract frpc: {e}") from e

extracted_path = tmpdir_path / "frpc"
if not extracted_path.exists():
raise BinaryDownloadError("frpc binary not found after extraction")

dest.parent.mkdir(parents=True, exist_ok=True)

# Set executable permissions on extracted file before moving
extracted_path.chmod(
extracted_path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
)

# Copy to temp file in same directory, then rename
# This prevents corruption if multiple processes download simultaneously
temp_dest = dest.parent / f".frpc.{os.getpid()}.tmp"
try:
shutil.copy2(extracted_path, temp_dest)
os.replace(temp_dest, dest) # Atomic on POSIX
finally:
# Clean up temp file if rename failed
if temp_dest.exists():
temp_dest.unlink()


def _compute_sha256(path: Path) -> str:
sha256 = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
sha256.update(chunk)
return sha256.hexdigest()


def get_frpc_path() -> Path:
config = Config()
frpc_path = config.bin_dir / "frpc"
version_file = config.bin_dir / ".frpc_version"

if frpc_path.exists():
if version_file.exists():
current_version = version_file.read_text().strip()
if current_version == FRPC_VERSION:
return frpc_path

_download_frpc(frpc_path)

# Write to temp file in same directory, then rename to prevent partial reads
temp_version = version_file.parent / f".frpc_version.{os.getpid()}.tmp"
try:
temp_version.write_text(FRPC_VERSION)
os.replace(temp_version, version_file)
finally:
if temp_version.exists():
temp_version.unlink()

return frpc_path
6 changes: 6 additions & 0 deletions packages/prime-tunnel/src/prime_tunnel/core/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"""Prime Tunnel Core - HTTP client and configuration."""

from prime_tunnel.core.client import TunnelClient
from prime_tunnel.core.config import Config

__all__ = ["Config", "TunnelClient"]
Loading