feat(update): integrate managed installs and recoverable in-app updates (#6168)
Add owner-aware Stable and Preview updates with explicit consent, verified release plans, protected process handoff and bounded service recovery. Keep configuration and conversations separate from program rollback. Include the compact About controls, Windows long-path support, native package recovery checks and optional macOS Dock lifecycle integration. Preserve documented guidance for installations owned by other managers. This code integration does not publish packages, enable signing or advance the public update channel. Co-authored-by: chengyongru <61816729+chengyongru@users.noreply.github.com>
This commit is contained in:
1 parent
76da55994b
commit
fbb61a373f
216 files changed
+27948
-1084
No files matched your search
+32
-28
@@ -21,27 +21,22 @@ import zipfile
|
||||
from email.parser import BytesParser
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
from nanobot.cli.tui_launcher import _verified_release_archive
|
||||
# Packaging must use the same archive checks as the installed launcher.
|
||||
from nanobot.cli.tui_launcher import (
|
||||
_verified_release_archive, # pyright: ignore[reportPrivateUsage]
|
||||
)
|
||||
from nanobot.releases import PLATFORMS
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
# Minimums verified against BOTH the Bun executable and its embedded OpenTUI library.
|
||||
# Linux binaries use glibc, not musl; macOS binaries require macOS 13.
|
||||
PLATFORMS = {
|
||||
"darwin-arm64": "macosx_13_0_arm64",
|
||||
"darwin-x64": "macosx_13_0_x86_64",
|
||||
"linux-arm64": "manylinux_2_17_aarch64",
|
||||
"linux-x64": "manylinux_2_17_x86_64",
|
||||
"win32-x64": "win_amd64",
|
||||
}
|
||||
|
||||
|
||||
def _digest(data: bytes) -> str:
|
||||
return "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(data).digest()).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def _source_files(raw: bytes) -> dict[str, bytes]:
|
||||
def source_files(raw: bytes) -> dict[str, bytes]:
|
||||
"""Compare archive contents without extracting any untrusted path to disk."""
|
||||
files = {}
|
||||
files: dict[str, bytes] = {}
|
||||
with tarfile.open(fileobj=io.BytesIO(raw), mode="r:gz") as archive:
|
||||
for member in archive:
|
||||
if member.isdir():
|
||||
@@ -73,10 +68,12 @@ def _verify_architecture(binary: bytes, target: str) -> None:
|
||||
raise ValueError(f"TUI executable architecture does not match {target}")
|
||||
|
||||
|
||||
def _base_files(wheel: Path, version: str) -> tuple[dict[str, bytes], dict[str, int], str]:
|
||||
def wheel_files(wheel: Path, version: str, *, platform: str = "any") -> tuple[dict[str, bytes], dict[str, int], str]:
|
||||
"""Verify identity and every RECORD entry for an intermediate or final wheel."""
|
||||
prefix = f"nanobot_ai-{version}"
|
||||
if wheel.name != f"{prefix}-py3-none-any.whl":
|
||||
raise ValueError(f"Expected the candidate's universal wheel ({version})")
|
||||
if wheel.name != f"{prefix}-py3-none-{platform}.whl":
|
||||
kind = "universal wheel" if platform == "any" else "platform wheel"
|
||||
raise ValueError(f"Expected the candidate's {kind} ({version})")
|
||||
info_dir = f"{prefix}.dist-info"
|
||||
with zipfile.ZipFile(wheel) as archive:
|
||||
names = archive.namelist()
|
||||
@@ -85,7 +82,7 @@ def _base_files(wheel: Path, version: str) -> tuple[dict[str, bytes], dict[str,
|
||||
for name in names:
|
||||
path = PurePosixPath(name)
|
||||
if (path.is_absolute() or ".." in path.parts or "\\" in name
|
||||
or name.startswith("nanobot/tui/bin/")
|
||||
or (platform == "any" and name.startswith("nanobot/tui/bin/"))
|
||||
or name.endswith(("/RECORD.jws", "/RECORD.p7s"))):
|
||||
raise ValueError(f"Unexpected base wheel entry: {name}")
|
||||
files = {name: archive.read(name) for name in names if not name.endswith("/")}
|
||||
@@ -93,8 +90,8 @@ def _base_files(wheel: Path, version: str) -> tuple[dict[str, bytes], dict[str,
|
||||
metadata = BytesParser().parsebytes(files[f"{info_dir}/METADATA"])
|
||||
wheel_metadata = BytesParser().parsebytes(files[f"{info_dir}/WHEEL"])
|
||||
if (metadata["Name"] != "nanobot-ai" or metadata["Version"] != version
|
||||
or wheel_metadata["Root-Is-Purelib"] != "true"
|
||||
or wheel_metadata.get_all("Tag") != ["py3-none-any"]):
|
||||
or wheel_metadata["Root-Is-Purelib"] != ("true" if platform == "any" else "false")
|
||||
or wheel_metadata.get_all("Tag") != [f"py3-none-{platform}"]):
|
||||
raise ValueError("Base wheel metadata does not match the candidate")
|
||||
record = f"{info_dir}/RECORD"
|
||||
rows = list(csv.reader(io.StringIO(files[record].decode())))
|
||||
@@ -107,15 +104,8 @@ def _base_files(wheel: Path, version: str) -> tuple[dict[str, bytes], dict[str,
|
||||
return files, modes, info_dir
|
||||
|
||||
|
||||
def build_wheel(wheel: Path, tui_dir: Path, out_dir: Path, target: str, *,
|
||||
root: Path = ROOT) -> Path:
|
||||
"""Fail closed on stale sources, damaged archives, or existing output files."""
|
||||
version = tomllib.loads((root / "pyproject.toml").read_text())["project"]["version"]
|
||||
tag = f"py3-none-{PLATFORMS[target]}"
|
||||
output = out_dir / f"nanobot_ai-{version}-{tag}.whl"
|
||||
if output.exists():
|
||||
raise FileExistsError(output)
|
||||
files, modes, info_dir = _base_files(wheel, version)
|
||||
def release_bundle(tui_dir: Path, target: str, *, root: Path = ROOT) -> dict[str, bytes]:
|
||||
"""Validate the archive, architecture and corresponding source once at its owner."""
|
||||
asset = f"nanobot-tui-{target}" + (".exe" if target.startswith("win32-") else "")
|
||||
archive = tui_dir / f"{asset}.zip"
|
||||
raw = archive.read_bytes()
|
||||
@@ -130,8 +120,22 @@ def build_wheel(wheel: Path, tui_dir: Path, out_dir: Path, target: str, *,
|
||||
source_packager = runpy.run_path(str(root / "tui/scripts/package-release.py"))
|
||||
source_packager["_validate_opentui_version"](root / "tui", notices)
|
||||
expected_source = source_packager["_source_archive"](root / "tui")
|
||||
if _source_files(bundle["nanobot-tui-source.tar.gz"]) != _source_files(expected_source):
|
||||
if source_files(bundle["nanobot-tui-source.tar.gz"]) != source_files(expected_source):
|
||||
raise ValueError("TUI archive source does not match this release checkout; rebuild it")
|
||||
return bundle
|
||||
|
||||
|
||||
def build_wheel(wheel: Path, tui_dir: Path, out_dir: Path, target: str, *,
|
||||
root: Path = ROOT) -> Path:
|
||||
"""Fail closed on stale sources, damaged archives, or existing output files."""
|
||||
version = tomllib.loads((root / "pyproject.toml").read_text())["project"]["version"]
|
||||
tag = f"py3-none-{PLATFORMS[target]}"
|
||||
output = out_dir / f"nanobot_ai-{version}-{tag}.whl"
|
||||
if output.exists():
|
||||
raise FileExistsError(output)
|
||||
files, modes, info_dir = wheel_files(wheel, version)
|
||||
asset = f"nanobot-tui-{target}" + (".exe" if target.startswith("win32-") else "")
|
||||
bundle = release_bundle(tui_dir, target, root=root)
|
||||
for name, content in bundle.items():
|
||||
path = f"nanobot/tui/bin/{name}"
|
||||
files[path] = content
|
||||
|
||||
@@ -51,6 +51,32 @@ _TOOL_CONFIG_MODULES = (
|
||||
)
|
||||
|
||||
IMPORT_RULES = (
|
||||
ImportRule(
|
||||
"update-policy-direction",
|
||||
("nanobot.agent", "nanobot.session", "nanobot.runtime_admission",
|
||||
"nanobot.data_access", "nanobot.installation_lock"),
|
||||
("nanobot.update_service", "nanobot.update_plan", "nanobot.update_jobs",
|
||||
"nanobot.update_worker", "nanobot.update_stop", "nanobot.update_restart"),
|
||||
),
|
||||
ImportRule(
|
||||
"update-domain",
|
||||
("nanobot.update_service", "nanobot.update_plan", "nanobot.update_jobs",
|
||||
"nanobot.update_worker", "nanobot.update_stop",
|
||||
"nanobot.update_profiles", "nanobot.update_handoff", "nanobot.update_guidance"),
|
||||
("nanobot.agent", "nanobot.session", "nanobot.api", "nanobot.cli",
|
||||
"nanobot.channels", "nanobot.webui"),
|
||||
),
|
||||
ImportRule(
|
||||
"update-restart-adapter",
|
||||
("nanobot.update_restart",),
|
||||
(*_ADAPTERS, "nanobot.agent", "nanobot.session"),
|
||||
# This protected-startup entry composes the existing CLI, not a second
|
||||
# agent runtime. Keep its frozen worker entry and launch semantics stable.
|
||||
allowed_targets=("nanobot.gateway.runtime", "nanobot.cli.gateway_runtime._run_gateway",
|
||||
"nanobot.cli.entry.configure_windows_console",
|
||||
"nanobot.cli.process_identity.set_cli_process_identity",
|
||||
"nanobot.cli.runtime_config._load_runtime_config"),
|
||||
),
|
||||
ImportRule(
|
||||
"core-execution",
|
||||
("nanobot.agent.loop", "nanobot.agent.runner", "nanobot.agent.turn_delivery"),
|
||||
|
||||
+419
-76
@@ -1,6 +1,10 @@
|
||||
param(
|
||||
[switch]$Dev,
|
||||
[switch]$DryRun,
|
||||
[string]$Wheel,
|
||||
[string]$Sha256,
|
||||
[string]$Release,
|
||||
[string]$ManifestSha256,
|
||||
[Parameter(ValueFromRemainingArguments = $true)]
|
||||
[string[]]$RemainingArgs
|
||||
)
|
||||
@@ -10,9 +14,8 @@ $ErrorActionPreference = "Stop"
|
||||
$Package = "nanobot-ai"
|
||||
$InstallTarget = $Package
|
||||
$InstallSource = "PyPI"
|
||||
$script:NanobotRunner = $null
|
||||
$script:NanobotPython = $null
|
||||
$script:LastInstallSucceeded = $false
|
||||
$ExpectedVersion = ""
|
||||
|
||||
function Write-Info {
|
||||
param([string]$Message)
|
||||
@@ -26,6 +29,9 @@ function Fail {
|
||||
|
||||
function Show-InstallFailureHint {
|
||||
[Console]::Error.WriteLine("Error: could not install nanobot from $InstallSource.")
|
||||
if ($ExpectedVersion) {
|
||||
Fail "Inspect the original manager error and retry this exact handoff. No setup or other installation was attempted."
|
||||
}
|
||||
[Console]::Error.WriteLine("If pip mentioned externally-managed-environment, use uv, pipx, or a virtual environment instead of system pip.")
|
||||
[Console]::Error.WriteLine("You can also run manually:")
|
||||
[Console]::Error.WriteLine(" uv tool install --force --upgrade $InstallTarget")
|
||||
@@ -37,10 +43,14 @@ function Show-InstallFailureHint {
|
||||
}
|
||||
|
||||
function Show-Usage {
|
||||
Write-Host "Usage: install.ps1 [-DryRun|--dry-run]"
|
||||
Write-Host "Usage: install.ps1 [-DryRun|--dry-run] [-Wheel PATH -Sha256 HASH]"
|
||||
Write-Host " install.ps1 [-DryRun|--dry-run] -Release VERSION -ManifestSha256 HASH"
|
||||
Write-Host ""
|
||||
Write-Host "By default this installs or upgrades nanobot-ai from PyPI."
|
||||
Write-Host "Use --dry-run to print what would happen without installing or starting setup."
|
||||
Write-Host "Use -Wheel and -Sha256 together for a verified release handoff; retain the downloaded wheel."
|
||||
Write-Host "Stop affected gateways and back up their data before updating an existing install."
|
||||
Write-Host "-Release downloads the matching official wheel; it is one version, not a Preview subscription."
|
||||
Write-Host ""
|
||||
Write-Host "For current main, clone the repository and run 'python -m pip install -e .'."
|
||||
}
|
||||
@@ -87,6 +97,39 @@ function Test-VirtualEnv {
|
||||
}
|
||||
}
|
||||
|
||||
function Get-InstallMethod {
|
||||
if (Test-VirtualEnv $Python) {
|
||||
$ActivePrefix = & $Python -I -c "import json, sys; print(json.dumps(sys.prefix))" | ConvertFrom-Json
|
||||
if ((Test-Path -LiteralPath (Join-Path $ActivePrefix "uv-receipt.toml")) -or
|
||||
(Test-Path -LiteralPath (Join-Path $ActivePrefix "pipx_metadata.json"))) {
|
||||
Fail "The active Python belongs to uv or pipx. Deactivate it and rerun this installer so its manager owns the update."
|
||||
}
|
||||
return "python"
|
||||
}
|
||||
|
||||
$Existing = @()
|
||||
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
||||
$ToolDir = & uv tool dir
|
||||
if ($LASTEXITCODE -ne 0 -or -not $ToolDir) { Fail "Could not inspect the uv tools directory." }
|
||||
if (Test-Path -LiteralPath (Join-Path $ToolDir $Package)) { $Existing += "uv" }
|
||||
}
|
||||
if (Get-Command pipx -ErrorAction SilentlyContinue) {
|
||||
$ToolDir = & pipx environment --value PIPX_LOCAL_VENVS
|
||||
if ($LASTEXITCODE -ne 0 -or -not $ToolDir) { Fail "Could not inspect the pipx environments directory." }
|
||||
if (Test-Path -LiteralPath (Join-Path $ToolDir $Package)) { $Existing += "pipx" }
|
||||
}
|
||||
$ProfileDir = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }
|
||||
if ($env:NANOBOT_VENV -or $ProfileDir) {
|
||||
$Environment = if ($env:NANOBOT_VENV) { $env:NANOBOT_VENV } else { Join-Path $ProfileDir ".nanobot\venv" }
|
||||
if (Test-Path -LiteralPath (Join-Path $Environment "pyvenv.cfg")) { $Existing += "managed" }
|
||||
}
|
||||
if ($Existing.Count -gt 1) {
|
||||
Fail "Multiple nanobot installations were found. Use the intended environment's package manager; this installer changed none of them."
|
||||
}
|
||||
if ($Existing.Count -eq 1) { return $Existing[0] }
|
||||
return "managed"
|
||||
}
|
||||
|
||||
function Ensure-Pip {
|
||||
param([string]$Command)
|
||||
|
||||
@@ -105,35 +148,45 @@ function Ensure-Pip {
|
||||
}
|
||||
}
|
||||
|
||||
function Select-InstalledPython {
|
||||
param([string]$Command, [string]$ExpectedEnvironment = "")
|
||||
|
||||
$Probe = @'
|
||||
import json
|
||||
import sys
|
||||
from importlib.metadata import distribution
|
||||
from pathlib import Path
|
||||
|
||||
import nanobot
|
||||
|
||||
prefix = Path(sys.prefix).resolve()
|
||||
package = Path(nanobot.__file__).resolve()
|
||||
expected = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
if sys.prefix == sys.base_prefix or (expected not in ("", "-") and prefix != Path(expected).resolve()):
|
||||
raise SystemExit("The installed interpreter does not belong to the expected virtual environment")
|
||||
if not package.is_relative_to(prefix) or package != Path(distribution("nanobot-ai").locate_file("nanobot/__init__.py")).resolve():
|
||||
raise SystemExit("nanobot imports from outside the installed package")
|
||||
if len(sys.argv) > 2 and sys.argv[2] and distribution("nanobot-ai").version != sys.argv[2]:
|
||||
raise SystemExit("The requested version was not installed. Check manager pins or locks; no setup was started.")
|
||||
print(json.dumps(str(Path(sys.executable).absolute())))
|
||||
'@
|
||||
# Do not resolve the interpreter symlink or launch a new pipx/uv run environment.
|
||||
# Send code on stdin so Windows PowerShell preserves its embedded quotes.
|
||||
$ExpectedRoot = if ($ExpectedEnvironment) { $ExpectedEnvironment } else { "-" }
|
||||
$Result = $Probe | & $Command -I - $ExpectedRoot $ExpectedVersion
|
||||
if ($LASTEXITCODE -ne 0 -or -not $Result) {
|
||||
Fail "The installed nanobot environment could not be verified. No setup or other installation was attempted."
|
||||
}
|
||||
$script:NanobotPython = [string]($Result | ConvertFrom-Json)
|
||||
}
|
||||
|
||||
function Invoke-Nanobot {
|
||||
param([string[]]$NanobotArgs)
|
||||
|
||||
switch ($script:NanobotRunner) {
|
||||
"uv" {
|
||||
& uv tool run --from $InstallTarget nanobot @NanobotArgs
|
||||
}
|
||||
"pipx" {
|
||||
& pipx run --spec $InstallTarget nanobot @NanobotArgs
|
||||
}
|
||||
"python" {
|
||||
& $script:NanobotPython -m nanobot @NanobotArgs
|
||||
}
|
||||
default {
|
||||
Fail "nanobot was installed, but no runner was configured."
|
||||
}
|
||||
}
|
||||
& $script:NanobotPython -I -m nanobot @NanobotArgs
|
||||
}
|
||||
|
||||
function Get-NanobotCommand {
|
||||
switch ($script:NanobotRunner) {
|
||||
"uv" { return "uv tool run --from $InstallTarget nanobot" }
|
||||
"pipx" { return "pipx run --spec $InstallTarget nanobot" }
|
||||
"python" {
|
||||
$QuotedPython = "'" + $script:NanobotPython.Replace("'", "''") + "'"
|
||||
return "& $QuotedPython -m nanobot"
|
||||
}
|
||||
default { return "nanobot" }
|
||||
}
|
||||
return "& '" + $script:NanobotPython.Replace("'", "''") + "' -I -m nanobot"
|
||||
}
|
||||
|
||||
function Test-FreshNanobotInstall {
|
||||
@@ -163,30 +216,77 @@ function Install-WithActivePython {
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Show-InstallFailureHint
|
||||
}
|
||||
$script:NanobotRunner = "python"
|
||||
$script:NanobotPython = $Python
|
||||
Select-InstalledPython $Python
|
||||
}
|
||||
|
||||
function Install-WithUv {
|
||||
$script:LastInstallSucceeded = $false
|
||||
Write-Info "Installing or upgrading nanobot from $InstallSource with uv tool..."
|
||||
& uv tool install --python $Python --force --upgrade $InstallTarget
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
return
|
||||
$ToolDir = & uv tool dir
|
||||
if ($LASTEXITCODE -ne 0 -or -not $ToolDir) {
|
||||
Fail "Could not locate the uv tools directory."
|
||||
}
|
||||
$script:NanobotRunner = "uv"
|
||||
$script:LastInstallSucceeded = $true
|
||||
$Environment = Join-Path $ToolDir $Package
|
||||
if (Test-Path -LiteralPath (Join-Path $Environment "uv-receipt.toml")) {
|
||||
& uv tool upgrade $InstallTarget
|
||||
} elseif (Test-Path -LiteralPath $Environment) {
|
||||
Fail "The uv environment exists without its installation record. Repair it with uv before rerunning this installer."
|
||||
} else {
|
||||
& uv tool install --python $Python $InstallTarget
|
||||
}
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Fail "uv could not install or upgrade nanobot. Resolve the error above and retry; no other installation was attempted."
|
||||
}
|
||||
Select-InstalledPython (Join-Path $Environment "Scripts\python.exe") $Environment
|
||||
}
|
||||
|
||||
function Install-WithPipx {
|
||||
$script:LastInstallSucceeded = $false
|
||||
Write-Info "Installing or upgrading nanobot from $InstallSource with pipx..."
|
||||
& pipx install --python $Python --force $InstallTarget
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
return
|
||||
$ToolDir = & pipx environment --value PIPX_LOCAL_VENVS
|
||||
if ($LASTEXITCODE -ne 0 -or -not $ToolDir) {
|
||||
Fail "Could not locate the pipx environments directory."
|
||||
}
|
||||
$script:NanobotRunner = "pipx"
|
||||
$script:LastInstallSucceeded = $true
|
||||
$Environment = Join-Path $ToolDir $Package
|
||||
if (Test-Path -LiteralPath (Join-Path $Environment "pipx_metadata.json")) {
|
||||
# Keep this stdlib bootstrap check in sync with install.sh.
|
||||
$Inspect = @'
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
path = Path(sys.argv[1])
|
||||
if path.is_symlink() or path.stat().st_size > 1024 * 1024:
|
||||
raise ValueError
|
||||
record = json.loads(path.read_text(encoding="utf-8"))
|
||||
main = record["main_package"]
|
||||
name = r"(?i)nanobot[-_.]ai(?:\[[a-z0-9_., -]+\])?"
|
||||
spec = main["package_or_url"]
|
||||
# An explicit wheel may replace an earlier wheel source, but not discard
|
||||
# registry constraints, lock workflows or recorded installer options.
|
||||
allowed = re.fullmatch(name, spec) or (sys.argv[2] != "-" and re.fullmatch(name + r"\s*@\s*\S+\.whl", spec))
|
||||
if record["pipx_metadata_version"] not in {"0.5", "0.12"} or not allowed or main.get("pip_args") or main.get("lock_file"):
|
||||
raise ValueError
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
raise SystemExit("Cannot safely reuse pipx installation settings; inspect the original requirement and options.") from None
|
||||
'@
|
||||
$Exact = if ($ExpectedVersion) { $ExpectedVersion } else { "-" }
|
||||
$Inspect | & $Python -I - (Join-Path $Environment "pipx_metadata.json") $Exact
|
||||
if ($LASTEXITCODE -ne 0) { Fail "Review the original pipx installation settings; no installation was attempted." }
|
||||
if ($ExpectedVersion) {
|
||||
& pipx install --skip-maintenance --upgrade $InstallTarget
|
||||
} else {
|
||||
& pipx upgrade $Package
|
||||
}
|
||||
} elseif (Test-Path -LiteralPath $Environment) {
|
||||
Fail "The pipx environment exists without its installation record. Repair it with pipx before rerunning this installer."
|
||||
} else {
|
||||
& pipx install --python $Python $InstallTarget
|
||||
}
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Fail "pipx could not install or upgrade nanobot. Resolve the error above and retry; no other installation was attempted."
|
||||
}
|
||||
Select-InstalledPython (Join-Path $Environment "Scripts\python.exe") $Environment
|
||||
}
|
||||
|
||||
function Install-WithManagedVenv {
|
||||
@@ -197,13 +297,38 @@ function Install-WithManagedVenv {
|
||||
|
||||
$VenvDir = if ($env:NANOBOT_VENV) { $env:NANOBOT_VENV } else { Join-Path $HomeDir ".nanobot\venv" }
|
||||
$VenvPython = Join-Path $VenvDir "Scripts\python.exe"
|
||||
|
||||
if (-not (Test-Path $VenvPython)) {
|
||||
Write-Info "Creating a dedicated virtual environment at $VenvDir..."
|
||||
$Parent = Split-Path -Parent $VenvDir
|
||||
if ($Parent) {
|
||||
New-Item -ItemType Directory -Force -Path $Parent *> $null
|
||||
}
|
||||
# Selection survives a failed first venv/pip operation. It is not an
|
||||
# installed/readiness claim, nor adoption of an existing environment.
|
||||
$RecordSelection = @'
|
||||
import json, os, sys
|
||||
from pathlib import Path
|
||||
prefix = Path(sys.argv[1]).resolve()
|
||||
if any((prefix / name).exists() for name in ('uv-receipt.toml', 'pipx_metadata.json')):
|
||||
raise SystemExit('This environment belongs to another package manager.')
|
||||
prefix.mkdir(parents=True, exist_ok=True)
|
||||
path = prefix / 'nanobot-install.json'
|
||||
record = {'schema_version': 1, 'owner': 'nanobot-installer', 'environment': str(prefix), 'extras': []}
|
||||
if path.is_symlink():
|
||||
raise SystemExit('The installation selection is invalid; no receipt was replaced.')
|
||||
if path.exists():
|
||||
if path.stat().st_size > 4096 or json.loads(path.read_bytes()) != record:
|
||||
raise SystemExit('The installation selection changed; no receipt was replaced.')
|
||||
else:
|
||||
with path.open('x', encoding='utf-8') as stream:
|
||||
json.dump(record, stream, sort_keys=True)
|
||||
stream.write('\n')
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
path.chmod(0o600)
|
||||
'@
|
||||
& $Python -I -c $RecordSelection $VenvDir
|
||||
if ($LASTEXITCODE -ne 0) { Fail "Could not record the new installation's update settings." }
|
||||
& $Python -m venv $VenvDir
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Show-InstallFailureHint
|
||||
@@ -221,10 +346,14 @@ function Install-WithManagedVenv {
|
||||
Show-InstallFailureHint
|
||||
}
|
||||
|
||||
$script:NanobotRunner = "python"
|
||||
$script:NanobotPython = $VenvPython
|
||||
Select-InstalledPython $VenvPython $VenvDir
|
||||
}
|
||||
|
||||
$PreviousOutputEncoding = [Console]::OutputEncoding
|
||||
try {
|
||||
# uv/pipx emit UTF-8 paths; Windows PowerShell otherwise uses the console code page.
|
||||
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
|
||||
|
||||
foreach ($Arg in $RemainingArgs) {
|
||||
switch ($Arg) {
|
||||
"--dev" {
|
||||
@@ -254,24 +383,251 @@ if ($Dev) {
|
||||
$Python = Find-Python
|
||||
$Version = & $Python --version
|
||||
Write-Info "Using Python: $Version"
|
||||
$InstallMethod = Get-InstallMethod
|
||||
|
||||
if ($PSBoundParameters.ContainsKey("Wheel") -or $PSBoundParameters.ContainsKey("Sha256") -or
|
||||
$PSBoundParameters.ContainsKey("Release") -or $PSBoundParameters.ContainsKey("ManifestSha256")) {
|
||||
if ($PSBoundParameters.ContainsKey("Release") -or $PSBoundParameters.ContainsKey("ManifestSha256")) {
|
||||
if (-not $Release -or -not $ManifestSha256) { Fail "-Release and -ManifestSha256 must be supplied together." }
|
||||
if ($PSBoundParameters.ContainsKey("Wheel") -or $PSBoundParameters.ContainsKey("Sha256")) { Fail "Choose -Release or -Wheel, not both." }
|
||||
} elseif (-not $Wheel -or -not $Sha256) { Fail "-Wheel and -Sha256 must be supplied together." }
|
||||
$TargetPython = $Python
|
||||
$ToolEnvironment = ""
|
||||
if ($InstallMethod -eq "uv") {
|
||||
$ToolDir = & uv tool dir
|
||||
if ($LASTEXITCODE -ne 0 -or -not $ToolDir) { Fail "Could not inspect the uv tools directory." }
|
||||
$ToolEnvironment = Join-Path $ToolDir $Package
|
||||
} elseif ($InstallMethod -eq "pipx") {
|
||||
$ToolDir = & pipx environment --value PIPX_LOCAL_VENVS
|
||||
if ($LASTEXITCODE -ne 0 -or -not $ToolDir) { Fail "Could not inspect the pipx environments directory." }
|
||||
$ToolEnvironment = Join-Path $ToolDir $Package
|
||||
} elseif ($InstallMethod -eq "managed") {
|
||||
$ProfileDir = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }
|
||||
if (-not $ProfileDir) { Fail "A home directory is required to retain the downloaded release." }
|
||||
$ToolEnvironment = if ($env:NANOBOT_VENV) { $env:NANOBOT_VENV } else { Join-Path $ProfileDir ".nanobot\venv" }
|
||||
}
|
||||
if ($ToolEnvironment) {
|
||||
$CandidatePython = Join-Path $ToolEnvironment "Scripts\python.exe"
|
||||
if (Test-Path -LiteralPath $CandidatePython) { $TargetPython = $CandidatePython }
|
||||
}
|
||||
$ProfileDir = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }
|
||||
$ReleaseCache = if ($env:NANOBOT_RELEASE_CACHE) { $env:NANOBOT_RELEASE_CACHE } elseif ($ProfileDir) { Join-Path $ProfileDir ".nanobot\downloads\releases" } else { "-" }
|
||||
if ($Release -and $ReleaseCache -eq "-") { Fail "A home directory is required to retain the downloaded release." }
|
||||
$OwnerRecord = "-"
|
||||
if ($InstallMethod -eq "pipx") {
|
||||
$PipxDir = & pipx environment --value PIPX_LOCAL_VENVS
|
||||
if ($LASTEXITCODE -ne 0 -or -not $PipxDir) { Fail "Could not inspect the pipx environments directory." }
|
||||
$OwnerRecord = Join-Path (Join-Path $PipxDir $Package) "pipx_metadata.json"
|
||||
}
|
||||
$Verify = @'
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from email.parser import BytesParser
|
||||
from pathlib import Path
|
||||
from zipfile import ZipFile
|
||||
|
||||
import os
|
||||
import platform
|
||||
import struct
|
||||
import sysconfig
|
||||
import tempfile
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
# Bootstrap has no installed nanobot/packaging dependency. This closed platform
|
||||
# set matches the five published wheel tags; the owner still checks compatibility.
|
||||
def native_platform():
|
||||
if struct.calcsize("P") != 8:
|
||||
raise SystemExit("No native release wheel is available for 32-bit Python")
|
||||
machine = platform.machine().lower()
|
||||
if sys.platform == "darwin":
|
||||
if int(platform.mac_ver()[0].split(".")[0]) < 13:
|
||||
raise SystemExit("The native release requires macOS 13 or newer")
|
||||
if machine in ("arm64", "x86_64"):
|
||||
return "macosx_13_0_" + machine
|
||||
elif sys.platform == "linux":
|
||||
try:
|
||||
libc = os.confstr("CS_GNU_LIBC_VERSION") or ""
|
||||
except (ValueError, OSError):
|
||||
libc = ""
|
||||
if not re.fullmatch(r"glibc \d+\.\d+", libc) or tuple(map(int, libc.split()[1].split("."))) < (2, 17):
|
||||
raise SystemExit("The native release requires glibc 2.17+; no musl wheel is published")
|
||||
if machine in ("aarch64", "x86_64"):
|
||||
return "manylinux_2_17_" + machine
|
||||
elif sys.platform == "win32" and sysconfig.get_platform() == "win-amd64":
|
||||
return "win_amd64"
|
||||
raise SystemExit("No native release wheel is published for this Python platform")
|
||||
|
||||
def checked_url(url):
|
||||
parsed = urlsplit(url)
|
||||
if (parsed.scheme != "https" or parsed.hostname not in
|
||||
{"github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"}
|
||||
or parsed.username is not None or parsed.password is not None
|
||||
or parsed.port not in (None, 443) or parsed.fragment):
|
||||
raise SystemExit("Release download redirected outside the approved HTTPS hosts")
|
||||
return url
|
||||
|
||||
class ReleaseRedirect(HTTPRedirectHandler):
|
||||
max_redirections = 4
|
||||
max_repeats = 1
|
||||
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
checked_url(newurl)
|
||||
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
||||
|
||||
def fetch_release(version, manifest_hash, cache, dry_run):
|
||||
number = r"(?:0|[1-9]\d*)"
|
||||
if not re.fullmatch(rf"{number}\.{number}\.{number}(?:\.dev{number}|\.post{number})?", version):
|
||||
raise SystemExit("Expected a canonical release version, not a branch or URL")
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", manifest_hash):
|
||||
raise SystemExit("A trusted published manifest SHA-256 is required")
|
||||
selected_platform = native_platform()
|
||||
base = "https://github.com/HKUDS/nanobot/releases/download/v" + version + "/"
|
||||
opener = build_opener(ReleaseRedirect())
|
||||
with opener.open(Request(checked_url(base + "release-manifest.json"),
|
||||
headers={"Accept-Encoding": "identity"}), timeout=20) as response:
|
||||
payload = response.read(64 * 1024 + 1)
|
||||
if len(payload) > 64 * 1024 or hashlib.sha256(payload).hexdigest() != manifest_hash:
|
||||
raise SystemExit("Release manifest size or SHA-256 mismatch")
|
||||
manifest = json.loads(payload)
|
||||
if (not isinstance(manifest, dict) or type(manifest.get("schema_version")) is not int
|
||||
or manifest["schema_version"] != 1 or manifest.get("version") != version
|
||||
or set(manifest) != {"schema_version", "version", "source_commit", "candidate_commit",
|
||||
"requires_python", "artifacts"}):
|
||||
raise SystemExit("Unsupported or mismatched release manifest")
|
||||
for key in ("source_commit", "candidate_commit"):
|
||||
if not isinstance(manifest[key], str) or not re.fullmatch(r"[0-9a-f]{40}", manifest[key]):
|
||||
raise SystemExit("Invalid release commit identity")
|
||||
if not isinstance(manifest["requires_python"], str) or not 0 < len(manifest["requires_python"]) <= 200:
|
||||
raise SystemExit("Invalid Python requirement in release manifest")
|
||||
targets = {"darwin-arm64": "macosx_13_0_arm64", "darwin-x64": "macosx_13_0_x86_64",
|
||||
"linux-arm64": "manylinux_2_17_aarch64", "linux-x64": "manylinux_2_17_x86_64",
|
||||
"win32-x64": "win_amd64"}
|
||||
expected = {f"nanobot_ai-{version}-py3-none-{tag}.whl" for tag in targets.values()}
|
||||
expected.add(f"nanobot_ai-{version}.tar.gz")
|
||||
for target in targets:
|
||||
name = "nanobot-tui-" + target + (".exe" if target == "win32-x64" else "") + ".zip"
|
||||
expected.update((name, name + ".sha256"))
|
||||
artifacts = manifest["artifacts"]
|
||||
if (not isinstance(artifacts, list) or len(artifacts) != 16
|
||||
or any(not isinstance(item, dict) or set(item) != {"filename", "size", "sha256"}
|
||||
or not isinstance(item["filename"], str) or type(item["size"]) is not int
|
||||
or not 0 < item["size"] <= 2 * 1024**3
|
||||
or not isinstance(item["sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", item["sha256"])
|
||||
for item in artifacts)
|
||||
or {item["filename"] for item in artifacts} != expected):
|
||||
raise SystemExit("Release manifest does not contain the complete matching artifact set")
|
||||
filename = f"nanobot_ai-{version}-py3-none-{selected_platform}.whl"
|
||||
artifact = next(item for item in artifacts if item["filename"] == filename)
|
||||
if dry_run:
|
||||
print("nanobot-ai @ " + base + filename + "#sha256=" + artifact["sha256"] + "|" + version)
|
||||
raise SystemExit(0)
|
||||
directory = Path(cache).expanduser().absolute() / version / artifact["sha256"]
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
destination = directory / filename
|
||||
if destination.exists() or destination.is_symlink():
|
||||
if destination.is_symlink() or not destination.is_file() or destination.stat().st_size != artifact["size"]:
|
||||
raise SystemExit("Invalid cached release file; inspect the release download directory")
|
||||
return destination, artifact["sha256"]
|
||||
descriptor, name = tempfile.mkstemp(prefix=".download-", suffix=".part", dir=directory)
|
||||
temporary = Path(name)
|
||||
try:
|
||||
size = 0
|
||||
digest = hashlib.sha256()
|
||||
with os.fdopen(descriptor, "wb") as output:
|
||||
with opener.open(Request(checked_url(base + filename),
|
||||
headers={"Accept-Encoding": "identity"}), timeout=20) as response:
|
||||
while chunk := response.read(64 * 1024):
|
||||
size += len(chunk)
|
||||
if size > artifact["size"]:
|
||||
raise SystemExit("Release wheel exceeds its verified size")
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
if size != artifact["size"] or digest.hexdigest() != artifact["sha256"]:
|
||||
raise SystemExit("Release wheel size or SHA-256 mismatch")
|
||||
try:
|
||||
os.link(temporary, destination)
|
||||
except FileExistsError:
|
||||
if destination.is_symlink() or not destination.is_file() or destination.stat().st_size != size:
|
||||
raise SystemExit("The cached release destination changed during download")
|
||||
return destination, artifact["sha256"]
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
expected_hash = sys.argv[2]
|
||||
if sys.argv[4] not in ("", "-"):
|
||||
path, expected_hash = fetch_release(sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7] == "1")
|
||||
else:
|
||||
path = Path(sys.argv[1]).absolute()
|
||||
match = re.fullmatch(r"nanobot_ai-(\d+\.\d+\.\d+(?:\.dev\d+|\.post\d+)?)-py3-none-(macosx_13_0_(?:arm64|x86_64)|manylinux_2_17_(?:aarch64|x86_64)|win_amd64)\.whl", path.name)
|
||||
if not match or path.is_symlink() or not path.is_file() or not re.fullmatch(r"[0-9a-f]{64}", expected_hash):
|
||||
raise SystemExit("Expected a saved native nanobot wheel and its published SHA-256")
|
||||
with path.open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != expected_hash:
|
||||
raise SystemExit("Wheel SHA-256 mismatch; no package manager was started")
|
||||
version = match[1]
|
||||
with ZipFile(path) as wheel:
|
||||
metadata_path = f"nanobot_ai-{version}.dist-info/METADATA"
|
||||
if wheel.getinfo(metadata_path).file_size > 256 * 1024:
|
||||
raise SystemExit("Wheel metadata exceeds its size limit")
|
||||
metadata = BytesParser().parsebytes(wheel.read(metadata_path))
|
||||
if metadata["Name"] != "nanobot-ai" or metadata["Version"] != version:
|
||||
raise SystemExit("Wheel identity does not match its filename")
|
||||
extras = []
|
||||
record = Path(sys.argv[3])
|
||||
if sys.argv[3] != "-" and record.is_file():
|
||||
if record.stat().st_size > 1024 * 1024:
|
||||
raise SystemExit("pipx installation record is too large; inspect it before updating")
|
||||
spec = json.loads(record.read_text(encoding="utf-8"))["main_package"]["package_or_url"]
|
||||
extra_match = re.match(r"(?i)^nanobot[-_.]ai\[([a-z0-9_., -]+)\]", spec)
|
||||
if extra_match:
|
||||
extras = sorted({re.sub(r"[-_.]+", "-", extra.strip().lower()) for extra in extra_match[1].split(",")})
|
||||
if any(not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", extra) for extra in extras):
|
||||
raise SystemExit("Cannot preserve pipx extras; review the installation manually")
|
||||
elif "[" in spec:
|
||||
raise SystemExit("Cannot preserve pipx extras; review the installation manually")
|
||||
provided = {re.sub(r"[-_.]+", "-", extra.lower()) for extra in metadata.get_all("Provides-Extra", [])}
|
||||
if not set(extras) <= provided:
|
||||
raise SystemExit("The target wheel does not provide all existing pipx extras")
|
||||
requirement = "nanobot-ai" + ("[" + ",".join(extras) + "]" if extras else "")
|
||||
print(requirement + " @ " + path.as_uri() + "|" + version)
|
||||
'@
|
||||
# Nonempty sentinels keep positional arguments intact on Windows PowerShell 5.1.
|
||||
$WheelArg = if ($Wheel) { $Wheel } else { "-" }
|
||||
$HashArg = if ($Sha256) { $Sha256 } else { "-" }
|
||||
$ReleaseArg = if ($Release) { $Release } else { "-" }
|
||||
$ManifestHashArg = if ($ManifestSha256) { $ManifestSha256 } else { "-" }
|
||||
$DryRunArg = if ($DryRun) { "1" } else { "0" }
|
||||
$WheelIdentity = $Verify | & $TargetPython -I - $WheelArg $HashArg $OwnerRecord $ReleaseArg $ManifestHashArg $ReleaseCache $DryRunArg
|
||||
if ($LASTEXITCODE -ne 0 -or -not $WheelIdentity) { Fail "Release verification failed; no installation was attempted." }
|
||||
$InstallTarget, $ExpectedVersion = $WheelIdentity -split '\|', 2
|
||||
$InstallSource = "verified wheel $ExpectedVersion"
|
||||
if ($Release -and $DryRun) {
|
||||
Write-Info "Selected nanobot $ExpectedVersion from verified release metadata; its wheel was not downloaded."
|
||||
} else {
|
||||
Write-Info "Verified nanobot $ExpectedVersion. Keep the downloaded wheel at its current path."
|
||||
}
|
||||
}
|
||||
|
||||
if ($DryRun) {
|
||||
Write-Info "Dry run: would install or upgrade nanobot from $InstallSource."
|
||||
if (Test-VirtualEnv $Python) {
|
||||
if ($InstallMethod -eq "python") {
|
||||
Write-Info "Dry run: active virtual environment detected; would run: $Python -m pip install --upgrade $InstallTarget"
|
||||
Write-Info "Dry run: would run nanobot as: $Python -m nanobot"
|
||||
} elseif (Get-Command uv -ErrorAction SilentlyContinue) {
|
||||
Write-Info "Dry run: would run: uv tool install --python $Python --force --upgrade $InstallTarget"
|
||||
Write-Info "Dry run: would run nanobot as: uv tool run --from $InstallTarget nanobot"
|
||||
} elseif (Get-Command pipx -ErrorAction SilentlyContinue) {
|
||||
Write-Info "Dry run: would run: pipx install --python $Python --force $InstallTarget"
|
||||
Write-Info "Dry run: would run nanobot as: pipx run --spec $InstallTarget nanobot"
|
||||
Write-Info "Dry run: would start nanobot with this environment's Python in isolated mode."
|
||||
} elseif ($InstallMethod -eq "uv") {
|
||||
Write-Info "Dry run: would install with uv tool install, or use uv tool upgrade for an existing installation."
|
||||
Write-Info "Dry run: would start nanobot from its persistent uv tool environment."
|
||||
} elseif ($InstallMethod -eq "pipx") {
|
||||
Write-Info "Dry run: would review pipx installation settings before upgrading an existing environment."
|
||||
Write-Info "Dry run: would start nanobot from its persistent pipx environment."
|
||||
} else {
|
||||
$HomeDir = if ($env:HOME) { $env:HOME } elseif ($env:USERPROFILE) { $env:USERPROFILE } else { "~" }
|
||||
$VenvDir = if ($env:NANOBOT_VENV) { $env:NANOBOT_VENV } else { Join-Path $HomeDir ".nanobot\venv" }
|
||||
Write-Info "Dry run: would create or reuse a dedicated virtual environment: $VenvDir"
|
||||
Write-Info "Dry run: would run: $VenvDir\Scripts\python.exe -m pip install --upgrade $InstallTarget"
|
||||
Write-Info "Dry run: would run nanobot as: $VenvDir\Scripts\python.exe -m nanobot"
|
||||
Write-Info "Dry run: would start nanobot with $VenvDir\Scripts\python.exe in isolated mode."
|
||||
}
|
||||
if ($env:NANOBOT_SKIP_WIZARD -eq "1") {
|
||||
Write-Info "Dry run: would skip automatic setup because NANOBOT_SKIP_WIZARD=1."
|
||||
@@ -285,31 +641,15 @@ if ($DryRun) {
|
||||
return
|
||||
}
|
||||
|
||||
if (Test-VirtualEnv $Python) {
|
||||
if ($InstallMethod -eq "python") {
|
||||
Install-WithActivePython
|
||||
} elseif ($InstallMethod -eq "uv") {
|
||||
Install-WithUv
|
||||
} elseif ($InstallMethod -eq "pipx") {
|
||||
Install-WithPipx
|
||||
} else {
|
||||
$Installed = $false
|
||||
|
||||
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
||||
Install-WithUv
|
||||
$Installed = $script:LastInstallSucceeded
|
||||
if (-not $Installed) {
|
||||
Write-Info "uv tool install failed. Trying the next isolated install method..."
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $Installed -and (Get-Command pipx -ErrorAction SilentlyContinue)) {
|
||||
Install-WithPipx
|
||||
$Installed = $script:LastInstallSucceeded
|
||||
if (-not $Installed) {
|
||||
Write-Info "pipx install failed. Trying the managed virtual environment..."
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $Installed) {
|
||||
Write-Info "Using a dedicated virtual environment to avoid system pip."
|
||||
Install-WithManagedVenv
|
||||
}
|
||||
Write-Info "Using a dedicated virtual environment to avoid system pip."
|
||||
Install-WithManagedVenv
|
||||
}
|
||||
|
||||
Write-Info "Installed nanobot:"
|
||||
@@ -347,3 +687,6 @@ if ($LASTEXITCODE -ne 0) {
|
||||
}
|
||||
|
||||
Write-Info "Done. Try: $(Get-NanobotCommand) agent -m `"Hello!`""
|
||||
} finally {
|
||||
[Console]::OutputEncoding = $PreviousOutputEncoding
|
||||
}
|
||||
+393
-69
@@ -5,8 +5,13 @@ package="nanobot-ai"
|
||||
install_target="$package"
|
||||
install_source="PyPI"
|
||||
dry_run="0"
|
||||
nanobot_runner=""
|
||||
nanobot_python=""
|
||||
release_wheel=""
|
||||
release_sha256=""
|
||||
release_kind=""
|
||||
expected_version=""
|
||||
release_version=""
|
||||
manifest_sha256=""
|
||||
|
||||
info() {
|
||||
printf '%s\n' "$*"
|
||||
@@ -19,6 +24,10 @@ fail() {
|
||||
|
||||
install_failure_hint() {
|
||||
printf '%s\n' "Error: could not install nanobot from $install_source." >&2
|
||||
if [ -n "$expected_version" ]; then
|
||||
printf '%s\n' "Inspect the original manager error and retry this exact handoff. No setup or other installation was attempted." >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "If pip mentioned externally-managed-environment, use uv, pipx, or a virtual environment instead of system pip." >&2
|
||||
printf '%s\n' "You can also run manually:" >&2
|
||||
printf ' %s\n' "uv tool install --force --upgrade $install_target" >&2
|
||||
@@ -31,10 +40,16 @@ install_failure_hint() {
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage: install.sh [--dry-run]
|
||||
Usage: install.sh [--dry-run] [--wheel PATH --sha256 HASH]
|
||||
install.sh [--dry-run] --release VERSION --manifest-sha256 HASH
|
||||
|
||||
By default this installs or upgrades nanobot-ai from PyPI.
|
||||
Use --dry-run to print what would happen without installing or starting setup.
|
||||
For a verified release handoff, use --wheel and --sha256 together. Keep that
|
||||
downloaded wheel in place; your manager may record it as the installation source.
|
||||
Stop affected gateways and back up their data before updating an existing install.
|
||||
--release downloads the matching platform wheel from the official release using
|
||||
its published manifest hash. This selects one version, not a Preview subscription.
|
||||
|
||||
For current main, clone the repository and run `python -m pip install -e .`.
|
||||
EOF
|
||||
@@ -63,6 +78,44 @@ raise SystemExit(0 if sys.prefix != sys.base_prefix else 1)
|
||||
PY
|
||||
}
|
||||
|
||||
select_install_method() {
|
||||
if python_is_virtual_env; then
|
||||
active_prefix="$("$python_bin" -I -c 'import sys; print(sys.prefix)')"
|
||||
if [ -f "$active_prefix/uv-receipt.toml" ] || [ -f "$active_prefix/pipx_metadata.json" ]; then
|
||||
fail "The active Python belongs to uv or pipx. Deactivate it and rerun this installer so its manager owns the update."
|
||||
fi
|
||||
install_method="python"
|
||||
return
|
||||
fi
|
||||
|
||||
install_method=""
|
||||
existing_count=0
|
||||
if command -v uv >/dev/null 2>&1; then
|
||||
uv_dir="$(uv tool dir)" || fail "Could not inspect the uv tools directory"
|
||||
[ -n "$uv_dir" ] || fail "uv returned an empty tools directory"
|
||||
if [ -e "$uv_dir/$package" ]; then
|
||||
install_method="uv"
|
||||
existing_count=$((existing_count + 1))
|
||||
fi
|
||||
fi
|
||||
if command -v pipx >/dev/null 2>&1; then
|
||||
pipx_dir="$(pipx environment --value PIPX_LOCAL_VENVS)" || fail "Could not inspect the pipx environments directory"
|
||||
[ -n "$pipx_dir" ] || fail "pipx returned an empty environments directory"
|
||||
if [ -e "$pipx_dir/$package" ]; then
|
||||
install_method="pipx"
|
||||
existing_count=$((existing_count + 1))
|
||||
fi
|
||||
fi
|
||||
if [ -n "${NANOBOT_VENV:-}${HOME:-}" ] && [ -f "${NANOBOT_VENV:-${HOME:-}/.nanobot/venv}/pyvenv.cfg" ]; then
|
||||
install_method="managed"
|
||||
existing_count=$((existing_count + 1))
|
||||
fi
|
||||
[ "$existing_count" -le 1 ] || fail "Multiple nanobot installations were found. Use the intended environment's package manager; this installer changed none of them."
|
||||
if [ -z "$install_method" ]; then
|
||||
install_method="managed"
|
||||
fi
|
||||
}
|
||||
|
||||
ensure_pip() {
|
||||
target_python="$1"
|
||||
if "$target_python" -m pip --version >/dev/null 2>&1; then
|
||||
@@ -73,35 +126,36 @@ ensure_pip() {
|
||||
"$target_python" -m ensurepip --upgrade >/dev/null 2>&1
|
||||
}
|
||||
|
||||
select_installed_python() {
|
||||
# Keep the venv interpreter path (resolving its symlink would select base Python).
|
||||
# Isolated mode also prevents a checkout/PYTHONPATH from shadowing the new package.
|
||||
nanobot_python="$("$1" -I - "$2" "$expected_version" <<'PY'
|
||||
import sys
|
||||
from importlib.metadata import distribution
|
||||
from pathlib import Path
|
||||
|
||||
import nanobot
|
||||
|
||||
prefix = Path(sys.prefix).resolve()
|
||||
package = Path(nanobot.__file__).resolve()
|
||||
expected = sys.argv[1]
|
||||
if sys.prefix == sys.base_prefix or (expected and prefix != Path(expected).resolve()):
|
||||
raise SystemExit("The installed interpreter does not belong to the expected virtual environment")
|
||||
if not package.is_relative_to(prefix) or package != Path(distribution("nanobot-ai").locate_file("nanobot/__init__.py")).resolve():
|
||||
raise SystemExit("nanobot imports from outside the installed package")
|
||||
if sys.argv[2] and distribution("nanobot-ai").version != sys.argv[2]:
|
||||
raise SystemExit("The requested version was not installed. Check manager pins or locks; no setup was started.")
|
||||
print(Path(sys.executable).absolute())
|
||||
PY
|
||||
)" || fail "The installed nanobot environment could not be verified. No setup or other installation was attempted."
|
||||
}
|
||||
|
||||
run_nanobot() {
|
||||
case "$nanobot_runner" in
|
||||
uv)
|
||||
uv tool run --from "$install_target" nanobot "$@"
|
||||
;;
|
||||
pipx)
|
||||
pipx run --spec "$install_target" nanobot "$@"
|
||||
;;
|
||||
python)
|
||||
"$nanobot_python" -m nanobot "$@"
|
||||
;;
|
||||
*)
|
||||
fail "nanobot was installed, but no runner was configured"
|
||||
;;
|
||||
esac
|
||||
"$nanobot_python" -I -m nanobot "$@"
|
||||
}
|
||||
|
||||
nanobot_try_command() {
|
||||
case "$nanobot_runner" in
|
||||
uv)
|
||||
printf '%s\n' "uv tool run --from $install_target nanobot"
|
||||
;;
|
||||
pipx)
|
||||
printf '%s\n' "pipx run --spec $install_target nanobot"
|
||||
;;
|
||||
python)
|
||||
printf '%s\n' "$nanobot_python -m nanobot"
|
||||
;;
|
||||
esac
|
||||
"$python_bin" -I -c 'import shlex, sys; print(shlex.quote(sys.argv[1]) + " -I -m nanobot")' "$nanobot_python"
|
||||
}
|
||||
|
||||
is_fresh_nanobot_install() {
|
||||
@@ -132,20 +186,64 @@ install_with_active_python() {
|
||||
info "Detected an active virtual environment. Installing into it..."
|
||||
ensure_pip "$python_bin" || return 1
|
||||
"$python_bin" -m pip install --upgrade "$install_target" || return 1
|
||||
nanobot_runner="python"
|
||||
nanobot_python="$python_bin"
|
||||
select_installed_python "$python_bin" ""
|
||||
}
|
||||
|
||||
install_with_uv() {
|
||||
info "Installing or upgrading nanobot from $install_source with uv tool..."
|
||||
uv tool install --python "$python_bin" --force --upgrade "$install_target" || return 1
|
||||
nanobot_runner="uv"
|
||||
tool_dir="$(uv tool dir)" || fail "Could not locate the uv tools directory"
|
||||
[ -n "$tool_dir" ] || fail "uv returned an empty tools directory"
|
||||
if [ -f "$tool_dir/$package/uv-receipt.toml" ]; then
|
||||
uv tool upgrade "$install_target" || fail "uv could not upgrade nanobot. Resolve the error above and retry; no other installation was attempted."
|
||||
elif [ -e "$tool_dir/$package" ]; then
|
||||
fail "The uv environment exists without its installation record. Repair it with uv before rerunning this installer."
|
||||
else
|
||||
uv tool install --python "$python_bin" "$install_target" ||
|
||||
fail "uv could not install nanobot. Resolve the error above and retry; no other installation was attempted."
|
||||
fi
|
||||
select_installed_python "$tool_dir/$package/bin/python" "$tool_dir/$package"
|
||||
}
|
||||
|
||||
install_with_pipx() {
|
||||
info "Installing or upgrading nanobot from $install_source with pipx..."
|
||||
pipx install --python "$python_bin" --force "$install_target" || return 1
|
||||
nanobot_runner="pipx"
|
||||
tool_dir="$(pipx environment --value PIPX_LOCAL_VENVS)" || fail "Could not locate the pipx environments directory"
|
||||
[ -n "$tool_dir" ] || fail "pipx returned an empty environments directory"
|
||||
if [ -f "$tool_dir/$package/pipx_metadata.json" ]; then
|
||||
# Bootstrap must not import the installed application or expose private options.
|
||||
"$python_bin" -I - "$tool_dir/$package/pipx_metadata.json" "$expected_version" <<'PY' || fail "Review the original pipx installation settings; no installation was attempted."
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
path = Path(sys.argv[1])
|
||||
if path.is_symlink() or path.stat().st_size > 1024 * 1024:
|
||||
raise ValueError
|
||||
record = json.loads(path.read_text(encoding="utf-8"))
|
||||
main = record["main_package"]
|
||||
name = r"(?i)nanobot[-_.]ai(?:\[[a-z0-9_., -]+\])?"
|
||||
spec = main["package_or_url"]
|
||||
# An explicit wheel may replace an earlier wheel source, but not discard
|
||||
# registry constraints, lock workflows or recorded installer options.
|
||||
allowed = re.fullmatch(name, spec) or (sys.argv[2] and re.fullmatch(name + r"\s*@\s*\S+\.whl", spec))
|
||||
if record["pipx_metadata_version"] not in {"0.5", "0.12"} or not allowed or main.get("pip_args") or main.get("lock_file"):
|
||||
raise ValueError
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
raise SystemExit("Cannot safely reuse pipx installation settings; inspect the original requirement and options.") from None
|
||||
PY
|
||||
if [ -n "$expected_version" ]; then
|
||||
pipx install --skip-maintenance --upgrade "$install_target" || fail "pipx could not upgrade nanobot. Resolve the error above and retry; no other installation was attempted."
|
||||
else
|
||||
pipx upgrade "$package" || fail "pipx could not upgrade nanobot. Resolve the error above and retry; no other installation was attempted."
|
||||
fi
|
||||
elif [ -e "$tool_dir/$package" ]; then
|
||||
fail "The pipx environment exists without its installation record. Repair it with pipx before rerunning this installer."
|
||||
else
|
||||
pipx install --python "$python_bin" "$install_target" ||
|
||||
fail "pipx could not install nanobot. Resolve the error above and retry; no other installation was attempted."
|
||||
fi
|
||||
select_installed_python "$tool_dir/$package/bin/python" "$tool_dir/$package"
|
||||
}
|
||||
|
||||
write_managed_wrapper() {
|
||||
@@ -158,10 +256,11 @@ write_managed_wrapper() {
|
||||
return 0
|
||||
fi
|
||||
|
||||
nanobot_command="$(nanobot_try_command)"
|
||||
cat > "$wrapper" <<EOF
|
||||
#!/bin/sh
|
||||
# Generated by nanobot installer.
|
||||
exec "$nanobot_python" -m nanobot "\$@"
|
||||
exec $nanobot_command "\$@"
|
||||
EOF
|
||||
chmod +x "$wrapper" || return 0
|
||||
|
||||
@@ -176,10 +275,33 @@ install_with_managed_venv() {
|
||||
|
||||
venv_dir="${NANOBOT_VENV:-$HOME/.nanobot/venv}"
|
||||
venv_python="$venv_dir/bin/python"
|
||||
|
||||
if [ ! -x "$venv_python" ]; then
|
||||
info "Creating a dedicated virtual environment at $venv_dir..."
|
||||
mkdir -p "$(dirname "$venv_dir")"
|
||||
# Persist selection before venv/pip work, so a failed first install can
|
||||
# resume as the same managed environment. This is not an installed claim.
|
||||
"$python_bin" -I - "$venv_dir" <<'PY' || return 1
|
||||
import json, os, sys
|
||||
from pathlib import Path
|
||||
prefix = Path(sys.argv[1]).resolve()
|
||||
if any((prefix / name).exists() for name in ('uv-receipt.toml', 'pipx_metadata.json')):
|
||||
raise SystemExit('This environment belongs to another package manager.')
|
||||
prefix.mkdir(parents=True, exist_ok=True)
|
||||
path = prefix / 'nanobot-install.json'
|
||||
record = {'schema_version': 1, 'owner': 'nanobot-installer', 'environment': str(prefix), 'extras': []}
|
||||
if path.is_symlink():
|
||||
raise SystemExit('The installation selection is invalid; no receipt was replaced.')
|
||||
if path.exists():
|
||||
if path.stat().st_size > 4096 or json.loads(path.read_bytes()) != record:
|
||||
raise SystemExit('The installation selection changed; no receipt was replaced.')
|
||||
else:
|
||||
with path.open('x', encoding='utf-8') as stream:
|
||||
json.dump(record, stream, sort_keys=True)
|
||||
stream.write('\n')
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
path.chmod(0o600)
|
||||
PY
|
||||
"$python_bin" -m venv "$venv_dir" || return 1
|
||||
fi
|
||||
|
||||
@@ -192,13 +314,25 @@ PY
|
||||
ensure_pip "$venv_python" || return 1
|
||||
"$venv_python" -m pip install --upgrade "$install_target" || return 1
|
||||
|
||||
nanobot_runner="python"
|
||||
nanobot_python="$venv_python"
|
||||
select_installed_python "$venv_python" "$venv_dir"
|
||||
write_managed_wrapper
|
||||
}
|
||||
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--wheel|--sha256|--release|--manifest-sha256)
|
||||
[ "$#" -ge 2 ] || fail "$1 requires a value"
|
||||
case "$1" in --wheel|--sha256) wanted_kind="wheel" ;; *) wanted_kind="release" ;; esac
|
||||
[ -z "$release_kind" ] || [ "$release_kind" = "$wanted_kind" ] || fail "Choose --release or --wheel, not both"
|
||||
release_kind="$wanted_kind"
|
||||
case "$1" in
|
||||
--wheel) release_wheel="$2" ;;
|
||||
--sha256) release_sha256="$2" ;;
|
||||
--release) release_version="$2" ;;
|
||||
--manifest-sha256) manifest_sha256="$2" ;;
|
||||
esac
|
||||
shift
|
||||
;;
|
||||
--dev)
|
||||
fail "--dev installed an untracked main snapshot and is no longer supported; clone the repository and run 'python -m pip install -e .' instead"
|
||||
;;
|
||||
@@ -229,23 +363,229 @@ else
|
||||
fi
|
||||
|
||||
info "Using Python: $("$python_bin" --version 2>&1)"
|
||||
select_install_method
|
||||
|
||||
if [ -n "$release_kind" ]; then
|
||||
if [ "$release_kind" = "release" ]; then
|
||||
[ -n "$release_version" ] && [ -n "$manifest_sha256" ] || fail "--release and --manifest-sha256 must be supplied together"
|
||||
[ -z "$release_wheel$release_sha256" ] || fail "Choose --release or --wheel, not both"
|
||||
[ -n "${HOME:-}" ] || fail "HOME is required to retain the downloaded release"
|
||||
else
|
||||
[ -n "$release_wheel" ] && [ -n "$release_sha256" ] || fail "--wheel and --sha256 must be supplied together"
|
||||
fi
|
||||
target_python="$python_bin"
|
||||
case "$install_method" in
|
||||
uv) [ ! -x "$uv_dir/$package/bin/python" ] || target_python="$uv_dir/$package/bin/python" ;;
|
||||
pipx) [ ! -x "$pipx_dir/$package/bin/python" ] || target_python="$pipx_dir/$package/bin/python" ;;
|
||||
managed)
|
||||
candidate_python="${NANOBOT_VENV:-${HOME:-}/.nanobot/venv}/bin/python"
|
||||
[ ! -x "$candidate_python" ] || target_python="$candidate_python"
|
||||
;;
|
||||
esac
|
||||
owner_record="-"
|
||||
if [ "$install_method" = "pipx" ]; then owner_record="$pipx_dir/$package/pipx_metadata.json"; fi
|
||||
wheel_identity="$("$target_python" -I - "$release_wheel" "$release_sha256" "$owner_record" "$release_version" "$manifest_sha256" "${NANOBOT_RELEASE_CACHE:-${HOME:-}/.nanobot/downloads/releases}" "$dry_run" <<'PY'
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from email.parser import BytesParser
|
||||
from pathlib import Path
|
||||
from zipfile import ZipFile
|
||||
|
||||
import os
|
||||
import platform
|
||||
import struct
|
||||
import sysconfig
|
||||
import tempfile
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
|
||||
# Bootstrap has no installed nanobot/packaging dependency. This closed platform
|
||||
# set matches the five published wheel tags; the owner still checks compatibility.
|
||||
def native_platform():
|
||||
if struct.calcsize("P") != 8:
|
||||
raise SystemExit("No native release wheel is available for 32-bit Python")
|
||||
machine = platform.machine().lower()
|
||||
if sys.platform == "darwin":
|
||||
if int(platform.mac_ver()[0].split(".")[0]) < 13:
|
||||
raise SystemExit("The native release requires macOS 13 or newer")
|
||||
if machine in ("arm64", "x86_64"):
|
||||
return "macosx_13_0_" + machine
|
||||
elif sys.platform == "linux":
|
||||
try:
|
||||
libc = os.confstr("CS_GNU_LIBC_VERSION") or ""
|
||||
except (ValueError, OSError):
|
||||
libc = ""
|
||||
if not re.fullmatch(r"glibc \d+\.\d+", libc) or tuple(map(int, libc.split()[1].split("."))) < (2, 17):
|
||||
raise SystemExit("The native release requires glibc 2.17+; no musl wheel is published")
|
||||
if machine in ("aarch64", "x86_64"):
|
||||
return "manylinux_2_17_" + machine
|
||||
elif sys.platform == "win32" and sysconfig.get_platform() == "win-amd64":
|
||||
return "win_amd64"
|
||||
raise SystemExit("No native release wheel is published for this Python platform")
|
||||
|
||||
def checked_url(url):
|
||||
parsed = urlsplit(url)
|
||||
if (parsed.scheme != "https" or parsed.hostname not in
|
||||
{"github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"}
|
||||
or parsed.username is not None or parsed.password is not None
|
||||
or parsed.port not in (None, 443) or parsed.fragment):
|
||||
raise SystemExit("Release download redirected outside the approved HTTPS hosts")
|
||||
return url
|
||||
|
||||
class ReleaseRedirect(HTTPRedirectHandler):
|
||||
max_redirections = 4
|
||||
max_repeats = 1
|
||||
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
checked_url(newurl)
|
||||
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
||||
|
||||
def fetch_release(version, manifest_hash, cache, dry_run):
|
||||
number = r"(?:0|[1-9]\d*)"
|
||||
if not re.fullmatch(rf"{number}\.{number}\.{number}(?:\.dev{number}|\.post{number})?", version):
|
||||
raise SystemExit("Expected a canonical release version, not a branch or URL")
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", manifest_hash):
|
||||
raise SystemExit("A trusted published manifest SHA-256 is required")
|
||||
selected_platform = native_platform()
|
||||
base = "https://github.com/HKUDS/nanobot/releases/download/v" + version + "/"
|
||||
opener = build_opener(ReleaseRedirect())
|
||||
with opener.open(Request(checked_url(base + "release-manifest.json"),
|
||||
headers={"Accept-Encoding": "identity"}), timeout=20) as response:
|
||||
payload = response.read(64 * 1024 + 1)
|
||||
if len(payload) > 64 * 1024 or hashlib.sha256(payload).hexdigest() != manifest_hash:
|
||||
raise SystemExit("Release manifest size or SHA-256 mismatch")
|
||||
manifest = json.loads(payload)
|
||||
if (not isinstance(manifest, dict) or type(manifest.get("schema_version")) is not int
|
||||
or manifest["schema_version"] != 1 or manifest.get("version") != version
|
||||
or set(manifest) != {"schema_version", "version", "source_commit", "candidate_commit",
|
||||
"requires_python", "artifacts"}):
|
||||
raise SystemExit("Unsupported or mismatched release manifest")
|
||||
for key in ("source_commit", "candidate_commit"):
|
||||
if not isinstance(manifest[key], str) or not re.fullmatch(r"[0-9a-f]{40}", manifest[key]):
|
||||
raise SystemExit("Invalid release commit identity")
|
||||
if not isinstance(manifest["requires_python"], str) or not 0 < len(manifest["requires_python"]) <= 200:
|
||||
raise SystemExit("Invalid Python requirement in release manifest")
|
||||
targets = {"darwin-arm64": "macosx_13_0_arm64", "darwin-x64": "macosx_13_0_x86_64",
|
||||
"linux-arm64": "manylinux_2_17_aarch64", "linux-x64": "manylinux_2_17_x86_64",
|
||||
"win32-x64": "win_amd64"}
|
||||
expected = {f"nanobot_ai-{version}-py3-none-{tag}.whl" for tag in targets.values()}
|
||||
expected.add(f"nanobot_ai-{version}.tar.gz")
|
||||
for target in targets:
|
||||
name = "nanobot-tui-" + target + (".exe" if target == "win32-x64" else "") + ".zip"
|
||||
expected.update((name, name + ".sha256"))
|
||||
artifacts = manifest["artifacts"]
|
||||
if (not isinstance(artifacts, list) or len(artifacts) != 16
|
||||
or any(not isinstance(item, dict) or set(item) != {"filename", "size", "sha256"}
|
||||
or not isinstance(item["filename"], str) or type(item["size"]) is not int
|
||||
or not 0 < item["size"] <= 2 * 1024**3
|
||||
or not isinstance(item["sha256"], str) or not re.fullmatch(r"[0-9a-f]{64}", item["sha256"])
|
||||
for item in artifacts)
|
||||
or {item["filename"] for item in artifacts} != expected):
|
||||
raise SystemExit("Release manifest does not contain the complete matching artifact set")
|
||||
filename = f"nanobot_ai-{version}-py3-none-{selected_platform}.whl"
|
||||
artifact = next(item for item in artifacts if item["filename"] == filename)
|
||||
if dry_run:
|
||||
print("nanobot-ai @ " + base + filename + "#sha256=" + artifact["sha256"] + "|" + version)
|
||||
raise SystemExit(0)
|
||||
directory = Path(cache).expanduser().absolute() / version / artifact["sha256"]
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
destination = directory / filename
|
||||
if destination.exists() or destination.is_symlink():
|
||||
if destination.is_symlink() or not destination.is_file() or destination.stat().st_size != artifact["size"]:
|
||||
raise SystemExit("Invalid cached release file; inspect the release download directory")
|
||||
return destination, artifact["sha256"]
|
||||
descriptor, name = tempfile.mkstemp(prefix=".download-", suffix=".part", dir=directory)
|
||||
temporary = Path(name)
|
||||
try:
|
||||
size = 0
|
||||
digest = hashlib.sha256()
|
||||
with os.fdopen(descriptor, "wb") as output:
|
||||
with opener.open(Request(checked_url(base + filename),
|
||||
headers={"Accept-Encoding": "identity"}), timeout=20) as response:
|
||||
while chunk := response.read(64 * 1024):
|
||||
size += len(chunk)
|
||||
if size > artifact["size"]:
|
||||
raise SystemExit("Release wheel exceeds its verified size")
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
if size != artifact["size"] or digest.hexdigest() != artifact["sha256"]:
|
||||
raise SystemExit("Release wheel size or SHA-256 mismatch")
|
||||
try:
|
||||
os.link(temporary, destination)
|
||||
except FileExistsError:
|
||||
if destination.is_symlink() or not destination.is_file() or destination.stat().st_size != size:
|
||||
raise SystemExit("The cached release destination changed during download")
|
||||
return destination, artifact["sha256"]
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
expected_hash = sys.argv[2]
|
||||
if sys.argv[4] not in ("", "-"):
|
||||
path, expected_hash = fetch_release(sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7] == "1")
|
||||
else:
|
||||
path = Path(sys.argv[1]).absolute()
|
||||
match = re.fullmatch(r"nanobot_ai-(\d+\.\d+\.\d+(?:\.dev\d+|\.post\d+)?)-py3-none-(macosx_13_0_(?:arm64|x86_64)|manylinux_2_17_(?:aarch64|x86_64)|win_amd64)\.whl", path.name)
|
||||
if not match or path.is_symlink() or not path.is_file() or not re.fullmatch(r"[0-9a-f]{64}", expected_hash):
|
||||
raise SystemExit("Expected a saved native nanobot wheel and its published SHA-256")
|
||||
with path.open("rb") as stream:
|
||||
if hashlib.file_digest(stream, "sha256").hexdigest() != expected_hash:
|
||||
raise SystemExit("Wheel SHA-256 mismatch; no package manager was started")
|
||||
version = match[1]
|
||||
with ZipFile(path) as wheel:
|
||||
metadata_path = f"nanobot_ai-{version}.dist-info/METADATA"
|
||||
if wheel.getinfo(metadata_path).file_size > 256 * 1024:
|
||||
raise SystemExit("Wheel metadata exceeds its size limit")
|
||||
metadata = BytesParser().parsebytes(wheel.read(metadata_path))
|
||||
if metadata["Name"] != "nanobot-ai" or metadata["Version"] != version:
|
||||
raise SystemExit("Wheel identity does not match its filename")
|
||||
extras = []
|
||||
record = Path(sys.argv[3])
|
||||
if sys.argv[3] != "-" and record.is_file():
|
||||
if record.stat().st_size > 1024 * 1024:
|
||||
raise SystemExit("pipx installation record is too large; inspect it before updating")
|
||||
spec = json.loads(record.read_text(encoding="utf-8"))["main_package"]["package_or_url"]
|
||||
extra_match = re.match(r"(?i)^nanobot[-_.]ai\[([a-z0-9_., -]+)\]", spec)
|
||||
if extra_match:
|
||||
extras = sorted({re.sub(r"[-_.]+", "-", extra.strip().lower()) for extra in extra_match[1].split(",")})
|
||||
if any(not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", extra) for extra in extras):
|
||||
raise SystemExit("Cannot preserve pipx extras; review the installation manually")
|
||||
elif "[" in spec:
|
||||
raise SystemExit("Cannot preserve pipx extras; review the installation manually")
|
||||
provided = {re.sub(r"[-_.]+", "-", extra.lower()) for extra in metadata.get_all("Provides-Extra", [])}
|
||||
if not set(extras) <= provided:
|
||||
raise SystemExit("The target wheel does not provide all existing pipx extras")
|
||||
requirement = "nanobot-ai" + ("[" + ",".join(extras) + "]" if extras else "")
|
||||
print(requirement + " @ " + path.as_uri() + "|" + version)
|
||||
PY
|
||||
)" || fail "Release verification failed; no installation was attempted."
|
||||
install_target="${wheel_identity%|*}"
|
||||
expected_version="${wheel_identity##*|}"
|
||||
install_source="verified wheel $expected_version"
|
||||
if [ "$release_kind" = "release" ] && [ "$dry_run" = "1" ]; then
|
||||
info "Selected nanobot $expected_version from verified release metadata; its wheel was not downloaded."
|
||||
else
|
||||
info "Verified nanobot $expected_version. Keep the downloaded wheel at its current path."
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$dry_run" = "1" ]; then
|
||||
info "Dry run: would install or upgrade nanobot from $install_source."
|
||||
if python_is_virtual_env; then
|
||||
if [ "$install_method" = "python" ]; then
|
||||
info "Dry run: active virtual environment detected; would run: $python_bin -m pip install --upgrade $install_target"
|
||||
info "Dry run: would run nanobot as: $python_bin -m nanobot"
|
||||
elif command -v uv >/dev/null 2>&1; then
|
||||
info "Dry run: would run: uv tool install --python $python_bin --force --upgrade $install_target"
|
||||
info "Dry run: would run nanobot as: uv tool run --from $install_target nanobot"
|
||||
elif command -v pipx >/dev/null 2>&1; then
|
||||
info "Dry run: would run: pipx install --python $python_bin --force $install_target"
|
||||
info "Dry run: would run nanobot as: pipx run --spec $install_target nanobot"
|
||||
info "Dry run: would start nanobot with this environment's Python in isolated mode."
|
||||
elif [ "$install_method" = "uv" ]; then
|
||||
info "Dry run: would install with uv tool install, or use uv tool upgrade for an existing installation."
|
||||
info "Dry run: would start nanobot from its persistent uv tool environment."
|
||||
elif [ "$install_method" = "pipx" ]; then
|
||||
info "Dry run: would review pipx installation settings before upgrading an existing environment."
|
||||
info "Dry run: would start nanobot from its persistent pipx environment."
|
||||
else
|
||||
venv_dir="${NANOBOT_VENV:-$HOME/.nanobot/venv}"
|
||||
info "Dry run: would create or reuse a dedicated virtual environment: $venv_dir"
|
||||
info "Dry run: would run: $venv_dir/bin/python -m pip install --upgrade $install_target"
|
||||
info "Dry run: would run nanobot as: $venv_dir/bin/python -m nanobot"
|
||||
info "Dry run: would start nanobot with $venv_dir/bin/python in isolated mode."
|
||||
fi
|
||||
if [ "${NANOBOT_SKIP_WIZARD:-}" = "1" ]; then
|
||||
info "Dry run: would skip automatic setup because NANOBOT_SKIP_WIZARD=1."
|
||||
@@ -259,31 +599,15 @@ if [ "$dry_run" = "1" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if python_is_virtual_env; then
|
||||
if [ "$install_method" = "python" ]; then
|
||||
install_with_active_python || install_failure_hint
|
||||
elif [ "$install_method" = "uv" ]; then
|
||||
install_with_uv
|
||||
elif [ "$install_method" = "pipx" ]; then
|
||||
install_with_pipx
|
||||
else
|
||||
installed="0"
|
||||
|
||||
if command -v uv >/dev/null 2>&1; then
|
||||
if install_with_uv; then
|
||||
installed="1"
|
||||
else
|
||||
info "uv tool install failed. Trying the next isolated install method..."
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$installed" != "1" ] && command -v pipx >/dev/null 2>&1; then
|
||||
if install_with_pipx; then
|
||||
installed="1"
|
||||
else
|
||||
info "pipx install failed. Trying the managed virtual environment..."
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$installed" != "1" ]; then
|
||||
info "Using a dedicated virtual environment to avoid system pip."
|
||||
install_with_managed_venv || install_failure_hint
|
||||
fi
|
||||
info "Using a dedicated virtual environment to avoid system pip."
|
||||
install_with_managed_venv || install_failure_hint
|
||||
fi
|
||||
|
||||
info "Installed nanobot:"
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
"""Prepare and verify an exact release candidate without publishing anything.
|
||||
|
||||
Preparation creates a separate checkout. Verification writes a manifest only after
|
||||
all five wheels, the sdist and licensed TUI archives pass their structural checks.
|
||||
Native execution, CI approval and public-download checks remain separate gates.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import tomllib
|
||||
from email.parser import BytesParser
|
||||
from fnmatch import fnmatchcase
|
||||
from pathlib import Path
|
||||
|
||||
from packaging.version import Version
|
||||
|
||||
from nanobot.releases import (
|
||||
PLATFORMS,
|
||||
ReleaseArtifact,
|
||||
ReleaseManifest,
|
||||
release_filenames,
|
||||
release_version,
|
||||
)
|
||||
from scripts.build_tui_wheels import build_wheel, release_bundle, source_files, wheel_files
|
||||
from scripts.release_install_guide import render_install_guide
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
VERSION_FILES = ("pyproject.toml", "nanobot/__init__.py")
|
||||
|
||||
|
||||
def _git(root: Path, *args: str, env: dict[str, str] | None = None, trim: bool = True) -> str:
|
||||
output = subprocess.run(
|
||||
["git", *args], cwd=root, env=env, check=True, capture_output=True,
|
||||
text=True, encoding="utf-8", timeout=120,
|
||||
).stdout
|
||||
return output.strip() if trim else output
|
||||
|
||||
|
||||
def _commit(value: str) -> str:
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", value):
|
||||
raise ValueError("Use an exact, full source commit SHA, not a branch or tag")
|
||||
return value
|
||||
|
||||
|
||||
def preview_version(base: str, sequence: int) -> str:
|
||||
release_version(base)
|
||||
parsed = Version(base)
|
||||
if parsed.is_prerelease or parsed.is_postrelease or sequence < 1:
|
||||
raise ValueError("Use a stable base and a positive preview sequence")
|
||||
return f"{base}.dev{sequence}"
|
||||
|
||||
|
||||
def _version_changes(pyproject: str, init: str, version: str) -> dict[str, str]:
|
||||
current = tomllib.loads(pyproject)["project"]["version"]
|
||||
updated_project, project_count = re.subn(
|
||||
rf'(?m)^version = "{re.escape(current)}"$', f'version = "{version}"', pyproject,
|
||||
)
|
||||
updated_init, init_count = re.subn(
|
||||
rf'return _read_pyproject_version\(\) or "{re.escape(current)}"',
|
||||
f'return _read_pyproject_version() or "{version}"', init,
|
||||
)
|
||||
if project_count != 1 or init_count != 1:
|
||||
raise ValueError("Package and fallback version declarations need maintainer review")
|
||||
return dict(zip(VERSION_FILES, (updated_project, updated_init), strict=True))
|
||||
|
||||
|
||||
def prepare_preview(root: Path, output: Path, *, source_commit: str, base: str, sequence: int) -> dict[str, str]:
|
||||
source_commit = _commit(source_commit)
|
||||
version = preview_version(base, sequence)
|
||||
root, output = root.resolve(), output.resolve()
|
||||
if output.exists() or output == root or root in output.parents:
|
||||
raise ValueError("Candidate output must be a new directory outside the source checkout")
|
||||
if _git(root, "rev-parse", f"{source_commit}^{{commit}}") != source_commit:
|
||||
raise ValueError("Source commit is not available in this repository")
|
||||
original = {name: _git(root, "show", f"{source_commit}:{name}", trim=False) for name in VERSION_FILES}
|
||||
current = Version(tomllib.loads(original["pyproject.toml"])["project"]["version"])
|
||||
if Version(base).release < current.release or _git(root, "tag", "--list", f"v{base}"):
|
||||
raise ValueError("Preview base must not precede the source or reuse an existing stable tag")
|
||||
changes = _version_changes(original["pyproject.toml"], original["nanobot/__init__.py"], version)
|
||||
# A separate clone preserves the source parent without touching the caller's worktree.
|
||||
_git(root, "clone", "--shared", "--no-checkout", "-c", "core.autocrlf=false", str(root), str(output))
|
||||
hooks = output / ".git" / "candidate-hooks"
|
||||
hooks.mkdir()
|
||||
_git(output, "-c", f"core.hooksPath={hooks}", "checkout", "--detach", source_commit)
|
||||
for name, content in changes.items():
|
||||
(output / name).write_text(content, encoding="utf-8", newline="\n")
|
||||
_git(output, "add", "--", *VERSION_FILES)
|
||||
timestamp = _git(root, "show", "-s", "--format=%cI", source_commit)
|
||||
env = dict(os.environ)
|
||||
for role in ("AUTHOR", "COMMITTER"):
|
||||
env[f"GIT_{role}_NAME"] = "nanobot release"
|
||||
env[f"GIT_{role}_EMAIL"] = "nanobot-release@users.noreply.github.com"
|
||||
env[f"GIT_{role}_DATE"] = timestamp
|
||||
_git(output, "-c", "commit.gpgsign=false", "-c", f"core.hooksPath={hooks}",
|
||||
"commit", "-m", f"Prepare {version} from {source_commit}", env=env)
|
||||
return {"version": version, "source_commit": source_commit,
|
||||
"candidate_commit": _git(output, "rev-parse", "HEAD")}
|
||||
|
||||
|
||||
def _candidate_identity(root: Path, source_commit: str) -> tuple[str, str, str]:
|
||||
_commit(source_commit)
|
||||
candidate_commit = _git(root, "rev-parse", "HEAD")
|
||||
if _git(root, "status", "--porcelain", "--untracked-files=no"):
|
||||
raise ValueError("Candidate has uncommitted tracked changes")
|
||||
metadata = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]
|
||||
version, requires_python = release_version(metadata["version"]), metadata["requires-python"]
|
||||
if source_commit != candidate_commit:
|
||||
if _git(root, "rev-parse", "HEAD^") != source_commit:
|
||||
raise ValueError("Candidate must be a direct child of its exact source commit")
|
||||
original = {name: _git(root, "show", f"{source_commit}:{name}", trim=False) for name in VERSION_FILES}
|
||||
expected = _version_changes(original["pyproject.toml"], original["nanobot/__init__.py"], version)
|
||||
changed = set(_git(root, "diff", "--name-only", source_commit, "HEAD").splitlines())
|
||||
if changed != set(VERSION_FILES) or any(
|
||||
(root / name).read_text(encoding="utf-8") != text for name, text in expected.items()
|
||||
):
|
||||
raise ValueError("Candidate contains changes beyond the two version declarations")
|
||||
return version, requires_python, candidate_commit
|
||||
|
||||
|
||||
def _source_payload(root: Path, source: dict[str, bytes], prefix: str) -> dict[str, bytes]:
|
||||
"""Bind shipped application files to the clean candidate, not its commit label."""
|
||||
tracked = set(_git(root, "ls-files", "-z", trim=False).split("\0")) - {""}
|
||||
build = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["tool"]["hatch"]["build"]
|
||||
# The sdist ships the tracked nanobot tree. Read its actual exclusions rather
|
||||
# than maintaining a second list of channel test directories here.
|
||||
exclusions = [*build.get("exclude", []), *build["targets"]["sdist"].get("exclude", [])]
|
||||
expected = {name: name for name in tracked if name.startswith("nanobot/")
|
||||
and not any(fnmatchcase(name, pattern) for pattern in exclusions)}
|
||||
# The build hook copies tracked docs into the built-in documentation skill.
|
||||
# Verify both copies: rebuilding the sdist must use the same reviewed bytes.
|
||||
for name in tracked:
|
||||
if (name.startswith("docs/") and name.endswith(".md")
|
||||
and not any(fnmatchcase(name, pattern) for pattern in exclusions)):
|
||||
if source.get(prefix + name) != (root / name).read_bytes():
|
||||
raise ValueError(f"Source documentation differs from the candidate: {name}")
|
||||
expected["nanobot/skills/nanobot-document/references/" + name.removeprefix("docs/")] = name
|
||||
payload = {name.removeprefix(prefix): data for name, data in source.items()
|
||||
if name.startswith(prefix + "nanobot/")}
|
||||
generated = {name for name in payload if name == "nanobot/_build_commit.txt"
|
||||
or name.startswith("nanobot/web/dist/")}
|
||||
if payload.keys() - generated != expected.keys():
|
||||
raise ValueError("Source application payload has missing or unexpected files")
|
||||
for name, data in payload.items():
|
||||
if name in generated:
|
||||
continue
|
||||
if data != (root / expected[name]).read_bytes():
|
||||
raise ValueError(f"Source application payload differs from the candidate: {name}")
|
||||
return payload
|
||||
|
||||
|
||||
def verify_candidate(root: Path, artifacts: Path, *, source_commit: str) -> ReleaseManifest:
|
||||
version, requires_python, candidate_commit = _candidate_identity(root, source_commit)
|
||||
expected = release_filenames(version)
|
||||
present = {path.name for path in artifacts.iterdir()}
|
||||
if present - {"release-manifest.json"} != expected:
|
||||
raise ValueError("Artifact directory must contain exactly the complete release upload set")
|
||||
for name in expected:
|
||||
if (artifacts / name).is_symlink() or not (artifacts / name).is_file():
|
||||
raise ValueError(f"Release artifact must be a regular file: {name}")
|
||||
commit_bytes = (candidate_commit + "\n").encode()
|
||||
source = source_files((artifacts / f"nanobot_ai-{version}.tar.gz").read_bytes())
|
||||
prefix = f"nanobot_ai-{version}/"
|
||||
source_metadata = BytesParser().parsebytes(source[f"{prefix}PKG-INFO"])
|
||||
if (source_metadata["Name"], source_metadata["Version"], source_metadata["Requires-Python"]) != (
|
||||
"nanobot-ai", version, requires_python,
|
||||
):
|
||||
raise ValueError("Source distribution metadata differs from the candidate")
|
||||
for name in VERSION_FILES:
|
||||
if source[f"{prefix}{name}"] != (root / name).read_bytes():
|
||||
raise ValueError(f"Source distribution differs from candidate: {name}")
|
||||
if (source.get(f"{prefix}nanobot/_build_commit.txt") != commit_bytes
|
||||
or not source.get(f"{prefix}nanobot/web/dist/index.html")):
|
||||
raise ValueError("Source distribution must contain the candidate commit and built WebUI")
|
||||
payload = _source_payload(root, source, prefix)
|
||||
for target, platform in PLATFORMS.items():
|
||||
wheel = artifacts / f"nanobot_ai-{version}-py3-none-{platform}.whl"
|
||||
files, modes, info = wheel_files(wheel, version, platform=platform)
|
||||
package_metadata = BytesParser().parsebytes(files[f"{info}/METADATA"])
|
||||
if package_metadata["Requires-Python"] != requires_python:
|
||||
raise ValueError("Wheel Python requirement differs from the candidate")
|
||||
if files.get("nanobot/_build_commit.txt") != commit_bytes:
|
||||
raise ValueError("Wheel build commit differs from the candidate")
|
||||
if not files.get("nanobot/web/dist/index.html"):
|
||||
raise ValueError("Wheel is missing its compiled WebUI")
|
||||
application = {name: data for name, data in files.items()
|
||||
if name.startswith("nanobot/") and not name.startswith("nanobot/tui/bin/")}
|
||||
if application != payload:
|
||||
raise ValueError(f"Wheel application payload differs from the source distribution: {target}")
|
||||
bundle = release_bundle(artifacts, target, root=root)
|
||||
embedded = {name.removeprefix("nanobot/tui/bin/"): data for name, data in files.items()
|
||||
if name.startswith("nanobot/tui/bin/")}
|
||||
if embedded != bundle:
|
||||
raise ValueError("Wheel and fallback TUI archive differ")
|
||||
asset = f"nanobot-tui-{target}" + (".exe" if target == "win32-x64" else "")
|
||||
mode = modes[f"nanobot/tui/bin/{asset}"]
|
||||
if not stat.S_ISREG(mode) or stat.S_IMODE(mode) != 0o755:
|
||||
raise ValueError("Installed TUI must retain executable permissions")
|
||||
records: list[ReleaseArtifact] = []
|
||||
for name in sorted(expected):
|
||||
path = artifacts / name
|
||||
with path.open("rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
records.append(ReleaseArtifact(filename=name, size=path.stat().st_size, sha256=digest))
|
||||
return ReleaseManifest(
|
||||
version=version, source_commit=source_commit, candidate_commit=candidate_commit,
|
||||
requires_python=requires_python,
|
||||
artifacts=records,
|
||||
)
|
||||
|
||||
|
||||
def _write_candidate_text(payload: str, output: Path) -> None:
|
||||
if output.exists():
|
||||
if output.read_text(encoding="utf-8") == payload:
|
||||
return
|
||||
raise FileExistsError(f"Existing {output.name} differs; do not overwrite candidate evidence")
|
||||
with tempfile.TemporaryDirectory(prefix=".candidate-report-", dir=output.parent) as temporary:
|
||||
candidate = Path(temporary) / "report"
|
||||
candidate.write_text(payload, encoding="utf-8")
|
||||
output.hardlink_to(candidate)
|
||||
|
||||
|
||||
def write_manifest(manifest: ReleaseManifest, output: Path) -> None:
|
||||
_write_candidate_text(manifest.model_dump_json(indent=2) + "\n", output)
|
||||
|
||||
|
||||
def write_install_guide(root: Path, artifacts: Path, output: Path, *, source_commit: str) -> None:
|
||||
"""Reverify the immutable upload set before emitting a manual installation handoff."""
|
||||
if output.resolve().is_relative_to(artifacts.resolve()):
|
||||
raise ValueError("Install guide must be outside the immutable artifact directory")
|
||||
payload = (artifacts / "release-manifest.json").read_bytes()
|
||||
recorded = ReleaseManifest.model_validate_json(payload)
|
||||
manifest = verify_candidate(root, artifacts, source_commit=source_commit)
|
||||
if recorded != manifest:
|
||||
raise ValueError("Candidate differs from its recorded release manifest")
|
||||
# Older retained candidates may not have the bootstrap options. Only link a
|
||||
# candidate's scripts when they are the known implementation shipped here.
|
||||
bootstrap = all(
|
||||
(root / "scripts" / name).is_file()
|
||||
and (root / "scripts" / name).read_bytes() == (ROOT / "scripts" / name).read_bytes()
|
||||
for name in ("install.sh", "install.ps1")
|
||||
)
|
||||
digest = hashlib.sha256(payload).hexdigest() if bootstrap else None
|
||||
_write_candidate_text(render_install_guide(manifest, manifest_sha256=digest), output)
|
||||
|
||||
|
||||
def assemble_candidate(root: Path, output: Path, *, wheel: Path, sdist: Path,
|
||||
tui_dir: Path, source_commit: str) -> ReleaseManifest:
|
||||
"""Assemble in a fresh directory; failed output is never given a manifest."""
|
||||
version, _, _ = _candidate_identity(root, source_commit)
|
||||
if sdist.name != f"nanobot_ai-{version}.tar.gz":
|
||||
raise ValueError("Source distribution filename differs from the candidate")
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
for target in PLATFORMS:
|
||||
build_wheel(wheel, tui_dir, output, target, root=root)
|
||||
for name in sorted(release_filenames(version)):
|
||||
if not name.endswith(".whl"):
|
||||
shutil.copyfile(sdist if name == sdist.name else tui_dir / name, output / name)
|
||||
manifest = verify_candidate(root, output, source_commit=source_commit)
|
||||
write_manifest(manifest, output / "release-manifest.json")
|
||||
return manifest
|
||||
|
||||
|
||||
def retain_candidate(root: Path, artifacts: Path, output: Path, *, source_commit: str) -> None:
|
||||
"""Preserve checked bytes and their source, without publishing or rebuilding.
|
||||
|
||||
A successful handoff has a final handoff.json. Partial copies are not accepted
|
||||
release inputs. The self-contained shallow repository preserves the candidate
|
||||
and its source parent, not unrelated history, untracked files or credentials.
|
||||
"""
|
||||
root, artifacts, output = root.resolve(), artifacts.resolve(), output.resolve()
|
||||
if output.is_relative_to(root) or output.is_relative_to(artifacts):
|
||||
raise ValueError("Retained handoff must be outside the checkout and artifact directory")
|
||||
recorded = (artifacts / "release-manifest.json").read_bytes()
|
||||
manifest = verify_candidate(root, artifacts, source_commit=source_commit)
|
||||
if ReleaseManifest.model_validate_json(recorded) != manifest:
|
||||
raise ValueError("Candidate differs from its recorded release manifest")
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
retained = output / "artifacts"
|
||||
retained.mkdir()
|
||||
for name in sorted(release_filenames(manifest.version) | {"release-manifest.json"}):
|
||||
shutil.copyfile(artifacts / name, retained / name)
|
||||
# Check the actual copies, not a report for the source directory. A future
|
||||
# publisher must consume these bytes and verify this manifest again.
|
||||
if ((retained / "release-manifest.json").read_bytes() != recorded
|
||||
or verify_candidate(root, retained, source_commit=source_commit) != manifest):
|
||||
raise ValueError("Retained artifacts differ from the reviewed candidate")
|
||||
source = output / "source.git"
|
||||
with tempfile.TemporaryDirectory(prefix=".candidate-template-", dir=output) as template:
|
||||
# File transport copies real objects rather than borrowing alternates.
|
||||
# Two commits retain the exact version-only candidate relationship.
|
||||
_git(root, "-c", f"init.templateDir={template}", "clone", "--bare", "--depth", "2",
|
||||
"--single-branch", "--no-tags", root.as_uri(), str(source))
|
||||
(source / "config").write_text("[core]\nrepositoryformatversion = 0\nbare = true\n", encoding="utf-8")
|
||||
_git(source, "fsck", "--full")
|
||||
if _git(source, "rev-parse", "HEAD") != manifest.candidate_commit:
|
||||
raise ValueError("Retained source differs from the candidate")
|
||||
write_install_guide(root, retained, output / "install.md", source_commit=source_commit)
|
||||
_write_candidate_text(json.dumps({
|
||||
"version": manifest.version, "source_commit": source_commit,
|
||||
"candidate_commit": manifest.candidate_commit,
|
||||
"manifest_sha256": hashlib.sha256(recorded).hexdigest(),
|
||||
"source_depth": 2,
|
||||
"published": False,
|
||||
}, indent=2) + "\n", output / "handoff.json")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--root", type=Path, default=ROOT)
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
prepare = commands.add_parser("prepare")
|
||||
prepare.add_argument("--source-commit", required=True)
|
||||
prepare.add_argument("--base", required=True)
|
||||
prepare.add_argument("--sequence", type=int, required=True)
|
||||
prepare.add_argument("--output", type=Path, required=True)
|
||||
verify = commands.add_parser("verify")
|
||||
verify.add_argument("--source-commit", required=True)
|
||||
verify.add_argument("--artifacts", type=Path, required=True)
|
||||
instructions = commands.add_parser("instructions")
|
||||
instructions.add_argument("--source-commit", required=True)
|
||||
instructions.add_argument("--artifacts", type=Path, required=True)
|
||||
instructions.add_argument("--output", type=Path, required=True)
|
||||
retain = commands.add_parser("retain")
|
||||
retain.add_argument("--source-commit", required=True)
|
||||
retain.add_argument("--artifacts", type=Path, required=True)
|
||||
retain.add_argument("--output", type=Path, required=True)
|
||||
assemble = commands.add_parser("assemble")
|
||||
assemble.add_argument("--source-commit", required=True)
|
||||
assemble.add_argument("--wheel", type=Path, required=True)
|
||||
assemble.add_argument("--sdist", type=Path, required=True)
|
||||
assemble.add_argument("--tui-dir", type=Path, required=True)
|
||||
assemble.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
if args.command == "prepare":
|
||||
print(json.dumps(prepare_preview(args.root, args.output, source_commit=args.source_commit,
|
||||
base=args.base, sequence=args.sequence)))
|
||||
elif args.command == "verify":
|
||||
manifest = verify_candidate(args.root, args.artifacts, source_commit=args.source_commit)
|
||||
write_manifest(manifest, args.artifacts / "release-manifest.json")
|
||||
print(manifest.model_dump_json(indent=2))
|
||||
elif args.command == "instructions":
|
||||
write_install_guide(args.root, args.artifacts, args.output, source_commit=args.source_commit)
|
||||
print(f"Candidate install handoff: {args.output}")
|
||||
elif args.command == "retain":
|
||||
retain_candidate(args.root, args.artifacts, args.output, source_commit=args.source_commit)
|
||||
print(f"Retained exact candidate (not published): {args.output}")
|
||||
else:
|
||||
manifest = assemble_candidate(args.root, args.output, wheel=args.wheel, sdist=args.sdist,
|
||||
tui_dir=args.tui_dir, source_commit=args.source_commit)
|
||||
print(manifest.model_dump_json(indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Render the initial manual install handoff for a verified release candidate.
|
||||
|
||||
This is not a channel resolver or an updater. The caller must verify the candidate
|
||||
bytes first; public availability, migration notes and native acceptance are release
|
||||
gates, not properties inferred from a manifest.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from typing import Literal
|
||||
|
||||
from nanobot.releases import PLATFORMS, ReleaseArtifact, ReleaseManifest
|
||||
|
||||
Owner = Literal["uv", "pipx", "pip"]
|
||||
PLATFORM_LABELS = {
|
||||
"darwin-arm64": "macOS 13+ · Apple silicon",
|
||||
"darwin-x64": "macOS 13+ · Intel x64",
|
||||
"linux-arm64": "Linux · glibc 2.17+ · ARM64",
|
||||
"linux-x64": "Linux · glibc 2.17+ · x64",
|
||||
"win32-x64": "Windows · x64",
|
||||
}
|
||||
|
||||
# Uses only Python's standard library, so the first preview can be installed before
|
||||
# the user's nanobot has a channel-aware updater. The downloaded file is retained:
|
||||
# managers can record its location as the installation source.
|
||||
VERIFY_AND_INSTALL = '''from pathlib import Path
|
||||
import hashlib
|
||||
import subprocess
|
||||
import sys
|
||||
wheel = Path(sys.argv[1]).resolve(strict=True)
|
||||
with wheel.open("rb") as stream:
|
||||
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if wheel.stat().st_size != int(sys.argv[2]) or digest != sys.argv[3]:
|
||||
raise SystemExit("Wheel size or SHA-256 mismatch; no package manager was started.")
|
||||
command = sys.argv[4:]
|
||||
if command[0] == "python":
|
||||
command[0] = sys.executable
|
||||
subprocess.run([*command, "nanobot-ai @ " + wheel.as_uri()], check=True)
|
||||
'''
|
||||
|
||||
|
||||
def install_command(manifest: ReleaseManifest, artifact: ReleaseArtifact, *,
|
||||
owner: Owner, existing: bool) -> list[str]:
|
||||
"""Verify saved bytes before asking the original owner to install that file."""
|
||||
if not artifact.filename.endswith(".whl"):
|
||||
raise ValueError("Install instructions require a platform wheel")
|
||||
if artifact not in manifest.artifacts:
|
||||
raise ValueError("Artifact does not belong to this release")
|
||||
if owner == "uv":
|
||||
command = ["uv", "tool", "upgrade" if existing else "install", "--no-python-downloads"]
|
||||
elif owner == "pipx":
|
||||
command = ["pipx", "install", "--skip-maintenance", *(["--upgrade"] if existing else [])]
|
||||
elif owner == "pip":
|
||||
command = ["python", "-I", "-m", "pip", "install", *(["--upgrade"] if existing else [])]
|
||||
else:
|
||||
raise ValueError(f"Unsupported installation owner: {owner}")
|
||||
return ["python", "-I", "-c", VERIFY_AND_INSTALL, artifact.filename,
|
||||
str(artifact.size), artifact.sha256, *command]
|
||||
|
||||
|
||||
def verification_command(owner: Owner, *, windows: bool) -> str:
|
||||
"""Inspect the persistent environment, never an ephemeral uvx/pipx run cache."""
|
||||
if owner == "pip":
|
||||
return "python -I -m nanobot --version"
|
||||
directory = "uv tool dir" if owner == "uv" else "pipx environment --value PIPX_LOCAL_VENVS"
|
||||
if windows:
|
||||
return f"& (Join-Path ({directory}) 'nanobot-ai\\Scripts\\python.exe') -I -m nanobot --version"
|
||||
return f'"$({directory})/nanobot-ai/bin/python" -I -m nanobot --version'
|
||||
|
||||
|
||||
def render_install_command(command: list[str], *, windows: bool) -> str:
|
||||
"""Render install_command's Python helper for the target shell."""
|
||||
if not windows:
|
||||
return shlex.join(command)
|
||||
# Windows PowerShell strips embedded quotes from native -c arguments. Feed
|
||||
# the fixed ASCII helper on stdin instead; wheel identity remains in argv.
|
||||
arguments = " ".join("'" + value.replace("'", "''") + "'" for value in command[4:])
|
||||
return f"@'\n{command[3].rstrip()}\n'@ | python -I - {arguments}"
|
||||
|
||||
|
||||
def bootstrap_commands(manifest: ReleaseManifest, manifest_sha256: str) -> tuple[str, str]:
|
||||
"""Pin the installer to the candidate and the download to verified manifest bytes."""
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", manifest_sha256):
|
||||
raise ValueError("Use the verified release manifest SHA-256")
|
||||
base = f"https://raw.githubusercontent.com/HKUDS/nanobot/{manifest.candidate_commit}/scripts"
|
||||
unix = f'''(
|
||||
installer_dir="$(mktemp -d)" || exit 1
|
||||
trap 'rm -f "$installer_dir/install.sh"; rmdir "$installer_dir"' 0
|
||||
curl --fail --silent --show-error --location --proto '=https' \\
|
||||
'{base}/install.sh' -o "$installer_dir/install.sh" &&
|
||||
sh "$installer_dir/install.sh" --release '{manifest.version}' \\
|
||||
--manifest-sha256 '{manifest_sha256}'
|
||||
)'''
|
||||
windows = f'''$Installer = Join-Path ([IO.Path]::GetTempPath()) ("nanobot-install-" + [guid]::NewGuid() + ".ps1")
|
||||
try {{
|
||||
Invoke-WebRequest -UseBasicParsing -Uri '{base}/install.ps1' -OutFile $Installer -ErrorAction Stop
|
||||
& $Installer -Release '{manifest.version}' -ManifestSha256 '{manifest_sha256}'
|
||||
if ($LASTEXITCODE -ne 0) {{ throw "Installation did not complete; review the output above." }}
|
||||
}} finally {{
|
||||
Remove-Item -LiteralPath $Installer -ErrorAction SilentlyContinue
|
||||
}}'''
|
||||
return unix, windows
|
||||
|
||||
|
||||
def render_install_guide(manifest: ReleaseManifest, *, manifest_sha256: str | None = None) -> str:
|
||||
release_url = f"https://github.com/HKUDS/nanobot/releases/tag/v{manifest.version}"
|
||||
lines = [
|
||||
f"# Install nanobot {manifest.version}", "",
|
||||
"> Candidate handoff — not publication approval. Use these commands only after",
|
||||
"> the maintainer has published and publicly verified this exact release, added",
|
||||
"> its changes/migration/recovery notes, and declared its native test coverage.", "",
|
||||
f"- Release: [{manifest.version}]({release_url})",
|
||||
f"- Source commit: `{manifest.source_commit}`",
|
||||
f"- Packaged candidate: `{manifest.candidate_commit}`",
|
||||
f"- Python requirement: `{manifest.requires_python}`", "",
|
||||
"The wheel contains the built WebUI and matching native TUI. Installing nanobot",
|
||||
"itself needs no Bun, Node or Git. Python and third-party dependencies have their",
|
||||
"own requirements. Commands pin this one release; they do not subscribe to Preview.", "",
|
||||
"## Before installing", "",
|
||||
"1. Read this release's changes, known limitations and recovery instructions.",
|
||||
" Prefer a separate environment **and separate data/profile/port** for an early",
|
||||
" preview. A second environment alone does not isolate the default nanobot data.",
|
||||
"2. For an existing install, identify its manager, interpreter and supervisor.",
|
||||
" Finish active tasks, stop all affected writers through that supervisor, and",
|
||||
" back up nanobot configuration/sessions and the owner's install metadata.",
|
||||
" Do not install into a running gateway or assume this guide performs a backup.",
|
||||
"3. Use automatic platform selection when offered below. For the manual route,",
|
||||
" choose the target computer's platform, then **one** owner/operation.",
|
||||
" Fresh commands are only for a new install; existing commands must target the",
|
||||
" same account and manager home. For pip, activate the intended ordinary venv",
|
||||
" and verify `python` belongs to it; never use system Python or a uv/pipx venv.", "",
|
||||
"4. For the manual route, download the linked wheel into a directory you own. Open",
|
||||
" a terminal in that directory. Each command uses Python 3.11+ (`python`) to",
|
||||
" verify the saved file's size and SHA-256 **before** starting the manager.",
|
||||
" For uv/pipx this helper Python does not replace the tool's interpreter.",
|
||||
" Keep the wheel at that path: the manager may record it as the install source.", "",
|
||||
"These commands cover a base `nanobot-ai` installation. If you use extras,",
|
||||
"pipx constraints/options/suffix/lock, custom wrappers or several installations,",
|
||||
"review the recorded",
|
||||
"spec and target explicitly instead of copying a base-package command. Preserve",
|
||||
"extras, injected packages, Python and index settings. Docker, Desktop, editable",
|
||||
"checkouts and system packages use their own deployment instructions.", "",
|
||||
"Command versions checked by the installer fixtures: uv 0.11.16 and pipx 1.17.12.",
|
||||
"Check your manager's version/help; older versions may not support these flags.",
|
||||
"This guide does not upgrade the manager. uv retains existing version constraints;",
|
||||
"pipx can skip a pinned/locked package successfully. A zero exit code alone does",
|
||||
"not prove the requested version was installed. Do not force/unpin automatically.", "",
|
||||
]
|
||||
if manifest_sha256 is not None:
|
||||
unix, windows = bootstrap_commands(manifest, manifest_sha256)
|
||||
lines += [
|
||||
"## Automatic platform selection", "",
|
||||
"Run **one** command block on the computer to install or update, after the",
|
||||
"checks above. It downloads this candidate's installer, preserves a recognized",
|
||||
"existing installation owner and selects that Python environment's wheel.",
|
||||
"It verifies the manifest, download size, hash and wheel identity before install.",
|
||||
"Python/dependency compatibility is enforced by the manager; this command does",
|
||||
"not provide a gateway maintenance window, backup or verified restart.", "",
|
||||
"macOS / Linux (Python 3.11+ and curl):", "", "```sh", unix, "```", "",
|
||||
"Windows (Python 3.11+ and PowerShell):", "", "```powershell", windows, "```", "",
|
||||
"Do not bypass a system script-execution policy. Use your approved installation",
|
||||
"route if this script is blocked. These commands target one release, not a",
|
||||
"persistent Preview subscription. The downloaded wheel stays in the private",
|
||||
"nanobot release cache because the original manager may retain its path.", "",
|
||||
"<details>", "<summary>Manual platform and manager commands</summary>", "",
|
||||
]
|
||||
lines += [
|
||||
"## Select the target platform", "",
|
||||
"Use the architecture of the target Python environment, not the browser. No musl",
|
||||
"or Windows ARM64 wheel is provided. x64 native TUI builds require SSE4.2.",
|
||||
"A platform label is not proof of a native test; consult the release's coverage.", "",
|
||||
]
|
||||
for target, platform in PLATFORMS.items():
|
||||
artifact = next(item for item in manifest.artifacts
|
||||
if item.filename.endswith(f"-py3-none-{platform}.whl"))
|
||||
shell = "powershell" if target == "win32-x64" else "sh"
|
||||
lines += [f"### {PLATFORM_LABELS[target]}", "",
|
||||
f"Download: [{artifact.filename}]({manifest.artifact_url(artifact)}) ({artifact.size:,} bytes).",
|
||||
f"SHA-256: `{artifact.sha256}`.", ""]
|
||||
owners: tuple[tuple[Owner, str], ...] = (
|
||||
("uv", "uv tool"), ("pipx", "pipx"), ("pip", "pip in an ordinary venv"),
|
||||
)
|
||||
for owner, title in owners:
|
||||
lines += [f"#### {title}", "", "New installation:", "", f"```{shell}",
|
||||
render_install_command(install_command(manifest, artifact, owner=owner, existing=False),
|
||||
windows=target == "win32-x64"),
|
||||
"```", "", "Existing base-package installation, after stopping and backing up:", "",
|
||||
f"```{shell}",
|
||||
render_install_command(install_command(manifest, artifact, owner=owner, existing=True),
|
||||
windows=target == "win32-x64"),
|
||||
"```", "", "Verify the version from this owner's persistent environment:", "",
|
||||
f"```{shell}", verification_command(owner, windows=target == "win32-x64"), "```", ""]
|
||||
if manifest_sha256 is not None:
|
||||
lines += ["</details>", ""]
|
||||
lines += [
|
||||
"## Verify, restart and recover", "",
|
||||
f"The verification command must report `{manifest.version}`. If it reports another",
|
||||
"version, stop and inspect the manager result and installation identity. Do not",
|
||||
"retry through another manager, run `pipx run`/`uvx`, or clear an intentional pin.", "",
|
||||
"After package verification, restart the original gateway with its original",
|
||||
"supervisor, profile and arguments. Verify that gateway's actual running version",
|
||||
"and readiness, then check that existing sessions can be opened and appended to.",
|
||||
"CLI version output is not proof that an already-running service has updated.", "",
|
||||
"If download or installation fails, retain the error and backup, and do not start",
|
||||
"an unverified environment. Follow the release's owner-specific recovery steps.",
|
||||
"Retry this exact candidate only if it is still eligible. Never replace a backup",
|
||||
"with partially migrated state. A package downgrade is not a data rollback; stop",
|
||||
"all writers and review data compatibility before restoring or downgrading.", "",
|
||||
"GitHub-only previews are not discovered by an ordinary index-only `pip --pre`",
|
||||
"upgrade. A local wheel may remain in a manager receipt or be a one-time override;",
|
||||
"neither means a daily-update subscription has been created.", "",
|
||||
]
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,335 @@
|
||||
"""Probe a wheel installed in a disposable venv, without a frontend toolchain.
|
||||
|
||||
Run with that venv's ``python -I`` and exact expected version/commit. This checks
|
||||
installed identity, real loopback asset responses and native TUI protocol startup.
|
||||
Optionally start a loopback-only gateway with a disposable, unconfigured profile.
|
||||
Neither mode uses a model or claims interactive UI, migration or updater coverage.
|
||||
With --install-wheel, first exercise the public installer in a disposable home.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import hashlib
|
||||
import http.client
|
||||
import importlib.metadata
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path, PurePosixPath
|
||||
|
||||
|
||||
def host_environment(environment: dict[str, str]) -> dict[str, str]:
|
||||
"""Retain OS identity at both isolation boundaries, not user tools/config."""
|
||||
return {key: value for key, value in environment.items()
|
||||
if key.upper() in {"SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT",
|
||||
"PROCESSOR_ARCHITECTURE", "PROCESSOR_ARCHITEW6432",
|
||||
"PROCESSOR_IDENTIFIER", "NUMBER_OF_PROCESSORS"}}
|
||||
|
||||
|
||||
def webui_assets(directory: Path) -> set[str]:
|
||||
"""Check Vite's complete manifest, including lazy chunks, before HTTP probing."""
|
||||
manifest = json.loads((directory / "asset-manifest.json").read_text(encoding="utf-8"))
|
||||
files: set[str] = set()
|
||||
for key, record in manifest.items():
|
||||
for dependency in [*record.get("imports", []), *record.get("dynamicImports", [])]:
|
||||
if dependency not in manifest:
|
||||
raise ValueError(f"Missing WebUI manifest dependency: {key} -> {dependency}")
|
||||
for filename in [record["file"], *record.get("css", []), *record.get("assets", [])]:
|
||||
relative = PurePosixPath(filename)
|
||||
if (relative.is_absolute() or ".." in relative.parts or "\\" in filename
|
||||
or not (directory / filename).resolve().is_relative_to(directory.resolve())):
|
||||
raise ValueError(f"Invalid WebUI asset path: {filename}")
|
||||
if not (directory / filename).is_file() or not (directory / filename).stat().st_size:
|
||||
raise ValueError(f"Missing or empty WebUI asset: {filename}")
|
||||
files.add(filename)
|
||||
html = (directory / "index.html").read_text(encoding="utf-8")
|
||||
entries = set(re.findall(r'(?:src|href)="/(assets/[^"?#]+\.(?:js|css))"', html))
|
||||
if not entries or not entries <= files:
|
||||
raise ValueError("WebUI HTML entrypoints are absent from the compiled manifest")
|
||||
return files
|
||||
|
||||
|
||||
def _wait_for_closed_listeners(ports: tuple[int, ...], *, timeout: float = 5) -> None:
|
||||
"""Require listener teardown, not just the Windows redirector's exit."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
reachable = False
|
||||
for port in ports:
|
||||
with socket.socket() as connection:
|
||||
connection.settimeout(0.2)
|
||||
reachable |= connection.connect_ex(("127.0.0.1", port)) == 0
|
||||
if not reachable:
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError("A probe listener remained reachable after stopping its gateway")
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
def gateway_probe(version: str, directory: Path) -> dict[str, object]:
|
||||
"""Probe the installed CLI, actual readiness and WebUI, then stop only our child."""
|
||||
directory.mkdir(mode=0o700)
|
||||
config = directory / "config.json"
|
||||
token = secrets.token_urlsafe(32)
|
||||
# If another process wins the bind race, the child must fail; its unique
|
||||
# bootstrap secret prevents accepting that other server's identity response.
|
||||
with socket.socket() as health_socket, socket.socket() as web_socket:
|
||||
health_socket.bind(("127.0.0.1", 0))
|
||||
web_socket.bind(("127.0.0.1", 0))
|
||||
health_port, web_port = health_socket.getsockname()[1], web_socket.getsockname()[1]
|
||||
config.write_text(json.dumps({
|
||||
"agents": {"defaults": {"workspace": str(directory / "workspace")}},
|
||||
"gateway": {"host": "127.0.0.1", "port": health_port, "heartbeat": {"enabled": False}},
|
||||
"channels": {"websocket": {"enabled": True, "host": "127.0.0.1", "port": web_port,
|
||||
"tokenIssueSecret": token, "websocketRequiresToken": True}},
|
||||
"tools": {"mcpServers": {}},
|
||||
}), encoding="utf-8")
|
||||
config.chmod(0o600)
|
||||
|
||||
def get(port: int, path: str) -> tuple[int, bytes]:
|
||||
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=2)
|
||||
try:
|
||||
connection.request("GET", path, headers={"X-Nanobot-Auth": token})
|
||||
response = connection.getresponse()
|
||||
return response.status, response.read(2 * 1024 * 1024)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
command = [sys.executable, "-I", "-m", "nanobot", "gateway", "--foreground", "--config", str(config)]
|
||||
# A file avoids pipe backpressure; print only a bounded, redacted tail on failure.
|
||||
with (directory / "gateway.log").open("w+b") as log:
|
||||
process = subprocess.Popen(command, cwd=directory, stdout=log, stderr=log)
|
||||
try:
|
||||
try:
|
||||
deadline = time.monotonic() + 45
|
||||
while True:
|
||||
if process.poll() is not None:
|
||||
raise ValueError(f"Installed gateway exited before readiness: {process.returncode}")
|
||||
try:
|
||||
code, body = get(health_port, "/health")
|
||||
if code == 200 and json.loads(body).get("ready") is True:
|
||||
break
|
||||
except (OSError, ValueError, http.client.HTTPException):
|
||||
pass
|
||||
if time.monotonic() >= deadline:
|
||||
raise ValueError("Installed gateway did not become ready within 45 seconds")
|
||||
time.sleep(0.2)
|
||||
code, body = get(web_port, "/webui/terminal")
|
||||
if code != 200 or json.loads(body).get("webui", {}).get("version") != version:
|
||||
raise ValueError("Running gateway did not report the installed candidate version")
|
||||
code, body = get(web_port, "/")
|
||||
if code != 200 or b"<html" not in body.lower() or b"/assets/" not in body:
|
||||
raise ValueError("Running gateway did not serve the built WebUI")
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
# Windows termination is cleanup, not graceful-shutdown proof.
|
||||
if os.name == "nt":
|
||||
# A venv python.exe is a redirector: killing it alone
|
||||
# leaves the actual interpreter and its listeners alive.
|
||||
taskkill = Path(os.environ["SYSTEMROOT"]) / "System32/taskkill.exe"
|
||||
subprocess.run([str(taskkill), "/PID", str(process.pid), "/T", "/F"],
|
||||
check=True, capture_output=True, timeout=10)
|
||||
else:
|
||||
process.send_signal(signal.SIGINT)
|
||||
try:
|
||||
process.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
raise ValueError("Installed gateway required forced cleanup") from None
|
||||
if os.name != "nt" and process.returncode != 0:
|
||||
raise ValueError(f"Installed gateway did not exit cleanly: {process.returncode}")
|
||||
# Windows process-tree termination and TCP teardown need not finish
|
||||
# when the venv redirector exits. Wait for the actual postcondition;
|
||||
# a listener that stays alive must still fail acceptance.
|
||||
_wait_for_closed_listeners((health_port, web_port))
|
||||
except Exception:
|
||||
log.flush()
|
||||
log.seek(max(0, os.fstat(log.fileno()).st_size - 8192))
|
||||
print(log.read().decode("utf-8", errors="replace").replace(token, "[redacted]"), file=sys.stderr)
|
||||
raise
|
||||
return {"gateway_ready": True, "gateway_webui_served": True,
|
||||
"gateway_process_stopped": True, "gateway_graceful_shutdown": os.name != "nt"}
|
||||
|
||||
|
||||
async def verify_installed_release(
|
||||
version: str, commit: str, data_dir: Path, *, gateway: bool = False,
|
||||
) -> dict[str, object]:
|
||||
# Imports deliberately happen only after main has isolated HOME, PATH and cwd.
|
||||
from aiohttp import ClientTimeout, web
|
||||
from aiohttp.test_utils import TestClient, TestServer
|
||||
|
||||
import nanobot
|
||||
from nanobot.build_info import COMMIT
|
||||
from nanobot.cli.tui_launcher import resolve_tui_command
|
||||
from nanobot.webui.build import inspect_webui_bundle
|
||||
from nanobot.webui.local_client_assets import LocalClientAssets
|
||||
|
||||
prefix = Path(sys.prefix).resolve()
|
||||
package = Path(nanobot.__file__).resolve()
|
||||
distribution = importlib.metadata.distribution("nanobot-ai")
|
||||
if (not package.is_relative_to(prefix)
|
||||
or package != Path(str(distribution.locate_file("nanobot/__init__.py"))).resolve()):
|
||||
raise ValueError("Probe imported a checkout or another environment, not the installed wheel")
|
||||
if nanobot.__version__ != version or distribution.version != version or COMMIT != commit:
|
||||
raise ValueError("Installed package version/commit differs from the expected candidate")
|
||||
if any(shutil.which(tool) for tool in ("bun", "node", "npm", "git")):
|
||||
raise ValueError("Frontend development tools must not be on the probe PATH")
|
||||
if os.environ.get("NANOBOT_TUI_NO_DOWNLOAD") != "1":
|
||||
raise ValueError("The installed TUI probe must disable fallback downloads")
|
||||
|
||||
bundle = inspect_webui_bundle()
|
||||
if not bundle.dist_available or bundle.needs_build or bundle.source_available:
|
||||
raise ValueError("Installed wheel must contain a usable WebUI without a source build")
|
||||
assets = LocalClientAssets()
|
||||
if not assets.directory.is_relative_to(package.parent):
|
||||
raise ValueError("WebUI assets do not belong to the installed package")
|
||||
files = webui_assets(assets.directory)
|
||||
app = web.Application()
|
||||
|
||||
async def serve(request: web.Request) -> web.FileResponse:
|
||||
return assets.response(request)
|
||||
|
||||
app.router.add_get("/{path:.*}", serve)
|
||||
async with asyncio.timeout(40), TestClient(
|
||||
TestServer(app, host="127.0.0.1"), timeout=ClientTimeout(total=5),
|
||||
headers={"Accept-Encoding": "identity"},
|
||||
) as client:
|
||||
for filename in ["index.html", "asset-manifest.json", *sorted(files)]:
|
||||
response = await client.get("/" if filename == "index.html" else f"/{filename}")
|
||||
if response.status != 200 or response.headers.get("X-Nanobot-UI") != "local":
|
||||
raise ValueError(f"Installed WebUI asset was not served: {filename}")
|
||||
if await response.read() != (assets.directory / filename).read_bytes():
|
||||
raise ValueError(f"Installed WebUI response differs from its file: {filename}")
|
||||
if filename.endswith((".js", ".css")) and response.content_type == "text/html":
|
||||
raise ValueError(f"WebUI asset unexpectedly served the HTML shell: {filename}")
|
||||
|
||||
command = resolve_tui_command(data_dir=data_dir)
|
||||
executable = Path(command[0]).resolve()
|
||||
if len(command) != 1 or not executable.is_relative_to(package.parent / "tui" / "bin"):
|
||||
raise ValueError("TUI command must use the installed native bundle, not source or cache")
|
||||
if not os.access(executable, os.X_OK):
|
||||
raise ValueError("Installed TUI is not executable")
|
||||
native = subprocess.run(
|
||||
[str(executable), "--desktop-protocol"], check=True, capture_output=True,
|
||||
text=True, encoding="utf-8", timeout=15,
|
||||
)
|
||||
if native.stdout.strip() != "1":
|
||||
raise ValueError("Installed TUI returned an unsupported desktop protocol")
|
||||
runtime = await asyncio.to_thread(gateway_probe, version, data_dir.parent / "gateway") if gateway else {}
|
||||
return {
|
||||
"version": version, "candidate_commit": commit, "package": str(package),
|
||||
"platform": platform.system(), "machine": platform.machine(),
|
||||
"python": platform.python_version(), "webui_assets_served": len(files),
|
||||
"frontend_build_tools_on_path": False, "tui_download_enabled": False,
|
||||
"native_tui": str(executable), "native_protocol_probe": native.stdout.strip(),
|
||||
"gateway_started": gateway, "interactive_ui_e2e": False, **runtime,
|
||||
}
|
||||
|
||||
|
||||
def install_and_probe(wheel: Path, *, version: str, commit: str, gateway: bool, report: Path | None) -> None:
|
||||
"""Exercise the public fresh installer with a real native wheel, no toolchain."""
|
||||
wheel = wheel.resolve(strict=True)
|
||||
scripts = Path(__file__).resolve().parent
|
||||
digest = hashlib.sha256(wheel.read_bytes()).hexdigest()
|
||||
with tempfile.TemporaryDirectory(prefix="nanobot-release-install-") as temporary:
|
||||
root = Path(temporary).resolve()
|
||||
# platform.machine() on Windows reads these OS-provided variables.
|
||||
# Removing them creates an artificial unknown-architecture host, not a
|
||||
# clean installation. Keep host identity, never user package/tool paths.
|
||||
system = host_environment(dict(os.environ))
|
||||
system.update(HOME=str(root), USERPROFILE=str(root), PYTHON=sys._base_executable,
|
||||
NANOBOT_VENV=str(root / "managed"), NANOBOT_BIN_DIR=str(root / "bin"),
|
||||
NANOBOT_SKIP_WIZARD="1", PIP_CONFIG_FILE=os.devnull, PIP_ONLY_BINARY=":all:",
|
||||
PIP_DISABLE_PIP_VERSION_CHECK="1", PIP_NO_INPUT="1", PYTHONUTF8="1",
|
||||
XDG_CONFIG_HOME=str(root / "config"), XDG_CACHE_HOME=str(root / "cache"),
|
||||
XDG_DATA_HOME=str(root / "data"), APPDATA=str(root / "config"),
|
||||
LOCALAPPDATA=str(root / "data"), TMPDIR=str(root), TMP=str(root), TEMP=str(root))
|
||||
if os.name == "nt":
|
||||
system["PATH"] = str(Path(system["SYSTEMROOT"]) / "System32")
|
||||
shell = Path(system["SYSTEMROOT"]) / "System32/WindowsPowerShell/v1.0/powershell.exe"
|
||||
command = [str(shell), "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File",
|
||||
str(scripts / "install.ps1"), "-Wheel", str(wheel), "-Sha256", digest]
|
||||
python = root / "managed/Scripts/python.exe"
|
||||
else:
|
||||
system["PATH"] = "/usr/bin:/bin"
|
||||
command = ["/bin/sh", str(scripts / "install.sh"), "--wheel", str(wheel), "--sha256", digest]
|
||||
python = root / "managed/bin/python"
|
||||
subprocess.run(command, check=True, cwd=root, env=system, timeout=600)
|
||||
receipt = json.loads((root / "managed/nanobot-install.json").read_bytes())
|
||||
if receipt != {"schema_version": 1, "owner": "nanobot-installer",
|
||||
"environment": str((root / "managed").resolve()), "extras": []}:
|
||||
raise ValueError("The public installer did not establish its managed update identity")
|
||||
command = [str(python), "-I", str(Path(__file__).resolve()), "--version", version, "--commit", commit]
|
||||
if gateway:
|
||||
command.append("--gateway")
|
||||
if report:
|
||||
command.extend(["--report", str(report)])
|
||||
subprocess.run(command, check=True, cwd=root, env=system, timeout=120)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--commit", required=True)
|
||||
parser.add_argument("--gateway", action="store_true",
|
||||
help="Also start a disposable loopback gateway; no model calls or user config")
|
||||
parser.add_argument("--report", type=Path)
|
||||
parser.add_argument("--install-wheel", type=Path,
|
||||
help="First run the public installer against this exact wheel in a disposable home")
|
||||
args = parser.parse_args()
|
||||
if args.install_wheel is not None:
|
||||
if not sys.flags.isolated:
|
||||
parser.error("Run the installer probe with python -I")
|
||||
if args.report is not None and args.report.exists():
|
||||
parser.error("Use a new report path; prior evidence must not be overwritten")
|
||||
install_and_probe(args.install_wheel, version=args.version, commit=args.commit,
|
||||
gateway=args.gateway, report=args.report.resolve() if args.report else None)
|
||||
return
|
||||
if not sys.flags.isolated or sys.prefix == sys.base_prefix:
|
||||
parser.error("Run the disposable installation's python -I, not the build/source interpreter")
|
||||
report = args.report.resolve() if args.report else None
|
||||
if report is not None and report.exists():
|
||||
parser.error("Use a new report path; prior evidence must not be overwritten")
|
||||
original_env, original_cwd = dict(os.environ), Path.cwd()
|
||||
with tempfile.TemporaryDirectory(prefix="nanobot-installed-probe-") as temporary:
|
||||
root = Path(temporary).resolve()
|
||||
empty_path = root / "empty-path"
|
||||
empty_path.mkdir()
|
||||
env = host_environment(original_env)
|
||||
env.update({
|
||||
"PATH": str(empty_path), "HOME": str(root), "USERPROFILE": str(root),
|
||||
"XDG_CONFIG_HOME": str(root / "config"), "XDG_CACHE_HOME": str(root / "cache"),
|
||||
"XDG_DATA_HOME": str(root / "data"), "TMPDIR": str(root), "TMP": str(root),
|
||||
"TEMP": str(root), "NANOBOT_TUI_NO_DOWNLOAD": "1", "NO_COLOR": "1",
|
||||
})
|
||||
os.environ.clear()
|
||||
os.environ.update(env)
|
||||
os.chdir(root)
|
||||
try:
|
||||
result = asyncio.run(verify_installed_release(
|
||||
args.version, args.commit, root / "tui", gateway=args.gateway,
|
||||
))
|
||||
finally:
|
||||
os.chdir(original_cwd)
|
||||
os.environ.clear()
|
||||
os.environ.update(original_env)
|
||||
payload = json.dumps(result, indent=2) + "\n"
|
||||
if report is not None:
|
||||
with report.open("x", encoding="utf-8") as stream:
|
||||
stream.write(payload)
|
||||
print(payload, end="")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,772 @@
|
||||
"""Run native packaged upgrade/recovery journeys in a disposable account.
|
||||
|
||||
The healthy target is the exact supplied wheel, not a patched application. The
|
||||
default baseline is explicitly a version-only fixture with a local feed transport
|
||||
and bounded fault injection. It does not stand for an older published release.
|
||||
Use --baseline-wheel to exercise an actual earlier updater-enabled package too.
|
||||
No public feed, user installation, model, credentials or OS service is used.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import base64
|
||||
import csv
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import secrets
|
||||
import socket
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
from urllib.parse import quote
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
SCENARIOS = ("upgrade", "upgrade-again", "skipped-preview", "import-failure", "restart-failure",
|
||||
"backup-failure", "worker-exit", "metadata-loss", "restore-interruption")
|
||||
|
||||
|
||||
def digest(path: Path) -> str:
|
||||
with path.open("rb") as stream:
|
||||
return hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
|
||||
|
||||
def read(path: Path):
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def write(path: Path, value) -> None:
|
||||
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def replace_once(source: bytes, old: bytes, new: bytes) -> bytes:
|
||||
if source.count(old) != 1:
|
||||
raise ValueError("The fault-injection seam changed; review the acceptance fixture")
|
||||
return source.replace(old, new, 1)
|
||||
|
||||
|
||||
def fixture_wheel(source: Path, output: Path, version: str, *, feed: Path | None = None,
|
||||
scenario: str = "upgrade") -> Path:
|
||||
"""Private instrumentation only; never overwrite or relabel the supplied target."""
|
||||
from packaging.utils import parse_wheel_filename
|
||||
|
||||
_, previous, _, _ = parse_wheel_filename(source.name)
|
||||
prefix, replacement = f"nanobot_ai-{previous}.dist-info/", f"nanobot_ai-{version}.dist-info/"
|
||||
with ZipFile(source) as archive:
|
||||
entries = [(item, archive.read(item)) for item in archive.infolist() if not item.filename.endswith("/RECORD")]
|
||||
files = {item.filename.replace(prefix, replacement): data for item, data in entries}
|
||||
metadata = replacement + "METADATA"
|
||||
files[metadata] = replace_once(files[metadata], f"Version: {previous}\n".encode(), f"Version: {version}\n".encode())
|
||||
if feed is not None:
|
||||
# This existing injectable transport runs in both planner and preflight
|
||||
# processes. It cannot reach external hosts. These private packages are
|
||||
# not approved public releases: signature admission is exercised by the
|
||||
# separate trust tests, not this installation/recovery fixture.
|
||||
files["nanobot/_acceptance_feed.py"] = f'''import json
|
||||
from pathlib import Path
|
||||
import httpx
|
||||
def transport():
|
||||
def respond(request):
|
||||
record = json.loads(Path({str(feed)!r}).read_text(encoding="utf-8"))
|
||||
if request.method != "GET" or str(request.url) not in record:
|
||||
raise ValueError("Unexpected acceptance feed request: " + str(request.url))
|
||||
item = record[str(request.url)]
|
||||
return httpx.Response(200, content=Path(item["file"]).read_bytes() if "file" in item else json.dumps(item["json"]).encode())
|
||||
return httpx.MockTransport(respond)
|
||||
'''.encode()
|
||||
files["nanobot/release_feed.py"] = replace_once(
|
||||
files["nanobot/release_feed.py"], b"transport=transport or PinnedDNSAsyncTransport(),",
|
||||
b'transport=transport or __import__("nanobot._acceptance_feed", fromlist=["transport"]).transport(),')
|
||||
if b"await self._authorize(target)" in files["nanobot/release_feed.py"]:
|
||||
files["nanobot/release_feed.py"] = replace_once(
|
||||
files["nanobot/release_feed.py"], b"await self._authorize(target)",
|
||||
b"pass # Private unsigned acceptance fixture, never a distributable wheel.")
|
||||
# Windows source archives can contain CRLF. Normalize only the private
|
||||
# instrumentation copy; the final target's bytes remain untouched.
|
||||
worker = files["nanobot/update_worker.py"].replace(b"\r\n", b"\n")
|
||||
# Inject into the first job in this disposable account. The recovered
|
||||
# updater must subsequently install a release without re-injecting it.
|
||||
fault = f"__import__('pathlib').Path({str(feed.parent / 'injected-fault')!r})"
|
||||
if scenario == "worker-exit":
|
||||
needle = b' env = {key: value for key, value in os.environ.items() if not key.upper().startswith("PIP_")}\n'
|
||||
worker = replace_once(worker, needle, f''' if not {fault}.exists():
|
||||
{fault}.touch()
|
||||
(directory / 'fault-fired').write_text('worker exit')
|
||||
os._exit(91)
|
||||
'''.encode() + needle)
|
||||
elif scenario == "metadata-loss":
|
||||
needle = b"\n _verify(spec, directory)\n"
|
||||
worker = replace_once(worker, needle, f'''
|
||||
if not {fault}.exists():
|
||||
{fault}.touch()
|
||||
(directory / 'fault-fired').write_text('metadata loss')
|
||||
next(Path(spec.baseline.environment).rglob('nanobot_ai-' + spec.version + '.dist-info/METADATA')).unlink()
|
||||
os._exit(92)
|
||||
'''.encode() + needle)
|
||||
elif scenario == "backup-failure":
|
||||
needle = b" ensure_backup(directory, spec.backup_sources,\n"
|
||||
worker = replace_once(worker, needle, f''' if not {fault}.exists():
|
||||
{fault}.write_text(str(directory))
|
||||
if {fault}.read_text() == str(directory):
|
||||
raise OSError('Injected backup write failure')
|
||||
'''.encode() + needle)
|
||||
files["nanobot/update_worker.py"] = worker
|
||||
if scenario == "restore-interruption":
|
||||
needle = b" os.rename(original, environment)\n"
|
||||
files["nanobot/update_fallback.py"] = replace_once(files["nanobot/update_fallback.py"].replace(b"\r\n", b"\n"), needle, b''' if not (directory / 'restore-fault-fired').exists():
|
||||
(directory / 'restore-fault-fired').write_text('interrupted between renames')
|
||||
raise OSError('Injected rename interruption')
|
||||
''' + needle)
|
||||
elif scenario in {"import-failure", "restore-interruption"}:
|
||||
files["nanobot/__init__.py"] = b"raise RuntimeError('Injected candidate import failure')\n"
|
||||
elif scenario == "restart-failure":
|
||||
files["nanobot/update_restart.py"] = b"raise RuntimeError('Injected candidate startup failure')\n"
|
||||
record = replacement + "RECORD"
|
||||
rows = io.StringIO()
|
||||
writer = csv.writer(rows, lineterminator="\n")
|
||||
for name, content in files.items():
|
||||
writer.writerow((name, "sha256=" + base64.urlsafe_b64encode(hashlib.sha256(content).digest()).rstrip(b"=").decode(), len(content)))
|
||||
writer.writerow((record, "", ""))
|
||||
files[record] = rows.getvalue().encode()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
result = output / source.name.replace(f"-{previous}-", f"-{version}-", 1)
|
||||
info = {item.filename.replace(prefix, replacement): item for item, _ in entries}
|
||||
with ZipFile(result, "x", compression=ZIP_DEFLATED) as archive:
|
||||
for name, content in files.items():
|
||||
if name in info:
|
||||
item = info[name]
|
||||
item.filename = name # Retain native executable permissions.
|
||||
archive.writestr(item, content)
|
||||
else:
|
||||
archive.writestr(name, content)
|
||||
return result
|
||||
|
||||
|
||||
def feed_records(wheel: Path, commit: str, *, generation: int = 1) -> dict:
|
||||
from packaging.utils import parse_wheel_filename
|
||||
from packaging.version import Version
|
||||
|
||||
from nanobot.release_feed import CATALOGUE_URL
|
||||
from nanobot.releases import (
|
||||
ReleaseArtifact,
|
||||
ReleaseCatalogue,
|
||||
ReleaseManifest,
|
||||
ReleasePointer,
|
||||
release_filenames,
|
||||
)
|
||||
|
||||
version = str(parse_wheel_filename(wheel.name)[1])
|
||||
artifacts = [ReleaseArtifact(filename=name, size=wheel.stat().st_size if name == wheel.name else 1,
|
||||
sha256=digest(wheel) if name == wheel.name else "a" * 64)
|
||||
for name in sorted(release_filenames(version))]
|
||||
if not Version(version).is_prerelease:
|
||||
base = "https://files.pythonhosted.org/packages/"
|
||||
metadata = {"info": {"name": "nanobot-ai", "version": version, "requires_python": ">=3.11"},
|
||||
"urls": [{"filename": item.filename, "size": item.size, "url": base + item.filename,
|
||||
"digests": {"sha256": item.sha256}, "yanked": False}
|
||||
for item in artifacts if item.filename.endswith((".whl", ".tar.gz"))]}
|
||||
return {base + wheel.name: {"file": str(wheel)},
|
||||
"https://pypi.org/pypi/nanobot-ai/json": {"json": metadata},
|
||||
f"https://pypi.org/pypi/nanobot-ai/{version}/json": {"json": metadata}}
|
||||
manifest = ReleaseManifest(version=version, source_commit=commit, candidate_commit=commit,
|
||||
requires_python=">=3.11", artifacts=artifacts)
|
||||
data = manifest.model_dump(mode="json")
|
||||
pointer = ReleasePointer(version=version, candidate_commit=commit,
|
||||
manifest_sha256=hashlib.sha256(json.dumps(data).encode()).hexdigest())
|
||||
catalogue = ReleaseCatalogue(generation=generation, preview=pointer)
|
||||
base = f"https://github.com/HKUDS/nanobot/releases/download/v{version}/"
|
||||
return {CATALOGUE_URL: {"json": catalogue.model_dump(mode="json")},
|
||||
base + "release-manifest.json": {"json": data}, base + wheel.name: {"file": str(wheel)}}
|
||||
|
||||
|
||||
def free_port() -> int:
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
return listener.getsockname()[1]
|
||||
|
||||
|
||||
def gateway(root: Path, *arguments: str) -> None:
|
||||
subprocess.run([sys.executable, "-I", "-m", "nanobot", "gateway", *arguments,
|
||||
"--config", str(root / "account/.nanobot/config.json")], check=True, timeout=60)
|
||||
|
||||
|
||||
def _dock_supported(root: Path) -> bool:
|
||||
return bool(read(root / "case.json").get("dock")
|
||||
and importlib.util.find_spec("nanobot.cli.dock") is not None)
|
||||
|
||||
|
||||
def _desktop_webui(root: Path) -> None:
|
||||
# The real managed receipt must select automatic detachment, not a test flag.
|
||||
subprocess.run([sys.executable, "-I", "-m", "nanobot", "webui", "--yes", "--no-open",
|
||||
"--config", str(root / "account/.nanobot/config.json")], check=True, timeout=60)
|
||||
|
||||
|
||||
def _dock_socket(root: Path) -> Path:
|
||||
from nanobot.cli.dock import _directory
|
||||
from nanobot.cli.webui_support import _webui_browser_url
|
||||
from nanobot.config.loader import load_config
|
||||
from nanobot.gateway.runtime import GatewayInstance
|
||||
|
||||
config = root / "account/.nanobot/config.json"
|
||||
instance = GatewayInstance.resolve(config_path=config)
|
||||
return _directory(instance.paths.state_path, _webui_browser_url(load_config(config))) / "s"
|
||||
|
||||
|
||||
def _wait_dock(address: Path, *, present: bool) -> None:
|
||||
deadline = time.monotonic() + 8
|
||||
while time.monotonic() < deadline:
|
||||
processes = subprocess.run(["/usr/bin/pgrep", "-f", str(address)], capture_output=True,
|
||||
text=True, check=False)
|
||||
count = len(processes.stdout.split())
|
||||
if count == (1 if present else 0):
|
||||
return
|
||||
time.sleep(0.1)
|
||||
raise AssertionError(f"Expected {'one live' if present else 'no'} Dock helper")
|
||||
|
||||
|
||||
def request(root: Path, path: str):
|
||||
import httpx
|
||||
|
||||
config = read(root / "account/.nanobot/config.json")
|
||||
web = config["channels"]["websocket"]
|
||||
base = f'http://127.0.0.1:{web["port"]}'
|
||||
with httpx.Client(timeout=10, trust_env=False) as client:
|
||||
bootstrap = client.get(base + "/webui/bootstrap", headers={"X-Nanobot-Auth": web["tokenIssueSecret"]})
|
||||
bootstrap.raise_for_status()
|
||||
if path == "/webui/bootstrap":
|
||||
return bootstrap.json()
|
||||
headers = ({"X-Nanobot-Auth": web["tokenIssueSecret"]} if path == "/webui/terminal"
|
||||
else {"Authorization": "Bearer " + bootstrap.json()["api_token"]})
|
||||
response = client.get(base + path, headers=headers)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
|
||||
def history(root: Path, key: str):
|
||||
rows = request(root, "/api/sessions")["sessions"]
|
||||
assert key in {row["key"] for row in rows}, rows
|
||||
response = request(root, "/api/sessions/" + quote(key, safe="") + "/webui-thread")
|
||||
# Revision/ETag and gateway identity must change after restart. Compare the
|
||||
# persisted transcript, not that intentionally volatile response envelope.
|
||||
return {name: response[name] for name in ("events", "completed_turn_ids")}
|
||||
|
||||
|
||||
def assert_history_preserved(before: dict, after: dict) -> None:
|
||||
"""Allow only known additive defaults in the older transcript projection."""
|
||||
assert after["completed_turn_ids"] == before["completed_turn_ids"]
|
||||
assert len(after["events"]) == len(before["events"])
|
||||
for previous, current in zip(before["events"], after["events"], strict=True):
|
||||
current = dict(current)
|
||||
# SQLite represents an unknown legacy timestamp as zero. New projection
|
||||
# also exposes the already-persisted inactive goal on a completed turn.
|
||||
# Do not ignore these fields when the old API supplied an actual value.
|
||||
if "created_at_ms" not in previous and current.get("created_at_ms") == 0:
|
||||
del current["created_at_ms"]
|
||||
if (previous["event"] == "turn_end" and "goal_state" not in previous
|
||||
and current.get("goal_state") == {"active": False}):
|
||||
del current["goal_state"]
|
||||
assert current == previous, (current, previous)
|
||||
|
||||
|
||||
def canonical_records(path: Path, tables: tuple[str, ...] = ("sessions", "messages", "checkpoints", "pending_inputs")) -> dict:
|
||||
"""Compare logical records, not SQLite's transient WAL/checkpoint layout."""
|
||||
with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as db:
|
||||
assert db.execute("PRAGMA integrity_check").fetchone() == ("ok",)
|
||||
return {table: [list(row) for row in db.execute(f"SELECT * FROM {table} ORDER BY 1, 2")]
|
||||
for table in tables}
|
||||
|
||||
|
||||
def assert_canonical_preserved(before: dict, after: dict) -> None:
|
||||
"""Schema v2 may add a display-only owner, never model context or lost rows."""
|
||||
key = "websocket:display-only"
|
||||
existing = {row[0] for row in before["sessions"]}
|
||||
added = [row for row in after["sessions"] if row[0] == key and key not in existing]
|
||||
for row in added:
|
||||
# A newly imported display transcript owns an empty Session. Only its
|
||||
# identity/timestamps and the public handle allocated by /api/sessions
|
||||
# are new; it must not manufacture agent context or other metadata.
|
||||
metadata = json.loads(row[3])
|
||||
if metadata:
|
||||
assert set(metadata) == {"session_handle"}, row
|
||||
handle = metadata["session_handle"]
|
||||
assert isinstance(handle, str) and re.fullmatch("[a-z]{4,16}", handle), row
|
||||
revision = 2 if metadata else 1
|
||||
assert row[4:7] == [None, 0, revision] and row[8:] == ["", "", None], row
|
||||
comparable = {**after, "sessions": [row for row in after["sessions"] if row not in added]}
|
||||
assert comparable == before, (comparable, before)
|
||||
|
||||
|
||||
def canonical_context(root: Path) -> dict:
|
||||
context = request(root, "/api/sessions/websocket%3Acanonical-only/context")
|
||||
# Tokenizer availability can alter estimates; stored message content is
|
||||
# checked separately against every canonical SQLite record.
|
||||
return {key: value for key, value in context.items() if not key.startswith("estimated_")}
|
||||
|
||||
|
||||
async def chat(root: Path, chat_id: str | None = None) -> str:
|
||||
import websockets
|
||||
|
||||
bootstrap = request(root, "/webui/bootstrap")
|
||||
async def receive(ws, event):
|
||||
async with asyncio.timeout(30):
|
||||
while True:
|
||||
value = json.loads(await ws.recv())
|
||||
if value.get("event") == event:
|
||||
return value
|
||||
async with websockets.connect(bootstrap["ws_url"] + "?token=" + bootstrap["token"] + "&client_id=package-acceptance") as ws:
|
||||
await receive(ws, "ready")
|
||||
await ws.send(json.dumps({"type": "attach", "chat_id": chat_id} if chat_id else {"type": "new_chat"}))
|
||||
attached = await receive(ws, "attached")
|
||||
chat_id = attached["chat_id"]
|
||||
await ws.send(json.dumps({"type": "message", "chat_id": chat_id, "content": "/model", "webui": True,
|
||||
"turn_id": "acceptance-" + secrets.token_hex(8)}))
|
||||
answer = await receive(ws, "message")
|
||||
assert "acceptance-no-model" in answer["text"], answer
|
||||
await receive(ws, "turn_end")
|
||||
return chat_id
|
||||
|
||||
|
||||
def ready(root: Path, version: str):
|
||||
from nanobot.gateway.runtime import GatewayRuntime
|
||||
from nanobot.update_profiles import inspect_profiles
|
||||
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
profiles = inspect_profiles(str(Path(sys.prefix).resolve()))
|
||||
if len(profiles) == 1:
|
||||
receipt = profiles[0].receipt
|
||||
if GatewayRuntime().verify_ready(receipt.health_identity, maintenance=False):
|
||||
assert receipt.version == version, (receipt.version, version)
|
||||
assert request(root, "/webui/terminal")["webui"]["version"] == version
|
||||
return receipt
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError("The actual installed gateway did not become ready")
|
||||
|
||||
|
||||
def seed(root: Path) -> None:
|
||||
import nanobot
|
||||
from nanobot.config.loader import load_config, save_config, set_config_path
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
|
||||
assert Path(nanobot.__file__).resolve().is_relative_to(Path(sys.prefix).resolve())
|
||||
config_path = root / "account/.nanobot/config.json"
|
||||
config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
set_config_path(config_path)
|
||||
config = load_config(config_path)
|
||||
config.agents.defaults.workspace = str(root / "workspace")
|
||||
config.agents.defaults.provider = "custom"
|
||||
config.agents.defaults.model = "acceptance-no-model"
|
||||
config.agents.defaults.dream.enabled = False
|
||||
config.agents.defaults.session_ttl_minutes = 0
|
||||
config.providers.custom.api_key = "fixture-not-a-secret"
|
||||
config.providers.custom.api_base = "http://127.0.0.1:1/v1"
|
||||
config.gateway.host, config.gateway.port = "127.0.0.1", free_port()
|
||||
config.gateway.heartbeat.enabled = False
|
||||
config.channels.websocket = {"enabled": True, "host": "127.0.0.1", "port": free_port(),
|
||||
"tokenIssueSecret": secrets.token_urlsafe(32), "websocketRequiresToken": True}
|
||||
save_config(config, config_path)
|
||||
# Real historical canonical files are imported by the installed SQLite owner,
|
||||
# not generated by a new-store round trip. Existing source bytes stay readable.
|
||||
if importlib.util.find_spec("nanobot.session.location") is not None:
|
||||
from nanobot.session.location import SessionLocation
|
||||
location = SessionLocation(root / "workspace")
|
||||
else:
|
||||
# The retained pre-SQLite package owns the same namespace here. This is
|
||||
# acceptance-fixture compatibility, not a fallback in the application.
|
||||
from nanobot.session.manager import JsonlSessionStore
|
||||
location = JsonlSessionStore(root / "workspace")
|
||||
sessions = location.sessions_dir
|
||||
key = "websocket:legacy-acceptance"
|
||||
legacy = sessions / (location.storage_key(key) + ".jsonl")
|
||||
legacy.write_text(json.dumps({"_type": "metadata", "key": key, "metadata": {"title": "升级前的聊天"},
|
||||
"created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-01T00:00:00"}) + "\n" +
|
||||
json.dumps({"role": "user", "content": "配置和聊天不能丢失"}, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
canonical_only = sessions / (location.storage_key("websocket:canonical-only") + ".jsonl")
|
||||
canonical_only.write_bytes(legacy.read_bytes().replace(key.encode(), b"websocket:canonical-only"))
|
||||
webui_dir = get_webui_dir()
|
||||
webui_dir.mkdir(parents=True, exist_ok=True)
|
||||
for chat_id in ("legacy-acceptance", "display-only"):
|
||||
events = [{"event": "user", "chat_id": chat_id, "text": "配置和聊天不能丢失"},
|
||||
{"event": "message", "chat_id": chat_id, "text": "独立验收数据"},
|
||||
{"event": "turn_end", "chat_id": chat_id}]
|
||||
(webui_dir / f"websocket_{chat_id}.jsonl").write_text(
|
||||
"".join(json.dumps(event, ensure_ascii=False) + "\n" for event in events), encoding="utf-8")
|
||||
if _dock_supported(root):
|
||||
_desktop_webui(root)
|
||||
_wait_dock(_dock_socket(root), present=True)
|
||||
else:
|
||||
gateway(root, "--background")
|
||||
|
||||
|
||||
def snapshot(root: Path) -> None:
|
||||
from nanobot.config.loader import set_config_path
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
|
||||
case = read(root / "case.json")
|
||||
config_path = root / "account/.nanobot/config.json"
|
||||
set_config_path(config_path)
|
||||
delivery = config_path.parent / "delivery/outbox.sqlite3"
|
||||
if not delivery.exists() and importlib.util.find_spec("nanobot.channels.outbox") is not None:
|
||||
from nanobot.bus.delivery import DeliveryRequest
|
||||
from nanobot.bus.events import OutboundMessage
|
||||
from nanobot.channels.outbox import DeliveryOutbox
|
||||
|
||||
# Keep a real durable result pending through the private journey without
|
||||
# attempting an external send. Older retained code has no outbox owner.
|
||||
with patch("nanobot.channels.outbox.time.time", return_value=time.time() + 3600):
|
||||
DeliveryOutbox(delivery).record(OutboundMessage(
|
||||
"whatsapp", "acceptance-offline", "Retain this scheduled result",
|
||||
delivery=DeliveryRequest("acceptance-run", "websocket:legacy-acceptance", None),
|
||||
))
|
||||
if importlib.util.find_spec("nanobot.session.location") is not None:
|
||||
from nanobot.session.location import SessionLocation
|
||||
location = SessionLocation(root / "workspace")
|
||||
else:
|
||||
from nanobot.session.manager import JsonlSessionStore
|
||||
location = JsonlSessionStore(root / "workspace")
|
||||
sessions, webui_dir = location.sessions_dir, get_webui_dir()
|
||||
key = "websocket:legacy-acceptance"
|
||||
legacy = sessions / (location.storage_key(key) + ".jsonl")
|
||||
canonical_only = sessions / (location.storage_key("websocket:canonical-only") + ".jsonl")
|
||||
receipt = ready(root, case["baseline_version"])
|
||||
chat_id = (read(root / "before.json")["chat_id"] if (root / "before.json").exists()
|
||||
else asyncio.run(chat(root)))
|
||||
before = history(root, "websocket:" + chat_id)
|
||||
legacy_before = history(root, key)
|
||||
display_before = history(root, "websocket:display-only")
|
||||
context_before = canonical_context(root)
|
||||
assert context_before["total_messages"] == 1
|
||||
assert "配置和聊天不能丢失" in json.dumps(legacy_before, ensure_ascii=False)
|
||||
# Immutable files plus public logical records: SQLite/WAL checkpoint bytes
|
||||
# may legitimately change across a clean shutdown without changing a record.
|
||||
preserved = {str(path): digest(path) for path in (legacy, canonical_only,
|
||||
webui_dir / "websocket_legacy-acceptance.jsonl", webui_dir / "websocket_display-only.jsonl")}
|
||||
preserved[str(config_path)] = digest(config_path)
|
||||
write(root / "before.json", {"chat_id": chat_id, "history": before, "legacy": legacy_before,
|
||||
"display_only": display_before, "canonical_only": context_before,
|
||||
"files": preserved, "run_id": receipt.run_id,
|
||||
"database": str(sessions / "sessions.sqlite3"),
|
||||
"delivery": (canonical_records(delivery, ("deliveries",)) if delivery.exists() else None),
|
||||
"canonical": (canonical_records(sessions / "sessions.sqlite3")
|
||||
if (sessions / "sessions.sqlite3").exists() else None)})
|
||||
|
||||
|
||||
def prepare(root: Path) -> None:
|
||||
from packaging.version import Version
|
||||
|
||||
from nanobot.installation_lock import installation_state_dir
|
||||
from nanobot.release_feed import ReleaseFeed
|
||||
from nanobot.update_channel import UpdateChannelRequest, read_update_channel
|
||||
from nanobot.update_jobs import prepare_job, start_handoff
|
||||
from nanobot.update_plan import preview_release_update
|
||||
from nanobot.update_service import UpdateJobService
|
||||
|
||||
if not (root / "before.json").exists():
|
||||
seed(root)
|
||||
snapshot(root)
|
||||
case = read(root / "case.json")
|
||||
|
||||
async def plan_update():
|
||||
state = installation_state_dir()
|
||||
channel = "preview" if Version(case["target_version"]).is_prerelease else "stable"
|
||||
UpdateJobService().change_channel(UpdateChannelRequest(channel=channel, revision=read_update_channel().revision))
|
||||
plan = await preview_release_update(restart_running=True)
|
||||
assert plan.stop_profiles and plan.restart_profiles
|
||||
async with ReleaseFeed(state / "feed") as feed:
|
||||
return await prepare_job(plan, feed)
|
||||
directory = asyncio.run(plan_update())
|
||||
# Capture the production launch, then let the outer, stdlib-only controller
|
||||
# execute it after this process exits. Otherwise Windows DLL locks from the
|
||||
# *test controller* prevent restoring the live venv directory.
|
||||
with patch("nanobot.update_jobs.subprocess.Popen") as spawn:
|
||||
start_handoff(directory, once=True)
|
||||
command = spawn.call_args.args[0]
|
||||
write(root / "launch.json", {"command": command, "directory": str(directory)})
|
||||
|
||||
|
||||
def verify(root: Path) -> dict:
|
||||
import nanobot
|
||||
from nanobot.build_info import COMMIT
|
||||
from nanobot.config.loader import set_config_path
|
||||
from nanobot.update_worker import JobStatus, Phase
|
||||
|
||||
set_config_path(root / "account/.nanobot/config.json")
|
||||
case, before, launch = read(root / "case.json"), read(root / "before.json"), read(root / "launch.json")
|
||||
directory = Path(launch["directory"])
|
||||
restored = case["scenario"] not in {"upgrade", "upgrade-again", "skipped-preview", "worker-exit"}
|
||||
status = JobStatus.read(directory)
|
||||
assert status.phase == (Phase.RESTORED if restored else Phase.SUCCEEDED), status
|
||||
expected = case["baseline_version"] if restored else case["target_version"]
|
||||
receipt = ready(root, expected)
|
||||
assert receipt.run_id != before["run_id"], "Update did not restart the gateway"
|
||||
assert nanobot.__version__ == expected
|
||||
if not restored:
|
||||
assert COMMIT == case["commit"]
|
||||
assert digest(Path(case["target_wheel"])) == case["target_sha256"]
|
||||
sqlite_expected = verify_data(root, expected)
|
||||
if case["scenario"] in {"worker-exit", "metadata-loss"}:
|
||||
assert (directory / "fault-fired").exists()
|
||||
if case["scenario"] in {"worker-exit", "metadata-loss", "backup-failure"}:
|
||||
assert (root / "injected-fault").exists()
|
||||
if case["scenario"] == "restore-interruption":
|
||||
assert (directory / "restore-fault-fired").exists()
|
||||
return {**case, "phase": status.phase.value, "running_version": receipt.version,
|
||||
"restarted": True, "config_and_legacy_bytes_preserved": True,
|
||||
"authenticated_history_preserved": True, "sqlite_records_preserved": True if sqlite_expected else None,
|
||||
"scheduled_delivery_preserved": True if before.get("delivery") is not None else None,
|
||||
"continued_write_and_second_start": True,
|
||||
"dock_socket": str(_dock_socket(root)) if _dock_supported(root) else None,
|
||||
"dock_restart_verified": True if _dock_supported(root) else None}
|
||||
|
||||
|
||||
def verify_data(root: Path, expected: str) -> bool:
|
||||
"""Public reads and subsequent writes, shared by inline and owner-driven updates."""
|
||||
from nanobot.config.loader import set_config_path
|
||||
|
||||
set_config_path(root / "account/.nanobot/config.json")
|
||||
before = read(root / "before.json")
|
||||
receipt = ready(root, expected)
|
||||
assert receipt.run_id != before["run_id"], "Update did not restart the gateway"
|
||||
if _dock_supported(root):
|
||||
from nanobot.gateway.runtime import GatewayInstance
|
||||
|
||||
instance = GatewayInstance.resolve(config_path=root / "account/.nanobot/config.json")
|
||||
# A historical package without this feature cannot record desktop intent.
|
||||
# After that first upgrade, exercise the real new launcher, then restart.
|
||||
if not instance.paths.state_path.with_suffix(".dock").exists():
|
||||
_desktop_webui(root)
|
||||
_wait_dock(_dock_socket(root), present=True)
|
||||
assert {name: digest(Path(name)) for name in before["files"]} == before["files"]
|
||||
key = "websocket:" + before["chat_id"]
|
||||
assert_history_preserved(before["history"], history(root, key))
|
||||
assert_history_preserved(before["legacy"], history(root, "websocket:legacy-acceptance"))
|
||||
assert_history_preserved(before["display_only"], history(root, "websocket:display-only"))
|
||||
assert canonical_context(root) == before["canonical_only"], (canonical_context(root), before["canonical_only"])
|
||||
database = Path(before["database"])
|
||||
sqlite_expected = importlib.util.find_spec("nanobot.session.location") is not None
|
||||
canonical = canonical_records(database) if sqlite_expected else None
|
||||
if before["canonical"] is not None:
|
||||
assert_canonical_preserved(before["canonical"], canonical)
|
||||
delivery = root / "account/.nanobot/delivery/outbox.sqlite3"
|
||||
if before.get("delivery") is not None:
|
||||
assert canonical_records(delivery, ("deliveries",)) == before["delivery"]
|
||||
if canonical is not None:
|
||||
# Display transcripts are not canonical agent context. Check the actual
|
||||
# imported message bodies too when the baseline predates SQLite.
|
||||
assert not any(row[0] == "websocket:display-only" for row in canonical["messages"])
|
||||
for session_key in ("websocket:legacy-acceptance", "websocket:canonical-only"):
|
||||
messages = [json.loads(row[2]) for row in canonical["messages"] if row[0] == session_key]
|
||||
assert [(message["role"], message["content"]) for message in messages] == [
|
||||
("user", "配置和聊天不能丢失")]
|
||||
asyncio.run(chat(root, before["chat_id"]))
|
||||
continued = history(root, key)
|
||||
canonical = canonical_records(database) if sqlite_expected else None
|
||||
assert len(continued["events"]) > len(before["history"]["events"])
|
||||
gateway(root, "stop")
|
||||
if _dock_supported(root):
|
||||
_wait_dock(_dock_socket(root), present=False)
|
||||
gateway(root, "--background")
|
||||
ready(root, expected)
|
||||
if _dock_supported(root):
|
||||
_wait_dock(_dock_socket(root), present=True)
|
||||
assert history(root, key) == continued
|
||||
assert_history_preserved(before["legacy"], history(root, "websocket:legacy-acceptance"))
|
||||
assert_history_preserved(before["display_only"], history(root, "websocket:display-only"))
|
||||
assert canonical_context(root) == before["canonical_only"]
|
||||
if sqlite_expected:
|
||||
assert canonical_records(database) == canonical
|
||||
if before.get("delivery") is not None:
|
||||
assert canonical_records(delivery, ("deliveries",)) == before["delivery"]
|
||||
assert {name: digest(Path(name)) for name in before["files"]} == before["files"]
|
||||
return sqlite_expected
|
||||
|
||||
|
||||
def run(args) -> dict:
|
||||
from packaging.utils import parse_wheel_filename
|
||||
from packaging.version import Version
|
||||
|
||||
# The build environment supplies dependencies for metadata construction only.
|
||||
# All product imports and execution happen in the separately installed wheel.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from scripts.build_tui_wheels import wheel_files
|
||||
from scripts.verify_installed_release import _wait_for_closed_listeners, host_environment
|
||||
|
||||
target = args.wheel.resolve(strict=True)
|
||||
version = str(parse_wheel_filename(target.name)[1])
|
||||
tags = parse_wheel_filename(target.name)[3]
|
||||
if len(tags) != 1 or any(tag.platform == "any" for tag in tags):
|
||||
raise ValueError("Acceptance requires the final native wheel, not an intermediate universal wheel")
|
||||
files, _, _ = wheel_files(target, version, platform=next(iter(tags)).platform)
|
||||
if files["nanobot/_build_commit.txt"].decode().strip() != args.commit:
|
||||
raise ValueError("Target wheel does not contain the requested candidate commit")
|
||||
original_hash = digest(target)
|
||||
root = args.output.resolve()
|
||||
root.mkdir(mode=0o700) # Exclusive evidence root. Never use a user's installation.
|
||||
environment = root / "managed"
|
||||
python = environment / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
|
||||
base = Version(version).release
|
||||
baseline_version = ".".join(map(str, (*base[:-1], max(0, base[-1] - 1))))
|
||||
if Version(baseline_version) >= Version(version):
|
||||
raise ValueError("Select a baseline wheel for this candidate version")
|
||||
baseline_source = args.baseline_wheel.resolve(strict=True) if args.baseline_wheel else target
|
||||
if args.baseline_wheel:
|
||||
baseline_version = str(parse_wheel_filename(baseline_source.name)[1])
|
||||
if Version(baseline_version) >= Version(version):
|
||||
raise ValueError("Baseline must precede the target")
|
||||
results = []
|
||||
system = host_environment(dict(os.environ))
|
||||
system.update(HOME=str(root), USERPROFILE=str(root), APPDATA=str(root / "config"),
|
||||
LOCALAPPDATA=str(root / "data"), XDG_CONFIG_HOME=str(root / "config"),
|
||||
XDG_CACHE_HOME=str(root / "cache"), XDG_DATA_HOME=str(root / "data"),
|
||||
TMPDIR=str(root), TMP=str(root), TEMP=str(root),
|
||||
PIP_CONFIG_FILE=os.devnull, PIP_NO_INPUT="1", PIP_DISABLE_PIP_VERSION_CHECK="1", PYTHONUTF8="1",
|
||||
NANOBOT_TUI_NO_DOWNLOAD="1", NO_COLOR="1", PATH=os.defpath)
|
||||
if os.name == "nt":
|
||||
system["PATH"] = str(Path(system["SYSTEMROOT"]) / "System32")
|
||||
# Install once, without inherited user pip settings; every case resets only
|
||||
# nanobot in this private environment. Dependencies stay pinned by its snapshot.
|
||||
subprocess.run([sys.executable, "-I", "-m", "venv", str(environment)], check=True, env=system, timeout=90)
|
||||
subprocess.run([str(python), "-I", "-m", "pip", "install", "--only-binary=:all:", str(target)],
|
||||
check=True, env=system, timeout=600, stdout=subprocess.DEVNULL)
|
||||
write(environment / "nanobot-install.json", {"schema_version": 1, "owner": "nanobot-installer",
|
||||
"environment": str(environment), "extras": []})
|
||||
for scenario in args.scenario or SCENARIOS:
|
||||
case_root = root / scenario
|
||||
case_root.mkdir()
|
||||
account = case_root / "account"
|
||||
account.mkdir()
|
||||
env = dict(system, HOME=str(account), USERPROFILE=str(account), APPDATA=str(account / "config"),
|
||||
LOCALAPPDATA=str(account / "data"), XDG_CONFIG_HOME=str(account / "config"),
|
||||
XDG_CACHE_HOME=str(root / "cache"), XDG_DATA_HOME=str(account / "data"),
|
||||
TMPDIR=str(case_root), TMP=str(case_root), TEMP=str(case_root))
|
||||
selected = target
|
||||
feed = case_root / "feed.json"
|
||||
if scenario in {"upgrade-again", "import-failure", "restart-failure", "restore-interruption"}:
|
||||
intermediate = Version(version).base_version + ".dev0"
|
||||
if not Version(baseline_version) < Version(intermediate) < Version(version):
|
||||
raise ValueError("Consecutive updates require baseline < target.dev0 < target")
|
||||
# Faults and the instrumented intermediate get a distinct version:
|
||||
# never overwrite a previously observed version with healthy bytes.
|
||||
selected = fixture_wheel(target, case_root / "intermediate", intermediate,
|
||||
feed=feed if scenario == "upgrade-again" else None, scenario=scenario)
|
||||
write(feed, feed_records(selected, args.commit))
|
||||
earlier = baseline_version
|
||||
if scenario == "skipped-preview" and not args.baseline_wheel:
|
||||
earlier = Version(version).base_version + ".dev0"
|
||||
if Version(earlier) >= Version(version):
|
||||
raise ValueError("Skipped Preview requires a target newer than dev0")
|
||||
baseline = fixture_wheel(baseline_source, case_root / "baseline", earlier, feed=feed, scenario=scenario)
|
||||
case = {"scenario": scenario, "baseline_version": earlier, "dock": args.dock,
|
||||
"target_version": str(parse_wheel_filename(selected.name)[1]),
|
||||
"baseline_kind": "instrumented historical wheel" if args.baseline_wheel else "instrumented version fixture",
|
||||
"baseline_source_sha256": digest(baseline_source), "baseline_fixture_sha256": digest(baseline),
|
||||
"target_wheel": str(selected), "target_sha256": digest(selected), "commit": args.commit,
|
||||
"target_unmodified": selected == target}
|
||||
write(case_root / "case.json", case)
|
||||
subprocess.run([str(python), "-I", "-m", "pip", "install", "--no-deps", "--force-reinstall", str(baseline)],
|
||||
check=True, env=env, timeout=120, stdout=subprocess.DEVNULL)
|
||||
child = [str(python), "-I", str(Path(__file__).resolve())]
|
||||
with (case_root / "acceptance.log").open("w", encoding="utf-8") as log:
|
||||
def journey():
|
||||
subprocess.run([*child, "--phase", "prepare", "--output", str(case_root)],
|
||||
check=True, env=env, cwd=case_root, stdout=log, stderr=log, timeout=180)
|
||||
launch = read(case_root / "launch.json")
|
||||
subprocess.run(launch["command"], check=True, env=env, cwd=launch["directory"],
|
||||
stdout=log, stderr=log, timeout=420)
|
||||
subprocess.run([*child, "--phase", "verify", "--output", str(case_root)],
|
||||
check=True, env=env, cwd=case_root, stdout=log, stderr=log, timeout=180)
|
||||
return read(case_root / "result.json")
|
||||
|
||||
try:
|
||||
result = journey()
|
||||
if result["phase"] == "restored" or scenario == "upgrade-again":
|
||||
previous_job = read(case_root / "launch.json")["directory"]
|
||||
write(feed, feed_records(target, args.commit, generation=2))
|
||||
write(case_root / "case.json", {
|
||||
**case, "scenario": "upgrade", "baseline_version": result["running_version"],
|
||||
"baseline_kind": "previous journey's running installation",
|
||||
"baseline_source_sha256": (case["baseline_source_sha256"] if result["phase"] == "restored"
|
||||
else case["target_sha256"]),
|
||||
"baseline_fixture_sha256": (case["baseline_fixture_sha256"] if result["phase"] == "restored"
|
||||
else case["target_sha256"]),
|
||||
"target_version": version, "target_wheel": str(target),
|
||||
"target_sha256": original_hash, "target_unmodified": True,
|
||||
})
|
||||
result["subsequent_update"] = journey()
|
||||
assert read(case_root / "launch.json")["directory"] != previous_job
|
||||
assert result["subsequent_update"]["phase"] == "succeeded"
|
||||
write(case_root / "result.json", result)
|
||||
results.append(result)
|
||||
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
|
||||
log.flush()
|
||||
tail = (case_root / "acceptance.log").read_text(encoding="utf-8", errors="replace")[-8192:]
|
||||
config_file = account / ".nanobot/config.json"
|
||||
if config_file.exists():
|
||||
token = read(config_file)["channels"]["websocket"]["tokenIssueSecret"]
|
||||
tail = tail.replace(token, "[redacted]")
|
||||
print(tail, file=sys.stderr)
|
||||
raise
|
||||
finally:
|
||||
subprocess.run([str(python), "-I", "-m", "nanobot", "gateway", "stop", "--config",
|
||||
str(account / ".nanobot/config.json")], env=env, cwd=case_root,
|
||||
stdout=log, stderr=log, timeout=60, check=True)
|
||||
config_file = account / ".nanobot/config.json"
|
||||
if config_file.exists():
|
||||
config = read(config_file)
|
||||
_wait_for_closed_listeners((config["gateway"]["port"], config["channels"]["websocket"]["port"]))
|
||||
results[-1]["gateway_process_stopped"] = True
|
||||
dock_address = results[-1].get("dock_socket")
|
||||
if not dock_address:
|
||||
dock_address = results[-1].get("subsequent_update", {}).get("dock_socket")
|
||||
if dock_address:
|
||||
_wait_dock(Path(dock_address), present=False)
|
||||
results[-1]["dock_stopped"] = True
|
||||
print(f"PASS {scenario}: {results[-1]['phase']}", flush=True)
|
||||
assert digest(target) == original_hash
|
||||
return {"platform": platform.system(), "machine": platform.machine(), "python": platform.python_version(),
|
||||
"target_sha256": original_hash, "candidate_commit": args.commit, "version": version,
|
||||
"release_transport": "local fixture; no public-download proof", "interactive_ui_e2e": False,
|
||||
"release_approval": "private unsigned fixture; not signature acceptance",
|
||||
"scenarios": results}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--wheel", type=Path)
|
||||
parser.add_argument("--baseline-wheel", type=Path)
|
||||
parser.add_argument("--commit")
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
parser.add_argument("--scenario", action="append", choices=SCENARIOS)
|
||||
parser.add_argument("--dock", action="store_true", help="Verify native macOS background Dock lifecycle")
|
||||
parser.add_argument("--phase", choices=("prepare", "verify"), help=argparse.SUPPRESS)
|
||||
args = parser.parse_args()
|
||||
if not sys.flags.isolated:
|
||||
parser.error("Run with python -I")
|
||||
if args.dock and sys.platform != "darwin":
|
||||
parser.error("--dock requires a real macOS desktop session")
|
||||
if args.phase:
|
||||
if sys.prefix == sys.base_prefix:
|
||||
parser.error("Product phases must run in the disposable installation")
|
||||
if args.phase == "prepare":
|
||||
prepare(args.output)
|
||||
else:
|
||||
write(args.output / "result.json", verify(args.output))
|
||||
return
|
||||
if not args.wheel or not args.commit:
|
||||
parser.error("--wheel and --commit are required")
|
||||
result = run(args)
|
||||
write(args.output / "packaged-update-report.json", result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Check a maintainer's exact release approval before requesting a signature.
|
||||
|
||||
This script only reads data. It must run from the protected workflow checkout,
|
||||
never from a downloaded candidate, and must never import or execute that package.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.releases import ReleaseManifest
|
||||
|
||||
|
||||
def verify_manifest(path: Path, *, sha256: str, version: str,
|
||||
source_commit: str, candidate_commit: str) -> ReleaseManifest:
|
||||
if path.is_symlink() or not path.is_file() or path.stat().st_size > 64 * 1024:
|
||||
raise ValueError("Expected a bounded, regular release manifest")
|
||||
payload = path.read_bytes()
|
||||
if hashlib.sha256(payload).hexdigest() != sha256:
|
||||
raise ValueError("Manifest differs from the maintainer-approved digest")
|
||||
manifest = ReleaseManifest.model_validate_json(payload)
|
||||
if (manifest.version, manifest.source_commit, manifest.candidate_commit) != (version, source_commit, candidate_commit):
|
||||
raise ValueError("Manifest differs from the maintainer-approved release identity")
|
||||
return manifest
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--manifest", type=Path, required=True)
|
||||
for name in ("sha256", "version", "source-commit", "candidate-commit"):
|
||||
parser.add_argument("--" + name, required=True)
|
||||
args = parser.parse_args()
|
||||
manifest = verify_manifest(args.manifest, sha256=args.sha256, version=args.version,
|
||||
source_commit=args.source_commit, candidate_commit=args.candidate_commit)
|
||||
print(f"Verified exact approval for {manifest.version}; no candidate code was executed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user