From 55824dc7237fbdd1631ba87d5c598e0b3f1a8d22 Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:37:08 +0800 Subject: [PATCH 01/13] feat: add standalone runtimes with verified updates and optional OCR --- .github/workflows/release.yml | 16 +- .github/workflows/runtime.yml | 69 +++ THIRD_PARTY_NOTICES.md | 2 +- scripts/accept_runtime.py | 316 ++++++++++++ scripts/build_runtime.py | 262 ++++++++++ scripts/build_runtime_upgrade_fixture.py | 37 ++ scripts/frozen_entry.py | 6 + scripts/runtime-build-requirements.txt | 4 + scripts/runtime-inputs.json | 24 + scripts/runtime.ps1 | 35 ++ scripts/runtime.sh | 33 ++ skills/android-use/SKILL.md | 6 +- src/android_use/ocr.py | 13 + src/android_use/portable.py | 624 +++++++++++++++++++++++ src/android_use/screen.py | 5 +- tests/fixtures/runtime-sample.h264 | Bin 0 -> 864 bytes tests/test_portable.py | 356 +++++++++++++ 17 files changed, 1800 insertions(+), 8 deletions(-) create mode 100644 .github/workflows/runtime.yml create mode 100644 scripts/accept_runtime.py create mode 100644 scripts/build_runtime.py create mode 100644 scripts/build_runtime_upgrade_fixture.py create mode 100644 scripts/frozen_entry.py create mode 100644 scripts/runtime-build-requirements.txt create mode 100644 scripts/runtime-inputs.json create mode 100644 scripts/runtime.ps1 create mode 100644 scripts/runtime.sh create mode 100644 src/android_use/portable.py create mode 100644 tests/fixtures/runtime-sample.h264 create mode 100644 tests/test_portable.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5947d5c..5e6883e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,8 +16,11 @@ jobs: tests: uses: ./.github/workflows/test.yml + runtimes: + uses: ./.github/workflows/runtime.yml + release: - needs: tests + needs: [tests, runtimes] runs-on: ubuntu-latest permissions: contents: write @@ -32,15 +35,22 @@ jobs: run: | title=$(python3 scripts/release_check.py "$GITHUB_REF_NAME") echo "title=$title" >> "$GITHUB_OUTPUT" + - uses: actions/download-artifact@v4 + with: + pattern: runtime-* + path: dist/runtime + merge-multiple: true - name: Build plugin ZIP run: | python3 scripts/package.py - cd dist && sha256sum "android-use-${GITHUB_REF_NAME#v}-plugin.zip" > SHA256SUMS + cd dist + sha256sum "android-use-${GITHUB_REF_NAME#v}-plugin.zip" > SHA256SUMS + cat runtime/*SHA256SUMS >> SHA256SUMS - name: Publish release env: GH_TOKEN: ${{ github.token }} TITLE: ${{ steps.check.outputs.title }} run: | gh release create "$GITHUB_REF_NAME" \ - "dist/android-use-${GITHUB_REF_NAME#v}-plugin.zip" dist/SHA256SUMS \ + "dist/android-use-${GITHUB_REF_NAME#v}-plugin.zip" dist/runtime/*.zip dist/SHA256SUMS \ --verify-tag --title "$TITLE" --notes-file "docs/releases/$GITHUB_REF_NAME.md" diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml new file mode 100644 index 0000000..6739d98 --- /dev/null +++ b/.github/workflows/runtime.yml @@ -0,0 +1,69 @@ +name: Standalone runtimes + +on: + workflow_dispatch: + workflow_call: + push: + branches: [codex/standalone-runtime] + pull_request: + paths: + - 'src/android_use/portable.py' + - 'src/android_use/screen.py' + - 'src/android_use/ocr.py' + - 'scripts/*runtime*' + - 'scripts/frozen_entry.py' + - '.github/workflows/runtime.yml' + +permissions: + contents: read + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-22.04 + platform: linux-x86_64 + - os: macos-15 + platform: macos-arm64 + - os: macos-15-intel + platform: macos-x86_64 + - os: windows-2022 + platform: windows-x86_64 + runs-on: ${{ matrix.os }} + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v6 + with: + python-version: '3.13.7' + - name: Prepare Windows compiler + if: runner.os == 'Windows' + uses: msys2/setup-msys2@v2 + with: + msystem: MINGW64 + update: true + install: make mingw-w64-x86_64-gcc diffutils pkgconf + - name: Expose Windows compiler + if: runner.os == 'Windows' + shell: pwsh + run: | + 'C:\msys64\mingw64\bin' >> $env:GITHUB_PATH + 'C:\msys64\usr\bin' >> $env:GITHUB_PATH + - run: uv sync --frozen --python 3.13.7 + - run: uv pip install -r scripts/runtime-build-requirements.txt + - name: Build native runtime and Dim plugin + run: uv run --no-sync python scripts/build_runtime.py + - name: Build a distinct upgrade version in a disposable source tree + run: uv run --no-sync python scripts/build_runtime_upgrade_fixture.py + - name: Test install, upgrade, rollback and bundled tools + run: uv run --no-sync python scripts/accept_runtime.py --archive dist/runtime/android-use-runtime-${{ matrix.platform }}.zip --upgrade-archive dist/runtime-upgrade/android-use-runtime-${{ matrix.platform }}.zip + - uses: actions/upload-artifact@v4 + with: + name: runtime-${{ matrix.platform }} + path: | + dist/runtime/*.zip + dist/runtime/*SHA256SUMS + dist/runtime/acceptance.json + retention-days: 14 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index f04aeeb..930e47a 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -1,6 +1,6 @@ # Third-party notices -Android Use source code is licensed under MIT. The bundled browser SDK and its dependencies retain their own licenses, reproduced below. Python dependencies and ffmpeg are installed separately and retain their upstream licenses. +Android Use source code is licensed under MIT. The bundled browser SDK and its dependencies retain their own licenses, reproduced below. Source installations obtain Python dependencies and ffmpeg separately. Standalone runtime archives include CPython, Python dependencies, Android Platform Tools and a minimal FFmpeg build; they retain their upstream licenses. Each runtime carries CPython and Python-package notices under `licenses/`, Android Platform Tools notices under `tools/adb/`, and the corresponding FFmpeg source archive plus exact configure options under `licenses/`. Native runtime inputs and SHA256 values are pinned in `scripts/runtime-inputs.json`. The optional macOS OCR component uses the system Vision framework and is distributed separately. ## @modelcontextprotocol/ext-apps@1.7.5 diff --git a/scripts/accept_runtime.py b/scripts/accept_runtime.py new file mode 100644 index 0000000..70fda96 --- /dev/null +++ b/scripts/accept_runtime.py @@ -0,0 +1,316 @@ +"""Opt-in acceptance of built native artifacts; no phone or model calls. + +The test driver uses Python/MCP. Tested executables use only their bundled runtime, +with Python, uv, adb and ffmpeg removed from PATH. Download transport is stubbed only +for the packaged bootstrap, so no unpublished release or external device is needed. +""" + +import argparse +import asyncio +import hashlib +import json +import os +import shutil +import subprocess +import sys +import tempfile +from datetime import timedelta +from pathlib import Path +from zipfile import ZIP_DEFLATED, ZipFile + +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) +from android_use.portable import extract, target # noqa: E402 + + +def digest(path): + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def run(command, env): + result = subprocess.run( + [str(p) for p in command], env=env, capture_output=True, text=True, timeout=120 + ) + return result, json.loads(result.stdout) + + +async def connected(command, env): + params = StdioServerParameters(command=command[0], args=command[1:], env=env) + async with stdio_client(params) as (read, write): + async with ClientSession( + read, write, read_timeout_seconds=timedelta(seconds=30) + ) as session: + started = await session.initialize() + assert len((await session.list_tools()).tools) == 26 + resource = (await session.list_resources()).resources[0] + content = (await session.read_resource(resource.uri)).contents[0].text + assert "Android Use" in content and len(content) > 10000 + return started.serverInfo.version + + +async def exercise(archive, upgrade_archive): + passed = [] + with tempfile.TemporaryDirectory(prefix="android-use-native-acceptance-") as folder: + folder = Path(folder) + unpacked = folder / "download with spaces" + extract(archive, unpacked) + version = json.loads((unpacked / "runtime.json").read_text())["version"] + exe = ( + unpacked + / "app" + / ("android-use-runtime.exe" if os.name == "nt" else "android-use-runtime") + ) + root = folder / "stable runtime with spaces" + env = { + k: v + for k, v in os.environ.items() + if not k.startswith(("TYPESAFE_", "TEXT_MODEL_")) + and k + not in { + "PYTHONPATH", + "PYTHONHOME", + "ANDROID_USE_OCR", + "ANDROID_USE_FFMPEG", + "ANDROID_USE_ADB", + } + } + env.update( + PATH=str(folder / "empty-path"), + ANDROID_USE_STATE_DIR=str(folder / "private-state"), + ANDROID_USE_AUTO_UPDATE="0", + ) + result, health = run([exe, "health"], env) + assert result.returncode == 0 and health["ok"], health + assert {"adb", "ffmpeg"} <= health["dependencies"].keys() + passed.append("health_without_system_python_uv_adb_ffmpeg") + result, first = run( + [exe, "--root", root, "install", "--archive", archive, "--sha256", digest(archive)], env + ) + assert result.returncode == 0 and first["tool_count"] == 26, first + config = first["mcp_config"] + command = [config["command"], *config["args"]] + assert await connected(command, env) == version + passed.append("first_install_stable_stdio_and_embedded_ui_resource") + preference = folder / "private-state/jev.json" + preference.parent.mkdir(exist_ok=True) + preference.write_text('{"fixture":"private-configuration-preserved"}') + preference_before = preference.read_bytes() + pointer = (root / "current.path").read_bytes() + result, bad = run( + [exe, "--root", root, "install", "--archive", archive, "--sha256", "0" * 64], env + ) + assert result.returncode and bad["error"] == "runtime_checksum_mismatch" + assert (root / "current.path").read_bytes() == pointer + passed.append("corrupt_download_keeps_previous_runtime") + # Keep an initialized old MCP session alive during promotion and rollback. + params = StdioServerParameters(command=command[0], args=command[1:], env=env) + async with stdio_client(params) as (read, write): + async with ClientSession( + read, write, read_timeout_seconds=timedelta(seconds=30) + ) as active: + assert (await active.initialize()).serverInfo.version == version + result, upgraded = run( + [ + exe, + "--root", + root, + "install", + "--archive", + upgrade_archive, + "--sha256", + digest(upgrade_archive), + ], + env, + ) + assert result.returncode == 0 and upgraded["previous"] == first["release"], upgraded + assert upgraded["mcp_config"] == config + assert len((await active.list_tools()).tools) == 26 + assert await connected(command, env) == upgraded["version"] + passed.append("upgrade_switches_new_sessions_without_interrupting_old_session") + shutil.rmtree(unpacked) + assert await connected(command, env) == upgraded["version"] + passed.append("deleted_original_extraction_does_not_break_stable_entry") + # Fail actual native health verification by giving the archive a mismatched version. + broken = folder / "bad-upgrade.zip" + with ( + ZipFile(upgrade_archive) as source, + ZipFile(broken, "w", ZIP_DEFLATED) as output, + ): + for entry in source.infolist(): + data = source.read(entry) + if entry.filename == "runtime.json": + info = json.loads(data) + info["version"] = "999.0.0" + data = json.dumps(info).encode() + output.writestr(entry, data) + result, failed = run( + [*command[:-1], "install", "--archive", broken, "--sha256", digest(broken)], env + ) + assert result.returncode and failed["error"] == "runtime_health_failed", failed + assert await connected(command, env) == upgraded["version"] + passed.append("native_health_failure_preserves_active_version") + result, rolled = run([*command[:-1], "rollback"], env) + assert result.returncode == 0 and rolled["version"] == version, rolled + assert await connected(command, env) == version + assert len((await active.list_tools()).tools) == 26 + assert json.loads((root / "update-policy.json").read_text())["paused"] + passed.append("rollback_reprobes_previous_runtime_and_pauses_auto_update") + assert preference.read_bytes() == preference_before + passed.append("private_settings_preserved") + result, schemas = run([*command[:-1], "cli", "tools"], env) + assert result.returncode == 0 and "tap" in schemas + passed.append("bundled_cli_dispatch") + native = root / "releases" / first["release"] + daemon = subprocess.run( + [native / "app" / exe.name, "preview-daemon", "--help"], + env=env, + capture_output=True, + text=True, + timeout=15, + ) + assert daemon.returncode == 0 and "--serial" in daemon.stdout + passed.append("frozen_preview_daemon_dispatch") + ffmpeg = native / "tools" / ("ffmpeg.exe" if os.name == "nt" else "ffmpeg") + sample = ROOT / "tests/fixtures/runtime-sample.h264" + frame = subprocess.run( + [ + ffmpeg, + "-loglevel", + "error", + "-f", + "h264", + "-i", + "pipe:0", + "-vf", + "select=if(gte(time(0)-ld(0)\\,0.1)\\,st(0\\,time(0))*0+1\\,0),scale=out_range=full", + "-pix_fmt", + "yuvj420p", + "-frames:v", + "1", + "-f", + "image2pipe", + "-vcodec", + "mjpeg", + "pipe:1", + ], + env=env, + input=sample.read_bytes(), + capture_output=True, + timeout=15, + ) + assert frame.returncode == 0 and frame.stdout.startswith(b"\xff\xd8"), frame.stderr.decode( + errors="replace" + ) + passed.append("bundled_ffmpeg_h264_filter_scale_and_jpeg_decode") + if target().startswith("macos"): + assert not (native / "tools/ocr").exists(), "Default runtime must not include OCR" + addon = archive.parent / f"android-use-ocr-{target()}.zip" + result, installed_ocr = run( + [*command[:-1], "install-ocr", "--archive", addon, "--sha256", digest(addon)], env + ) + assert result.returncode == 0 and installed_ocr["ocr_installed"], installed_ocr + ocr_id = (root / "ocr.path").read_text().strip() + ocr_binary = root / "components" / ocr_id / "ocr" + before_ocr = (root / "ocr.path").read_bytes() + result, rejected = run( + [*command[:-1], "install-ocr", "--archive", addon, "--sha256", "0" * 64], env + ) + assert result.returncode and rejected["error"] == "runtime_checksum_mismatch" + assert (root / "ocr.path").read_bytes() == before_ocr + passed.append( + "ocr_omitted_by_default_optional_component_verified_and_bad_update_refused" + ) + from PIL import Image, ImageDraw + + image = Image.new("RGB", (800, 180), "white") + ImageDraw.Draw(image).text((20, 40), "TOTAL 22.90", fill="black", font_size=65) + path = folder / "ocr.png" + image.save(path) + result = subprocess.run( + [ocr_binary, path], env=env, capture_output=True, text=True, timeout=15 + ) + assert result.returncode == 0 and "22.90" in result.stdout, result.stderr + passed.append("precompiled_ocr_without_swift_compiler") + # The lightweight plugin's initial download uses a deterministic local transport. + plugin_zip = archive.parent / f"android-use-{version}-{target()}-dim-plugin.zip" + if plugin_zip.exists(): + plugin = folder / "plugin" + extract(plugin_zip, plugin) + bootstrap_env = { + **env, + "ANDROID_USE_RUNTIME_DIR": str(folder / "bootstrap-runtime"), + "PATH": os.environ.get("PATH", ""), + } + sums = folder / "SHA256SUMS" + sums.write_text(digest(archive) + " " + archive.name + "\n") + if os.name == "nt": + wrapper = folder / "bootstrap-test.ps1" + + def quote(value): + return str(value).replace("'", "''") + + wrapper.write_text(f"""function Invoke-WebRequest {{ +param([Parameter(Position=0)][string]$Uri,[switch]$UseBasicParsing,[int]$TimeoutSec,[string]$OutFile) +if ($Uri -eq 'https://github.com/arcships/android-use/releases/latest/download/SHA256SUMS') {{ Copy-Item -LiteralPath '{quote(sums)}' -Destination $OutFile }} +elseif ($Uri -eq 'https://github.com/arcships/android-use/releases/latest/download/{archive.name}') {{ Copy-Item -LiteralPath '{quote(archive)}' -Destination $OutFile }} +else {{ throw 'Unexpected download URL' }} +}} +& '{quote(plugin / "scripts/runtime.ps1")}' +""") + launch = [ + str( + Path(os.environ["SystemRoot"]) + / "System32/WindowsPowerShell/v1.0/powershell.exe" + ), + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-File", + str(wrapper), + ] + else: + fakebin = folder / "fakebin" + fakebin.mkdir() + curl = fakebin / "curl" + curl.write_text(f"""#!{Path(sys.executable).resolve()} +import sys,shutil +url=next(a for a in sys.argv if a.startswith('https://')) +assert url.startswith('https://github.com/arcships/android-use/releases/latest/download/') +source={str(sums)!r} if url.endswith('/SHA256SUMS') else {str(archive)!r} +shutil.copyfile(source,sys.argv[sys.argv.index('-o')+1]) +""") + curl.chmod(0o755) + bootstrap_env["PATH"] = str(fakebin) + ":/usr/bin:/bin" + launch = ["/bin/sh", str(plugin / "scripts/runtime.sh")] + assert await connected(launch, bootstrap_env) == version + passed.append( + "packaged_plugin_first_install_and_clean_stdio_with_stubbed_download_transport" + ) + return { + "platform": target(), + "version": version, + "upgraded_version": upgraded["version"], + "passed": passed, + "phone_actions": False, + "model_calls": False, + "runtime_system_tools_removed_from_PATH": True, + "bootstrap_download_transport": "local stub; production URLs checked", + "runtime_sha256": digest(archive), + } + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--archive", type=Path, required=True) + parser.add_argument("--upgrade-archive", type=Path) + args = parser.parse_args() + result = asyncio.run( + exercise(args.archive.resolve(), (args.upgrade_archive or args.archive).resolve()) + ) + output = args.archive.parent / "acceptance.json" + output.write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result, indent=2)) diff --git a/scripts/build_runtime.py b/scripts/build_runtime.py new file mode 100644 index 0000000..941978d --- /dev/null +++ b/scripts/build_runtime.py @@ -0,0 +1,262 @@ +"""Build a native standalone runtime and a dependency-free Dim bootstrap plugin. + +Run on each target OS/architecture, with locked Python deps and PyInstaller installed. +""" + +import argparse +import hashlib +import json +import os +import shutil +import subprocess +import sys +import tarfile +from pathlib import Path +from zipfile import ZIP_DEFLATED, ZipFile + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) +from android_use import __version__ # noqa: E402 +from android_use.portable import fetch, target # noqa: E402 + +CONFIGURE = [ + "--disable-autodetect", + "--disable-network", + "--disable-doc", + "--disable-debug", + "--disable-shared", + "--enable-static", + "--disable-x86asm", + "--disable-everything", + "--enable-ffmpeg", + "--enable-decoder=h264", + "--enable-parser=h264", + "--enable-demuxer=h264", + "--enable-encoder=mjpeg", + "--enable-muxer=image2pipe", + "--enable-protocol=pipe", + "--enable-filter=select,scale,format", +] +if os.name == "nt": + CONFIGURE.append("--extra-ldflags=-static") + + +def run(args, cwd=None): + subprocess.run([str(a) for a in args], cwd=cwd, check=True, stdout=sys.stderr) + + +def locked_input(cache, item): + path = cache / item["filename"] + if not path.exists(): + fetch(item["url"], path) + with path.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + if digest != item["sha256"]: + raise ValueError("Build input checksum mismatch: " + path.name) + return path + + +def archive_folder(folder, destination): + with ZipFile(destination, "w", ZIP_DEFLATED) as archive: + for path in sorted(folder.rglob("*")): + if path.is_file(): + archive.write(path, path.relative_to(folder)) + + +def build(output, cache, ffmpeg_binary=None): + from android_use.installation import probe + + output.mkdir(parents=True, exist_ok=True) + cache.mkdir(parents=True, exist_ok=True) + lock = json.loads((ROOT / "scripts/runtime-inputs.json").read_text()) + plat = target() + host = plat.split("-")[0] + adb_zip = locked_input(cache, lock["adb"][host]) + ffmpeg_source = locked_input(cache, lock["ffmpeg"]) + work = cache / ("build-" + plat) + work.mkdir(exist_ok=True) + suffix = ".exe" if os.name == "nt" else "" + if ffmpeg_binary is None: + source = work / "ffmpeg-8.0" + if not source.exists(): + with tarfile.open(ffmpeg_source) as archive: + archive.extractall(work, filter="data") + ffmpeg_binary = source / ("ffmpeg" + suffix) + if not ffmpeg_binary.exists(): + run(["bash", "./configure", *CONFIGURE], cwd=source) + run(["make", "-j4", "ffmpeg"], cwd=source) + config = subprocess.run( + [str(ffmpeg_binary), "-buildconf"], capture_output=True, text=True, check=True + ) + configuration = (config.stdout + config.stderr).replace("'", "").replace('"', "") + if not all(flag in configuration for flag in CONFIGURE) or any( + flag in configuration for flag in ["--enable-gpl", "--enable-nonfree"] + ): + raise ValueError("FFmpeg must be built with the locked minimal configuration") + run( + [ + sys.executable, + "-m", + "PyInstaller", + "--noconfirm", + "--clean", + "--onedir", + "--name", + "android-use-runtime", + "--distpath", + work / "dist", + "--workpath", + work / "pyinstaller", + "--specpath", + work, + "--paths", + ROOT / "src", + "--collect-all", + "android_use", + "--collect-data", + "mcp", + "--collect-submodules", + "mcp.server", + "--collect-all", + "uiautomator2", + "--copy-metadata", + "android-use", + ROOT / "scripts/frozen_entry.py", + ] + ) + bundle = work / "bundle" + if bundle.exists(): + shutil.rmtree(bundle) + shutil.copytree(work / "dist/android-use-runtime", bundle / "app", symlinks=False) + with ZipFile(adb_zip) as archive: + archive.extractall(work / "adb") + shutil.copytree(work / "adb/platform-tools", bundle / "tools/adb", dirs_exist_ok=True) + (bundle / "tools/adb" / ("adb" + suffix)).chmod(0o755) + shutil.copyfile(ffmpeg_binary, bundle / "tools" / ("ffmpeg" + suffix)) + (bundle / "tools" / ("ffmpeg" + suffix)).chmod(0o755) + ocr_archive = None + if host == "macos": + component = work / "ocr-component" + if component.exists(): + shutil.rmtree(component) + component.mkdir() + run(["/usr/bin/swiftc", ROOT / "src/android_use/assets/ocr.swift", "-o", component / "ocr"]) + (component / "ocr.json").write_text( + json.dumps({"schema": 1, "api": "vision-v1", "platform": plat, "version": __version__}) + ) + shutil.copyfile(ROOT / "LICENSE", component / "LICENSE") + ocr_archive = output / f"android-use-ocr-{plat}.zip" + archive_folder(component, ocr_archive) + licenses = bundle / "licenses" + licenses.mkdir() + for filename in ("LICENSE", "THIRD_PARTY_NOTICES.md"): + shutil.copyfile(ROOT / filename, licenses / filename) + # Carry corresponding FFmpeg source and exact configure options with the binary. + shutil.copyfile(ffmpeg_source, licenses / ffmpeg_source.name) + (licenses / "ffmpeg-build.json").write_text( + json.dumps({"source": lock["ffmpeg"], "configure": CONFIGURE}, indent=2) + ) + import sysconfig + + python_license = Path(sysconfig.get_path("stdlib")) / "LICENSE.txt" + if not python_license.is_file(): + python_license = Path(sys.base_prefix) / "LICENSE.txt" + if not python_license.is_file(): + raise ValueError("CPython license missing from build interpreter") + shutil.copyfile(python_license, licenses / "CPython-LICENSE.txt") + # Include license metadata for every installed Python distribution in the build env. + import importlib.metadata + + for distribution in importlib.metadata.distributions(): + for file in distribution.files or []: + if any( + part.lower() + in {"licenses", "license", "license.txt", "copying", "notice", "notice.txt"} + for part in file.parts + ): + path = Path(distribution.locate_file(file)) + if path.is_file(): + destination = licenses / "python" / str(file) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, destination) + info = { + "schema": 1, + "version": __version__, + "platform": plat, + "inputs": lock, + "python": sys.version.split()[0], + "pyinstaller": importlib.metadata.version("pyinstaller"), + } + (bundle / "runtime.json").write_text(json.dumps(info, indent=2)) + entry = bundle / "app" / ("android-use-runtime" + suffix) + run([entry, "health"]) + probe([str(entry), "serve"], os.environ.copy(), __version__) + runtime_zip = output / f"android-use-runtime-{plat}.zip" + archive_folder(bundle, runtime_zip) + plugin = work / "plugin" + if plugin.exists(): + shutil.rmtree(plugin) + (plugin / ".codex-plugin").mkdir(parents=True) + (plugin / "scripts").mkdir() + shutil.copytree(ROOT / "skills", plugin / "skills") + shutil.copyfile(ROOT / "LICENSE", plugin / "LICENSE") + (plugin / "README.md").write_text( + "# Android Use for Dim Agent\n\nThis lightweight plugin automatically installs a standalone runtime on first use.\nPython, ADB, ffmpeg and the screen UI are included in that runtime.\n\nDocumentation: https://github.com/arcships/android-use#quick-start\n" + ) + (plugin / "docs").mkdir() + for name in ( + "guide.md", + "guide.zh-CN.md", + "jev.md", + "jev.zh-CN.md", + "upgrading.md", + "standalone.md", + ): + if (ROOT / "docs" / name).exists(): + shutil.copyfile(ROOT / "docs" / name, plugin / "docs" / name) + for name in ("runtime.sh", "runtime.ps1"): + shutil.copyfile(ROOT / "scripts" / name, plugin / "scripts" / name) + manifest = { + "name": "android-use", + "version": __version__, + "description": "Android control with an automatically provisioned standalone runtime", + "skills": "./skills/", + "mcpServers": "./.mcp.json", + "interface": {"displayName": "Android Use"}, + } + (plugin / ".codex-plugin/plugin.json").write_text(json.dumps(manifest, indent=2)) + if host == "windows": + command, args = ( + "powershell.exe", + [ + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-File", + "${CLAUDE_PLUGIN_ROOT}/scripts/runtime.ps1", + ], + ) + else: + command, args = "/bin/sh", ["${CLAUDE_PLUGIN_ROOT}/scripts/runtime.sh"] + (plugin / ".mcp.json").write_text( + json.dumps( + {"mcpServers": {"android_use": {"type": "stdio", "command": command, "args": args}}}, + indent=2, + ) + ) + plugin_zip = output / f"android-use-{__version__}-{plat}-dim-plugin.zip" + archive_folder(plugin, plugin_zip) + checksums = [] + for archive in [runtime_zip, plugin_zip, *([ocr_archive] if ocr_archive else [])]: + checksums.append(hashlib.sha256(archive.read_bytes()).hexdigest() + " " + archive.name) + (output / (plat + "-SHA256SUMS")).write_text("\n".join(checksums) + "\n") + print(runtime_zip) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, default=ROOT / "dist/runtime") + parser.add_argument("--cache", type=Path, default=ROOT / "dist/runtime-build") + parser.add_argument("--ffmpeg-binary", type=Path) + args = parser.parse_args() + build(args.output.resolve(), args.cache.resolve(), args.ffmpeg_binary) diff --git a/scripts/build_runtime_upgrade_fixture.py b/scripts/build_runtime_upgrade_fixture.py new file mode 100644 index 0000000..b11a4d2 --- /dev/null +++ b/scripts/build_runtime_upgrade_fixture.py @@ -0,0 +1,37 @@ +"""Build a second version in a disposable source tree for native lifecycle acceptance.""" + +import os +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "src")) +from android_use import __version__ # noqa: E402 +from android_use.installation import source_files # noqa: E402 + +if __name__ == "__main__": + with tempfile.TemporaryDirectory(prefix="android-use-upgrade-source-") as folder: + checkout = Path(folder) + for source, relative in source_files(ROOT): + destination = checkout / relative + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + init = checkout / "src/android_use/__init__.py" + init.write_text( + init.read_text().replace(__version__, __version__.split("+")[0] + "+upgrade-test") + ) + subprocess.run( + [ + sys.executable, + str(checkout / "scripts/build_runtime.py"), + "--cache", + str(ROOT / "dist/runtime-build"), + "--output", + str(ROOT / "dist/runtime-upgrade"), + ], + env={**os.environ, "PYTHONPATH": str(checkout / "src")}, + check=True, + ) diff --git a/scripts/frozen_entry.py b/scripts/frozen_entry.py new file mode 100644 index 0000000..019fcd9 --- /dev/null +++ b/scripts/frozen_entry.py @@ -0,0 +1,6 @@ +"""PyInstaller entry; all runtime commands stay in the normal Python package.""" + +from android_use.portable import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/runtime-build-requirements.txt b/scripts/runtime-build-requirements.txt new file mode 100644 index 0000000..820963c --- /dev/null +++ b/scripts/runtime-build-requirements.txt @@ -0,0 +1,4 @@ +pyinstaller==6.16.0 +pyinstaller-hooks-contrib==2026.9 +altgraph==0.17.5 +macholib==1.16.4 ; sys_platform == 'darwin' diff --git a/scripts/runtime-inputs.json b/scripts/runtime-inputs.json new file mode 100644 index 0000000..5bd1bbe --- /dev/null +++ b/scripts/runtime-inputs.json @@ -0,0 +1,24 @@ +{ + "ffmpeg": { + "filename": "ffmpeg-8.0.tar.xz", + "url": "https://ffmpeg.org/releases/ffmpeg-8.0.tar.xz", + "sha256": "b2751fccb6cc4c77708113cd78b561059b6fa904b24162fa0be2d60273d27b8e" + }, + "adb": { + "macos": { + "filename": "platform-tools_r36.0.2-darwin.zip", + "url": "https://dl.google.com/android/repository/platform-tools_r36.0.2-darwin.zip", + "sha256": "106a5d31fad8c1c0c5a180d06f5779767d129d7d5edbe629005c11a85eec5b4b" + }, + "linux": { + "filename": "platform-tools_r36.0.2-linux.zip", + "url": "https://dl.google.com/android/repository/platform-tools_r36.0.2-linux.zip", + "sha256": "3afdea91441815ab41254193df0343d92c1b1c0d0237165c3a345c8af8891c31" + }, + "windows": { + "filename": "platform-tools_r36.0.2-windows.zip", + "url": "https://dl.google.com/android/repository/platform-tools_r36.0.2-win.zip", + "sha256": "b024d4f319d6ad3004de1ba7b96a5c7c5f3512e8b14126308d598b4ab93dcead" + } + } +} diff --git a/scripts/runtime.ps1 b/scripts/runtime.ps1 new file mode 100644 index 0000000..0d6206b --- /dev/null +++ b/scripts/runtime.ps1 @@ -0,0 +1,35 @@ +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' +$root = if ($env:ANDROID_USE_RUNTIME_DIR) { $env:ANDROID_USE_RUNTIME_DIR } else { Join-Path $HOME '.local/share/android-use/runtime' } +function Start-AndroidUse { + $start = New-Object System.Diagnostics.ProcessStartInfo + $start.FileName = Join-Path $root 'launcher-runtime/android-use-runtime.exe' + $start.Arguments = '--root "' + (Join-Path $root '.') + '" auto-serve' + $start.UseShellExecute = $false + $process = [System.Diagnostics.Process]::Start($start) + $process.WaitForExit() + exit $process.ExitCode +} +if ((Test-Path (Join-Path $root 'launcher-runtime/android-use-runtime.exe')) -and (Test-Path (Join-Path $root 'current.path'))) { + Start-AndroidUse +} +if ([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture -ne 'X64') { throw 'Unsupported runtime architecture' } +$base = 'https://github.com/arcships/android-use/releases/latest/download' +$name = 'android-use-runtime-windows-x86_64.zip' +$work = Join-Path ([System.IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $work | Out-Null +try { + Invoke-WebRequest -UseBasicParsing -TimeoutSec 180 "$base/SHA256SUMS" -OutFile (Join-Path $work 'SHA256SUMS') + Invoke-WebRequest -UseBasicParsing -TimeoutSec 180 "$base/$name" -OutFile (Join-Path $work $name) + $lines = @(Get-Content (Join-Path $work 'SHA256SUMS') | Where-Object { $_ -match "^[a-fA-F0-9]{64}\s+\*?$([regex]::Escape($name))$" }) + if ($lines.Count -ne 1) { throw 'Missing runtime checksum' } + $expected = ($lines[0] -split '\s+')[0].ToLowerInvariant() + if ((Get-FileHash (Join-Path $work $name) -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expected) { throw 'Runtime checksum mismatch' } + Expand-Archive -LiteralPath (Join-Path $work $name) -DestinationPath (Join-Path $work 'bundle') + $result = & (Join-Path $work 'bundle/app/android-use-runtime.exe') --root $root install --archive (Join-Path $work $name) --sha256 $expected + [Console]::Error.WriteLine(($result -join [Environment]::NewLine)) + if ($LASTEXITCODE -ne 0) { throw 'Runtime installation failed' } +} finally { + Remove-Item -LiteralPath $work -Recurse -Force +} +Start-AndroidUse diff --git a/scripts/runtime.sh b/scripts/runtime.sh new file mode 100644 index 0000000..59d8566 --- /dev/null +++ b/scripts/runtime.sh @@ -0,0 +1,33 @@ +#!/bin/sh +# First install uses OS tools only. Later starts use the managed stable launcher. +set -eu +root=${ANDROID_USE_RUNTIME_DIR:-"$HOME/.local/share/android-use/runtime"} +if [ -f "$root/launcher.sh" ] && [ -f "$root/current.path" ]; then + exec /bin/sh "$root/launcher.sh" auto-serve +fi +case "$(uname -s):$(uname -m)" in + Darwin:arm64) target=macos-arm64;; + Darwin:x86_64) target=macos-x86_64;; + Linux:x86_64) target=linux-x86_64;; + *) echo 'Unsupported Android Use runtime platform' >&2; exit 1;; +esac +base=https://github.com/arcships/android-use/releases/latest/download +name=android-use-runtime-$target.zip +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT HUP INT TERM +curl -fL --retry 2 --connect-timeout 15 --max-time 180 "$base/SHA256SUMS" -o "$work/SHA256SUMS" >&2 +curl -fL --retry 2 --connect-timeout 15 --max-time 180 "$base/$name" -o "$work/$name" >&2 +expected=$(awk -v file="$name" '$2==file {print $1}' "$work/SHA256SUMS") +case "$expected" in ''|*[!a-fA-F0-9]*) echo 'Invalid runtime checksum' >&2; exit 1;; esac +[ "${#expected}" -eq 64 ] || exit 1 +if command -v sha256sum >/dev/null 2>&1; then + actual=$(sha256sum "$work/$name" | awk '{print $1}') +else + actual=$(shasum -a 256 "$work/$name" | awk '{print $1}') +fi +[ "$actual" = "$expected" ] || { echo 'Runtime checksum mismatch' >&2; exit 1; } +unzip -q "$work/$name" -d "$work/bundle" +"$work/bundle/app/android-use-runtime" --root "$root" install --archive "$work/$name" --sha256 "$expected" >&2 +rm -rf "$work" +trap - EXIT HUP INT TERM +exec /bin/sh "$root/launcher.sh" auto-serve diff --git a/skills/android-use/SKILL.md b/skills/android-use/SKILL.md index 48447e0..3f48da5 100644 --- a/skills/android-use/SKILL.md +++ b/skills/android-use/SKILL.md @@ -15,7 +15,7 @@ Agent 负责理解任务、规划、编写文本和验收;Jev 是决策模型 首次使用执行 `aua_setup(action="status")`。服务缺失时调用一次 `aua_setup(action="start")`,再调用 `aua_ready(screenshot=false)`。多台设备先 discover,按用户目标 configure(serial=...),不随意选第一台。USB 未授权或锁屏让用户在手机上完成信任/解锁,再 READY。服务不会自动重启;启动失败按返回原因诊断,不循环 start。 -READY 自动关联本聊天的实时手机屏幕侧边栏;同一聊天复用同一个面板,不反复打开新面板。用户单独要求看屏幕时调用一次 `aua_screen()`,无需为打开预览重复 READY。视频由独立的 ADB screenrecord H.264 通道提供;需要宿主安装 ffmpeg,缺失时按工具返回处理。预览没有可见 viewer 5 秒后停止手机端采集;前端读取的是内存中缓存的视频帧,不轮询手机截图或 XML。侧边栏失败不自动判定控制通道失效。 +READY 自动关联本聊天的实时手机屏幕侧边栏;同一聊天复用同一个面板,不反复打开新面板。用户单独要求看屏幕时调用一次 `aua_screen()`,无需为打开预览重复 READY。视频由独立的 ADB screenrecord H.264 通道提供;独立运行包已内置 ffmpeg;源码安装需要宿主提供,缺失时按工具返回处理。预览没有可见 viewer 5 秒后停止手机端采集;前端读取的是内存中缓存的视频帧,不轮询手机截图或 XML。侧边栏失败不自动判定控制通道失效。 `aua_screen_frame`、`aua_screen_action` 仅供预览 App 自己使用,模型不要调用它们刷新画面或模拟用户点击。模型需要看图片仍用 aua_observe,侧边栏 Live 不替代模型观察。用户可以在预览中点击、滑动、返回、Home 或将当前视频画面复制为剪贴板 PNG 图片;这些动作会改变真实页面,下一次模型观察按实际状态继续。CLI 的 `screen` 返回本机预览 URL,可作为 Codex 的右侧浏览器面板打开。 @@ -39,4 +39,6 @@ batch 中动作等待超时停止为 postcondition_timeout,scroll_until 未找 aua_apps 查询已安装的第三方 **包名**,不支持按 App 显示名查找。不要连续猜包名。aua_launch_app 使用已核实的 package,不强停或清除 App 数据。发送、下单等外部变更需用户授权,并核对目标与内容,执行一次后验收结果。 -MCP 不可用时使用同一仓库 CLI:`uv run --frozen --directory <仓库路径> android-use <操作> ''`。CLI 截图保存到 image_paths 中的本机绝对路径,使用图片查看工具实际查看。MCP 图片必须转发 image 块,不输出 base64。CLI 的每次运行是新 Runtime,不能跨进程传 observation_id。 +独立运行包的固定入口也支持 `cli <操作> ''`,使用安装返回的启动命令,将最后的 `auto-serve` 改为 `cli` 并追加操作及参数,无需 uv。回滚使用固定入口的 `rollback`;后台更新只影响后续 MCP 会话,不重启当前任务。 + +MCP 不可用且使用源码安装时,使用同一仓库 CLI:`uv run --frozen --directory <仓库路径> android-use <操作> ''`。CLI 截图保存到 image_paths 中的本机绝对路径,使用图片查看工具实际查看。MCP 图片必须转发 image 块,不输出 base64。CLI 的每次运行是新 Runtime,不能跨进程传 observation_id。 diff --git a/src/android_use/ocr.py b/src/android_use/ocr.py index 9a1bb12..8a668a8 100644 --- a/src/android_use/ocr.py +++ b/src/android_use/ocr.py @@ -55,6 +55,14 @@ class VisionOCR: name = "macos_vision" def recognize(self, image, deadline): + bundled = os.environ.get("ANDROID_USE_OCR") + if bundled: + if not Path(bundled).is_file(): + raise UseError( + "ocr_unavailable", + "Optional local OCR is not installed; use the stable launcher's install-ocr command, or let the Agent inspect the screenshot", + ) + return self._recognize_binary(image, deadline, Path(bundled)) if platform.system() != "Darwin": raise UseError("ocr_unavailable", "Built-in OCR currently requires macOS Vision") source = files("android_use").joinpath("assets/ocr.swift").read_bytes() @@ -75,6 +83,11 @@ def recognize(self, image, deadline): ) output.chmod(0o700) os.replace(output, binary) + return self._recognize_binary(image, deadline, binary, version, start) + + def _recognize_binary(self, image, deadline, binary, version=None, start=None): + version = version or "vision-v1-" + platform.mac_ver()[0] + start = time.monotonic() if start is None else start with tempfile.TemporaryDirectory(prefix="android-use-ocr-") as folder: path = Path(folder) / "region.png" image.save(path, format="PNG") diff --git a/src/android_use/portable.py b/src/android_use/portable.py new file mode 100644 index 0000000..968a833 --- /dev/null +++ b/src/android_use/portable.py @@ -0,0 +1,624 @@ +"""Self-contained runtime installation. No uv, Python install, phone or model required.""" + +import argparse +import hashlib +import json +import os +import platform +import re +import shutil +import stat +import subprocess +import sys +import tempfile +import time +import urllib.request +import uuid +from pathlib import Path +from zipfile import ZipFile + +from . import __version__ +from .installation import InstallError, atomic_write, probe, read_json, write_json + +REPOSITORY = "arcships/android-use" +MAX_DOWNLOAD = 512 * 1024 * 1024 +MAX_EXPANDED = 2 * 1024 * 1024 * 1024 +VERSION = r"\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?" +_UNSET = object() +IDENTIFIER = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,100}") + + +def target(): + system = {"Darwin": "macos", "Linux": "linux", "Windows": "windows"}.get(platform.system()) + machine = {"arm64": "arm64", "aarch64": "arm64", "AMD64": "x86_64", "x86_64": "x86_64"}.get( + platform.machine() + ) + value = f"{system}-{machine}" + if value not in {"macos-arm64", "macos-x86_64", "linux-x86_64", "windows-x86_64"}: + raise InstallError("unsupported_runtime_platform") + return value + + +def root_path(): + return ( + Path(os.environ.get("ANDROID_USE_RUNTIME_DIR", "~/.local/share/android-use/runtime")) + .expanduser() + .resolve() + ) + + +def bundle_path(): + return Path(sys.executable).resolve().parent.parent if getattr(sys, "frozen", False) else None + + +def configure_bundle(): + bundle = bundle_path() + if bundle: + suffix = ".exe" if os.name == "nt" else "" + os.environ["ANDROID_USE_ADB"] = str(bundle / "tools/adb" / ("adb" + suffix)) + os.environ["ADBUTILS_ADB_PATH"] = os.environ["ANDROID_USE_ADB"] + os.environ["ANDROID_USE_FFMPEG"] = str(bundle / "tools" / ("ffmpeg" + suffix)) + if platform.system() == "Darwin": + root = Path( + os.environ.get( + "ANDROID_USE_RUNTIME_DIR", + bundle.parent.parent if bundle.parent.name == "releases" else root_path(), + ) + ) + os.environ["ANDROID_USE_OCR"] = str(ocr_binary(root) or bundle / "tools/ocr") + + +def release_id(value): + if not isinstance(value, str) or not IDENTIFIER.fullmatch(value): + raise InstallError("invalid_runtime_pointer") + return value + + +def current_id(root): + path = root / "current.path" + return release_id(path.read_text().strip()) if path.exists() else None + + +def executable(folder): + path = ( + folder / "app" / ("android-use-runtime.exe" if os.name == "nt" else "android-use-runtime") + ) + if not path.is_file() or not path.resolve().is_relative_to(folder.resolve()): + raise InstallError("runtime_executable_missing") + return path + + +def metadata(folder): + value = read_json(folder / "runtime.json", {}) + if value.get("schema") != 1 or value.get("platform") != target(): + raise InstallError("runtime_platform_mismatch") + if not isinstance(value.get("version"), str) or not re.fullmatch(VERSION, value["version"]): + raise InstallError("invalid_runtime_version") + executable(folder) + return value + + +def status(root): + active = current_id(root) + if not active: + return {"ok": True, "installed": False, "platform": target()} + folder = root / "releases" / active + info = metadata(folder) + return { + "ok": True, + "installed": True, + "version": info["version"], + "platform": info["platform"], + "release": active, + "previous": read_json(folder / "activation.json", {}).get("previous"), + "mcp_config": mcp_config(root), + } + + +def mcp_config(root): + if os.name == "nt": + return { + "command": str(root / "launcher-runtime/android-use-runtime.exe"), + "args": ["--root", str(root), "auto-serve"], + } + return {"command": "/bin/sh", "args": [str(root / "launcher.sh"), "auto-serve"]} + + +def launchers(root, folder): + # Written once. The only commit point is current.path; release history is immutable. + if os.name == "nt": + bridge = root / "launcher-runtime" + if not bridge.exists(): + temporary = root / (".launcher-" + uuid.uuid4().hex) + + def link_or_copy(source, destination): + try: + os.link(source, destination) + except OSError: + shutil.copy2(source, destination) + + try: + shutil.copytree(folder / "app", temporary, copy_function=link_or_copy) + os.replace(temporary, bridge) + finally: + shutil.rmtree(temporary, ignore_errors=True) + return + + posix = """#!/bin/sh +set -eu +case "$0" in */*) base=${0%/*};; *) base=.;; esac +base=$(CDPATH= cd -- "$base" && pwd) +IFS= read -r release < "$base/current.path" +case "$release" in ''|*[!a-zA-Z0-9._-]*) echo 'Invalid runtime pointer' >&2; exit 1;; esac +exec "$base/releases/$release/app/android-use-runtime" --root "$base" "$@" +""" + windows = """$ErrorActionPreference = 'Stop' +$release = (Get-Content -LiteralPath (Join-Path $PSScriptRoot 'current.path') -Raw).Trim() +if ($release -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,100}$') { throw 'Invalid runtime pointer' } +& (Join-Path $PSScriptRoot "releases/$release/app/android-use-runtime.exe") --root $PSScriptRoot @args +exit $LASTEXITCODE +""" + for name, text in [("launcher.sh", posix), ("launcher.ps1", windows)]: + path = root / name + if not path.exists(): + atomic_write(path, text.encode()) + + +def extract(archive, destination): + with ZipFile(archive) as source: + entries = source.infolist() + if len(entries) > 15000 or sum(e.file_size for e in entries) > MAX_EXPANDED: + raise InstallError("runtime_archive_too_large") + seen = set() + for item in entries: + parts = item.filename.rstrip("/").split("/") + key = item.filename.rstrip("/").casefold() + if ( + not parts + or any( + p in {"", ".", ".."} + or p.endswith((".", " ")) + or p.split(".")[0].upper() + in { + "CON", + "PRN", + "AUX", + "NUL", + *[f"COM{i}" for i in range(1, 10)], + *[f"LPT{i}" for i in range(1, 10)], + } + for p in parts + ) + or any(c in item.filename for c in ("\\", ":", "\x00")) + or key in seen + or stat.S_ISLNK(item.external_attr >> 16) + ): + raise InstallError("unsafe_runtime_archive") + seen.add(key) + for item in entries: + path = destination.joinpath(*item.filename.rstrip("/").split("/")) + if item.is_dir(): + path.mkdir(parents=True, exist_ok=True) + else: + path.parent.mkdir(parents=True, exist_ok=True) + with source.open(item) as src, path.open("wb") as dst: + shutil.copyfileobj(src, dst) + path.chmod(0o755 if (item.external_attr >> 16) & 0o111 else 0o644) + + +def verify(folder): + info = metadata(folder) + entry = executable(folder) + env = { + k: v + for k, v in os.environ.items() + if k + not in { + "ANDROID_USE_ADB", + "ANDROID_USE_FFMPEG", + "ANDROID_USE_OCR", + "PYTHONPATH", + "PYTHONHOME", + } + } + result = subprocess.run( + [str(entry), "health"], env=env, capture_output=True, text=True, timeout=30, check=True + ) + health = json.loads(result.stdout) + if not health.get("ok") or health.get("version") != info["version"]: + raise InstallError("runtime_health_failed") + return probe([str(entry), "serve"], env, info["version"]) + + +def verify_archive(archive, digest): + if not re.fullmatch(r"[a-fA-F0-9]{64}", digest): + raise InstallError("invalid_runtime_checksum") + if archive.stat().st_size > MAX_DOWNLOAD: + raise InstallError("runtime_archive_too_large") + with archive.open("rb") as stream: + actual = hashlib.file_digest(stream, "sha256").hexdigest() + if actual != digest.lower(): + raise InstallError("runtime_checksum_mismatch") + + +def activate(root, archive, digest, expected_version=None, expected_current=_UNSET): + verify_archive(archive, digest) + root.mkdir(parents=True, exist_ok=True) + lock = root / "runtime.lock" + try: + lock.mkdir() + except FileExistsError: + raise InstallError("runtime_upgrade_in_progress") from None + folder = None + promoted = False + try: + previous = current_id(root) + if expected_current is not _UNSET and previous != expected_current: + raise InstallError("runtime_changed_during_download") + folder = root / "releases" / ("candidate-" + uuid.uuid4().hex) + folder.mkdir(parents=True) + extract(archive, folder) + info = metadata(folder) + if expected_version and info["version"] != expected_version: + raise InstallError("runtime_release_version_mismatch") + checked = verify(folder) + write_json(folder / "activation.json", {"previous": previous, "sha256": digest.lower()}) + launchers(root, folder) + atomic_write(root / "current.path", (folder.name + "\n").encode()) + promoted = True + # A failed timestamp write must not undo a committed, verified installation. + try: + write_json(root / "last-check.json", {"time": time.time()}) + except OSError: + pass + return {**status(root), **checked, "phone_actions": False, "host_reload_required": True} + finally: + if folder is not None and not promoted: + shutil.rmtree(folder, ignore_errors=True) + lock.rmdir() + + +def rollback(root): + lock = root / "runtime.lock" + try: + lock.mkdir() + except FileExistsError: + raise InstallError("runtime_upgrade_in_progress") from None + try: + active = current_id(root) + previous = read_json(root / "releases" / release_id(active) / "activation.json", {}).get( + "previous" + ) + if not previous: + raise InstallError("no_previous_runtime") + folder = root / "releases" / release_id(previous) + verify(folder) + write_json(root / "update-policy.json", {"paused": True}) + atomic_write(root / "current.path", (previous + "\n").encode()) + return status(root) + finally: + lock.rmdir() + + +def fetch(url, destination, limit=MAX_DOWNLOAD): + if not url.startswith("https://"): + raise InstallError("runtime_download_requires_https") + request = urllib.request.Request( + url, headers={"User-Agent": "android-use-runtime", "Accept": "application/octet-stream"} + ) + with urllib.request.urlopen(request, timeout=15) as response, destination.open("wb") as stream: + total = 0 + while block := response.read(1024 * 1024): + total += len(block) + if total > limit: + raise InstallError("runtime_download_too_large") + stream.write(block) + + +def update(root, version=None): + with tempfile.TemporaryDirectory(prefix="android-use-update-") as temporary: + temporary = Path(temporary) + release = temporary / "release.json" + if version is not None and not re.fullmatch(VERSION, version): + raise InstallError("invalid_runtime_version") + endpoint = "latest" if version is None else "tags/v" + version + fetch(f"https://api.github.com/repos/{REPOSITORY}/releases/{endpoint}", release, 2_000_000) + info = json.loads(release.read_text()) + tag = info.get("tag_name", "") + if info.get("draft") or info.get("prerelease") or not re.fullmatch("v" + VERSION, tag): + raise InstallError("invalid_runtime_release") + if version and tag != "v" + version: + raise InstallError("runtime_release_version_mismatch") + installed = status(root) + installed_version = installed.get("version") + if installed_version == tag[1:]: + return installed + if installed_version and version is None: + + def numbers(text): + return tuple(int(part) for part in re.split(r"[-+]", text)[0].split(".")) + + if numbers(installed_version) >= numbers(tag[1:]): + return installed + name = f"android-use-runtime-{target()}.zip" + prefix = f"https://github.com/{REPOSITORY}/releases/download/{tag}/" + assets = {a["name"]: a.get("browser_download_url") for a in info.get("assets", [])} + if assets.get(name) != prefix + name or assets.get("SHA256SUMS") != prefix + "SHA256SUMS": + raise InstallError("runtime_release_assets_missing") + checksums = temporary / "SHA256SUMS" + fetch(prefix + "SHA256SUMS", checksums, 1_000_000) + matches = [ + line.split()[0] + for line in checksums.read_text().splitlines() + if len(line.split()) == 2 and line.split()[1].lstrip("*") == name + ] + if len(matches) != 1: + raise InstallError("runtime_checksum_missing") + archive = temporary / name + fetch(prefix + name, archive) + return activate( + root, + archive, + matches[0], + expected_version=tag[1:], + expected_current=installed.get("release"), + ) + + +def update_due(root): + try: + last = read_json(root / "last-check.json", {}).get("time", 0) + paused = read_json(root / "update-policy.json", {}).get("paused", False) + return ( + not paused + and type(last) in (int, float) + and time.time() - last >= 86400 + and not (root / "download.lock").exists() + ) + except (OSError, ValueError, TypeError, AttributeError): + return False # Auxiliary update state must never prevent serving a healthy runtime. + + +def auto_serve(root): + active = release_id(current_id(root)) + if os.environ.get("ANDROID_USE_AUTO_UPDATE", "1") != "0" and update_due(root): + # Never delay stdio initialize or replace the running process for an update. + try: + with (root / "update.log").open("ab") as log: + subprocess.Popen( + [sys.executable, "--root", str(root), "update", "--automatic"], + stdin=subprocess.DEVNULL, + stdout=log, + stderr=log, + start_new_session=True, + env={**os.environ, "PYINSTALLER_RESET_ENVIRONMENT": "1"}, + ) + except OSError: + print( + "Android Use: background update unavailable; keeping installed runtime.", + file=sys.stderr, + ) + entry = executable(root / "releases" / active) + if os.name == "nt": + return subprocess.call([str(entry), "serve"]) + os.execv(str(entry), [str(entry), "serve"]) + + +def checked_update(root, version=None, automatic=False): + root.mkdir(parents=True, exist_ok=True) + if automatic and not update_due(root): + return status(root) + lock = root / "download.lock" + try: + lock.mkdir() + except FileExistsError: + raise InstallError("runtime_download_in_progress") from None + try: + if automatic: + last = read_json(root / "last-check.json", {}).get("time", 0) + if ( + read_json(root / "update-policy.json", {}).get("paused") + or time.time() - last < 86400 + ): + return status(root) + write_json(root / "last-check.json", {"time": time.time()}) + result = update(root, version) + if not automatic: + write_json(root / "update-policy.json", {"paused": False}) + return result + finally: + lock.rmdir() + + +def ocr_binary(root): + try: + pointer = root / "ocr.path" + if not pointer.exists(): + return None + component = root / "components" / release_id(pointer.read_text().strip()) + info = read_json(component / "ocr.json", {}) + binary = component / "ocr" + if ( + info.get("schema") == 1 + and info.get("api") == "vision-v1" + and info.get("platform") == target() + and binary.is_file() + and binary.resolve().is_relative_to(component.resolve()) + ): + return binary + except (OSError, ValueError, TypeError, AttributeError, InstallError): + pass + return None + + +def install_ocr(root, archive, digest): + if not target().startswith("macos-"): + raise InstallError("optional_ocr_requires_macos") + verify_archive(archive, digest) + root.mkdir(parents=True, exist_ok=True) + lock = root / "runtime.lock" + try: + lock.mkdir() + except FileExistsError: + raise InstallError("runtime_upgrade_in_progress") from None + component = root / "components" / ("ocr-" + uuid.uuid4().hex) + promoted = False + try: + component.mkdir(parents=True) + extract(archive, component) + info = read_json(component / "ocr.json", {}) + binary = component / "ocr" + if ( + info.get("schema") != 1 + or info.get("api") != "vision-v1" + or info.get("platform") != target() + or not binary.is_file() + ): + raise InstallError("invalid_ocr_component") + from PIL import Image + + with tempfile.TemporaryDirectory() as folder: + image = Path(folder) / "test.png" + Image.new("RGB", (100, 100), "white").save(image) + result = subprocess.run( + [str(binary), str(image)], capture_output=True, text=True, timeout=15, check=True + ) + if not isinstance(json.loads(result.stdout), list): + raise InstallError("ocr_component_health_failed") + atomic_write(root / "ocr.path", (component.name + "\n").encode()) + promoted = True + return {"ok": True, "ocr_installed": True, "host_reload_required": True} + finally: + if not promoted: + shutil.rmtree(component, ignore_errors=True) + lock.rmdir() + + +def download_ocr(root): + version = metadata(root / "releases" / release_id(current_id(root)))["version"] + name = f"android-use-ocr-{target()}.zip" + prefix = f"https://github.com/{REPOSITORY}/releases/download/v{version}/" + with tempfile.TemporaryDirectory(prefix="android-use-ocr-download-") as folder: + folder = Path(folder) + sums = folder / "SHA256SUMS" + fetch(prefix + "SHA256SUMS", sums, 1_000_000) + matches = [ + line.split()[0] + for line in sums.read_text().splitlines() + if len(line.split()) == 2 and line.split()[1].lstrip("*") == name + ] + if len(matches) != 1: + raise InstallError("ocr_component_checksum_missing") + archive = folder / name + fetch(prefix + name, archive) + return install_ocr(root, archive, matches[0]) + + +def health(): + configure_bundle() + bundle = bundle_path() + if not bundle: + raise InstallError("health_requires_built_runtime") + results = {} + for name, variable, flag in [ + ("adb", "ANDROID_USE_ADB", "version"), + ("ffmpeg", "ANDROID_USE_FFMPEG", "-version"), + ]: + result = subprocess.run( + [os.environ[variable], flag], capture_output=True, text=True, timeout=10, check=True + ) + results[name] = result.stdout.splitlines()[0] + if platform.system() == "Darwin": + results["ocr"] = ( + "installed" + if Path(os.environ["ANDROID_USE_OCR"]).is_file() + else "optional_not_installed" + ) + return {"ok": True, "version": __version__, "platform": target(), "dependencies": results} + + +def main(): + if len(sys.argv) >= 3 and sys.argv[1] == "--root": + os.environ["ANDROID_USE_RUNTIME_DIR"] = str(Path(sys.argv[2]).expanduser().resolve()) + if os.name == "nt" and Path(sys.executable).parent.name == "launcher-runtime": + try: + root = root_path() + entry = executable(root / "releases" / release_id(current_id(root))) + return subprocess.call([str(entry), *sys.argv[1:]]) + except (OSError, ValueError, InstallError): + print("Android Use: invalid standalone runtime entry", file=sys.stderr) + return 1 + configure_bundle() + parser = argparse.ArgumentParser(description="Android Use standalone runtime") + parser.add_argument("--root", type=Path, default=root_path()) + commands = parser.add_subparsers(dest="command", required=True) + for name in ("serve", "auto-serve", "health", "status", "rollback"): + commands.add_parser(name) + install = commands.add_parser("install") + install.add_argument("--archive", type=Path, required=True) + install.add_argument("--sha256", required=True) + ocr = commands.add_parser("install-ocr") + ocr.add_argument("--archive", type=Path) + ocr.add_argument("--sha256") + upgrade = commands.add_parser("update") + upgrade.add_argument("--version") + upgrade.add_argument("--automatic", action="store_true", help=argparse.SUPPRESS) + commands.add_parser("cli").add_argument("arguments", nargs=argparse.REMAINDER) + commands.add_parser("preview-daemon").add_argument("arguments", nargs=argparse.REMAINDER) + # Preserve arbitrary daemon/CLI flags after these dispatch words. + argv = sys.argv[1:] + offset = 2 if argv[:1] == ["--root"] else 0 + if len(argv) > offset and argv[offset] in {"preview-daemon", "cli"}: + mode = argv[offset] + sys.argv = [sys.argv[0], *argv[offset + 1 :]] + if mode == "preview-daemon": + from .preview_daemon import main as dispatch + else: + from .cli import main as dispatch + return dispatch() + args = parser.parse_args(argv) + args.root = args.root.expanduser().resolve() + try: + if args.command == "serve": + from .server import main as serve + + return serve() + if args.command == "auto-serve": + return auto_serve(args.root) + if args.command == "health": + result = health() + elif args.command == "status": + result = status(args.root) + elif args.command == "install": + result = activate(args.root, args.archive, args.sha256) + elif args.command == "install-ocr": + if bool(args.archive) != bool(args.sha256): + raise InstallError("ocr_archive_requires_checksum") + result = ( + install_ocr(args.root, args.archive, args.sha256) + if args.archive + else download_ocr(args.root) + ) + elif args.command == "update": + result = checked_update(args.root, args.version, args.automatic) + else: + result = rollback(args.root) + print(json.dumps(result)) + return 0 + except Exception as exc: + # No exception details: transports and private paths may contain credentials. + output = sys.stderr if args.command in {"serve", "auto-serve"} else sys.stdout + print( + json.dumps( + { + "ok": False, + "error": str(exc) if isinstance(exc, InstallError) else type(exc).__name__, + } + ), + file=output, + ) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/android_use/screen.py b/src/android_use/screen.py index 13bc405..f77098d 100644 --- a/src/android_use/screen.py +++ b/src/android_use/screen.py @@ -612,8 +612,8 @@ def ensure(self): process = subprocess.Popen( [ sys.executable, - "-m", - "android_use.preview_daemon", + *(["preview-daemon"] if getattr(sys, "frozen", False) + else ["-m", "android_use.preview_daemon"]), "--serial", self.serial, "--key", @@ -628,6 +628,7 @@ def ensure(self): # same browser URL. The child consumes this private value once. env={ **{k: v for k, v in os.environ.items() if k != PREVIEW_BOOTSTRAP_ENV}, + **({"PYINSTALLER_RESET_ENVIRONMENT": "1"} if getattr(sys, "frozen", False) else {}), **( { PREVIEW_BOOTSTRAP_ENV: json.dumps( diff --git a/tests/fixtures/runtime-sample.h264 b/tests/fixtures/runtime-sample.h264 new file mode 100644 index 0000000000000000000000000000000000000000..7279b5676b791f8ac882cf4b5cb845bc71532c2c GIT binary patch literal 864 zcmX|9J%|%Q6yD=hRJ8D~A5?6-Bs;sgToN4Q{_q3^ZPad=ot@3@Wp`&XJ24w=EIhDK z;hF;#Vt0tx9~R=-30GL^ffgbNBB-S{7vChF&CK`S`@Z)#V_DWjE3gi}*j_lZxnNn7 z)*f@bJ-4)W!-81!{ma(LO#u7$4u{V_E`EFUb$e-JZR!KsKK0{g;nb?AgqTnqVSviT zb{)Bx<3`wkz)~3qmCIKaFO;fi_S!r!1I{2YFJwRAp+=5vyCuhVTyREO%Vwq0>-EYv zjRoWGVg;FPEQ2{mu(Qifzr6(foC#ePP~^lxi4biX zf#L1?Fv^pdK`*-w8)a%#gT*P;rjIz&TqP7p;P;cRqJ58vR8kE#gB58-;|x*&QBlJQ z6-{{#%kn+h2OI}b+xKWdrJ2I_{FvsZNUZp1t{#tDk@g`bB+tB-kPsa^B}m)654njm zZU2K_8fRdlobimat|nF6w5h0Bsp5GAa>cy=V^4;wcyju^`Qx*XPbc%|cLt?jBWo~MtPBslG*BN7=+UM9*M~dx2XDr@mBk}dXNP0P#9)2I{tHVBA7}so literal 0 HcmV?d00001 diff --git a/tests/test_portable.py b/tests/test_portable.py new file mode 100644 index 0000000..0984593 --- /dev/null +++ b/tests/test_portable.py @@ -0,0 +1,356 @@ +import hashlib +import json +import os +import stat +import sys +from pathlib import Path +from zipfile import ZipFile, ZipInfo + +import pytest + +from android_use import portable as runtime +from android_use.installation import InstallError, probe + + +@pytest.fixture +def bundle(tmp_path): + if os.name == "nt": + pytest.skip( + "Protocol fixture uses a POSIX executable; native Windows acceptance uses the built EXE" + ) + + def create(version="1.0.0", platform=None, bad_health=False, bad_protocol=False, extras=None): + archive = tmp_path / (version + "-" + str(len(list(tmp_path.glob("*.zip")))) + ".zip") + code = f"""#!{Path(sys.executable).resolve()} +import json,sys +VERSION={version!r} +if sys.argv[-1]=='health': + print(json.dumps({{'ok':{not bad_health!r},'version':VERSION}}));sys.exit() +for line in sys.stdin: + msg=json.loads(line) + if msg['method']=='initialize': result={{'serverInfo':{{'version':VERSION + {".bad" if bad_protocol else ""!r}}}}} + elif msg['method']=='tools/list': result={{'tools':[{{'name':n}} for n in ('aua_setup','aua_ready','aua_observe')]}} + else: continue + print(json.dumps({{'jsonrpc':'2.0','id':msg['id'],'result':result}}),flush=True) +""" + with ZipFile(archive, "w") as zipfile: + zipfile.writestr( + "runtime.json", + json.dumps( + {"schema": 1, "version": version, "platform": platform or runtime.target()} + ), + ) + entry = ZipInfo("app/android-use-runtime") + entry.external_attr = (stat.S_IFREG | 0o755) << 16 + zipfile.writestr(entry, code) + for name, data in (extras or {}).items(): + zipfile.writestr(name, data) + return archive, hashlib.sha256(archive.read_bytes()).hexdigest() + + return create + + +def test_install_upgrade_rollback_stable_entry_and_settings_survive(tmp_path, bundle): + root = tmp_path / "runtime with spaces" + root.mkdir() + preferences = root / "private.env" + preferences.write_text("SENTINEL=private-local\n") + first = runtime.activate(root, *bundle()) + command = first["mcp_config"] + # For lifecycle tests avoid the automatic background update dispatch. + launch = [command["command"], *command["args"][:-1], "serve"] + probe(launch, {**os.environ, "PATH": str(tmp_path / "empty-path")}, "1.0.0") + second = runtime.activate(root, *bundle("2.0.0")) + assert second["mcp_config"] == command and second["previous"] == first["release"] + # Remove original archives: neither runtime needs their source or download directory. + for archive in tmp_path.glob("*.zip"): + archive.unlink() + probe(launch, os.environ.copy(), "2.0.0") + rolled = runtime.rollback(root) + assert rolled["version"] == "1.0.0" + probe(launch, os.environ.copy(), "1.0.0") + assert runtime.read_json(root / "update-policy.json")["paused"] + assert preferences.read_text() == "SENTINEL=private-local\n" + assert len(list((root / "releases").iterdir())) == 2 + + +@pytest.mark.parametrize("failure", ["digest", "platform", "health", "protocol", "version"]) +def test_failed_upgrade_keeps_active_release_and_removes_candidate(tmp_path, bundle, failure): + root = tmp_path / "install" + first = runtime.activate(root, *bundle()) + before = (root / "current.path").read_bytes() + archive, digest = bundle( + "2.0.0", + platform="wrong" if failure == "platform" else None, + bad_health=failure == "health", + bad_protocol=failure == "protocol", + ) + if failure == "digest": + digest = "0" * 64 + with pytest.raises(InstallError): + runtime.activate( + root, archive, digest, expected_version="3.0.0" if failure == "version" else None + ) + assert (root / "current.path").read_bytes() == before + assert runtime.status(root)["release"] == first["release"] + assert len(list((root / "releases").iterdir())) == 1 + assert not (root / "runtime.lock").exists() + + +@pytest.mark.parametrize( + "unsafe", + [ + "../outside", + "/absolute", + "app/../../outside", + "C:/outside", + "app\\outside", + "./runtime.json", + "RUNTIME.JSON", + "app/.. /outside", + "app/CON.txt", + ], +) +def test_archive_paths_and_case_collisions_refused_before_write(tmp_path, bundle, unsafe): + root = tmp_path / "install" + with pytest.raises(InstallError, match="unsafe_runtime_archive"): + runtime.activate(root, *bundle(extras={unsafe: "bad"})) + assert not (root / "current.path").exists() + assert not (tmp_path / "outside").exists() + + +def test_symlink_archive_refused(tmp_path, bundle): + archive, _ = bundle() + with ZipFile(archive, "a") as output: + link = ZipInfo("app/link") + link.external_attr = (stat.S_IFLNK | 0o777) << 16 + output.writestr(link, "../../outside") + with pytest.raises(InstallError, match="unsafe_runtime_archive"): + runtime.activate( + tmp_path / "runtime", archive, hashlib.sha256(archive.read_bytes()).hexdigest() + ) + + +def test_concurrent_install_and_failed_rollback_leave_pointer_unchanged( + tmp_path, bundle, monkeypatch +): + root = tmp_path / "install" + runtime.activate(root, *bundle()) + runtime.activate(root, *bundle("2.0.0")) + before = (root / "current.path").read_bytes() + (root / "runtime.lock").mkdir() + with pytest.raises(InstallError, match="upgrade_in_progress"): + runtime.activate(root, *bundle("3.0.0")) + (root / "runtime.lock").rmdir() + monkeypatch.setattr(runtime, "verify", lambda _: (_ for _ in ()).throw(InstallError("failed"))) + with pytest.raises(InstallError, match="failed"): + runtime.rollback(root) + assert (root / "current.path").read_bytes() == before + + +def test_atomic_promotion_failure_leaves_old_runtime(tmp_path, bundle, monkeypatch): + root = tmp_path / "install" + runtime.activate(root, *bundle()) + before = (root / "current.path").read_bytes() + original = runtime.atomic_write + + def fail(path, data): + if path.name == "current.path": + raise OSError("simulated disk failure") + return original(path, data) + + monkeypatch.setattr(runtime, "atomic_write", fail) + with pytest.raises(OSError): + runtime.activate(root, *bundle("2.0.0")) + assert (root / "current.path").read_bytes() == before + assert len(list((root / "releases").iterdir())) == 1 + + +def release_downloads(monkeypatch, archive, digest, *, version="2.0.0", checksum=None): + name = f"android-use-runtime-{runtime.target()}.zip" + prefix = f"https://github.com/{runtime.REPOSITORY}/releases/download/v{version}/" + info = { + "tag_name": "v" + version, + "assets": [ + {"name": item, "browser_download_url": prefix + item} for item in [name, "SHA256SUMS"] + ], + } + requested = [] + + def fetch(url, destination, limit=runtime.MAX_DOWNLOAD): + requested.append(url) + if "api.github.com" in url: + destination.write_text(json.dumps(info)) + elif url.endswith("SHA256SUMS"): + destination.write_text( + checksum if checksum is not None else digest + " " + name + "\n" + ) + else: + destination.write_bytes(archive.read_bytes()) + + monkeypatch.setattr(runtime, "fetch", fetch) + return info, requested + + +def test_download_update_validates_release_and_preserves_old_on_network_failure( + tmp_path, bundle, monkeypatch +): + root = tmp_path / "install" + first = runtime.activate(root, *bundle()) + release_downloads(monkeypatch, *bundle("2.0.0")) + assert runtime.checked_update(root)["version"] == "2.0.0" + assert not runtime.read_json(root / "update-policy.json")["paused"] + runtime.rollback(root) + assert runtime.status(root)["release"] == first["release"] + monkeypatch.setattr(runtime, "fetch", lambda *_: (_ for _ in ()).throw(OSError("offline"))) + with pytest.raises(OSError): + runtime.checked_update(root) + assert runtime.status(root)["version"] == "1.0.0" + assert not (root / "download.lock").exists() + + +@pytest.mark.parametrize("failure", ["asset", "checksum", "archive_version", "prerelease"]) +def test_invalid_download_never_promotes(tmp_path, bundle, monkeypatch, failure): + root = tmp_path / "install" + runtime.activate(root, *bundle()) + info, _ = release_downloads( + monkeypatch, + *bundle("9.0.0" if failure == "archive_version" else "2.0.0"), + checksum="" if failure == "checksum" else None, + ) + if failure == "asset": + info["assets"][0]["browser_download_url"] = "https://untrusted.example/payload" + if failure == "prerelease": + info["prerelease"] = True + with pytest.raises(InstallError): + runtime.checked_update(root) + assert runtime.status(root)["version"] == "1.0.0" + + +def test_automatic_check_cooldown_and_rollback_pause(tmp_path, bundle, monkeypatch): + root = tmp_path / "install" + runtime.activate(root, *bundle()) + calls = [] + monkeypatch.setattr(runtime, "update", lambda *_: calls.append(True)) + runtime.checked_update(root, automatic=True) + assert not calls + runtime.write_json(root / "last-check.json", {"time": 0}) + runtime.write_json(root / "update-policy.json", {"paused": True}) + runtime.checked_update(root, automatic=True) + assert not calls + + +def test_frozen_daemon_dispatch_and_bundled_dependencies(monkeypatch, tmp_path): + monkeypatch.setattr(sys, "frozen", True, raising=False) + monkeypatch.setattr(sys, "executable", str(tmp_path / "app/android-use-runtime")) + for name in ("ANDROID_USE_ADB", "ANDROID_USE_FFMPEG", "ANDROID_USE_OCR", "ADBUTILS_ADB_PATH"): + monkeypatch.setenv(name, "/stale/runtime/tool") + runtime.configure_bundle() + assert os.environ["ANDROID_USE_ADB"] == str( + tmp_path / "tools/adb" / ("adb.exe" if os.name == "nt" else "adb") + ) + assert os.environ["ANDROID_USE_FFMPEG"].startswith(str(tmp_path / "tools")) + + +def test_stale_download_cannot_replace_a_more_recent_install(tmp_path, bundle): + root = tmp_path / "install" + first = runtime.activate(root, *bundle()) + current = runtime.activate(root, *bundle("3.0.0")) + with pytest.raises(InstallError, match="runtime_changed_during_download"): + runtime.activate(root, *bundle("2.0.0"), expected_current=first["release"]) + assert runtime.status(root)["release"] == current["release"] + + +def test_latest_check_never_downgrades_a_newer_installed_version(tmp_path, bundle, monkeypatch): + root = tmp_path / "install" + runtime.activate(root, *bundle("3.0.0")) + _, requested = release_downloads(monkeypatch, *bundle("2.0.0")) + assert runtime.checked_update(root)["version"] == "3.0.0" + assert len(requested) == 1 + + +def test_corrupt_update_metadata_does_not_block_current_mcp(tmp_path, bundle, monkeypatch): + root = tmp_path / "install" + first = runtime.activate(root, *bundle()) + (root / "last-check.json").write_text("broken JSON") + monkeypatch.setenv("ANDROID_USE_AUTO_UPDATE", "1") + selected = [] + monkeypatch.setattr(os, "execv", lambda entry, args: selected.append(entry)) + runtime.auto_serve(root) + assert selected == [str(runtime.executable(root / "releases" / first["release"]))] + + +def test_background_process_failure_still_launches_current_runtime(tmp_path, bundle, monkeypatch): + root = tmp_path / "install" + first = runtime.activate(root, *bundle()) + runtime.write_json(root / "last-check.json", {"time": 0}) + monkeypatch.setenv("ANDROID_USE_AUTO_UPDATE", "1") + monkeypatch.setattr( + runtime.subprocess, "Popen", lambda *a, **k: (_ for _ in ()).throw(OSError("unavailable")) + ) + selected = [] + monkeypatch.setattr(os, "execv", lambda entry, args: selected.append(entry)) + runtime.auto_serve(root) + assert selected == [str(runtime.executable(root / "releases" / first["release"]))] + + +def test_optional_ocr_install_and_failed_upgrade_preserve_component(tmp_path, monkeypatch): + if os.name == "nt": + pytest.skip("POSIX executable fixture") + monkeypatch.setattr(runtime, "target", lambda: "macos-arm64") + root = tmp_path / "install" + + def component(api="vision-v1"): + archive = tmp_path / (api + ".zip") + with ZipFile(archive, "w") as output: + output.writestr( + "ocr.json", json.dumps({"schema": 1, "api": api, "platform": "macos-arm64"}) + ) + binary = ZipInfo("ocr") + binary.external_attr = (stat.S_IFREG | 0o755) << 16 + output.writestr(binary, f'#!{Path(sys.executable).resolve()}\nprint("[]")\n') + return archive, hashlib.sha256(archive.read_bytes()).hexdigest() + + assert runtime.ocr_binary(root) is None + assert runtime.install_ocr(root, *component())["ocr_installed"] + before = (root / "ocr.path").read_bytes() + assert runtime.ocr_binary(root).exists() + with pytest.raises(InstallError, match="invalid_ocr_component"): + runtime.install_ocr(root, *component("incompatible-v2")) + assert (root / "ocr.path").read_bytes() == before + assert len(list((root / "components").iterdir())) == 1 + + +def test_absent_optional_ocr_never_compiles_swift(tmp_path, monkeypatch): + from android_use.backend import UseError + from android_use.ocr import VisionOCR + + monkeypatch.setenv("ANDROID_USE_OCR", str(tmp_path / "not-installed")) + with pytest.raises(UseError, match="Optional local OCR is not installed"): + VisionOCR().recognize(None, 0) + + +def test_cli_relative_install_root_returns_absolute_stable_config( + tmp_path, bundle, monkeypatch, capsys +): + archive, digest = bundle() + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("ANDROID_USE_RUNTIME_DIR", str(tmp_path / "before")) + monkeypatch.setattr( + sys, + "argv", + [ + "android-use-runtime", + "--root", + "relative root", + "install", + "--archive", + str(archive), + "--sha256", + digest, + ], + ) + assert runtime.main() == 0 + result = json.loads(capsys.readouterr().out) + assert Path(result["mcp_config"]["args"][0]).is_absolute() + assert runtime.current_id(tmp_path / "relative root") == result["release"] From 5a5f29ef1e93417035a07b04bb5a9130e2eabb7f Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:40:41 +0800 Subject: [PATCH 02/13] fix: resolve the actual MSYS2 compiler tools on Windows --- .github/workflows/runtime.yml | 7 +++++-- scripts/build_runtime.py | 11 +++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index 6739d98..3bac828 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -39,6 +39,7 @@ jobs: with: python-version: '3.13.7' - name: Prepare Windows compiler + id: msys2 if: runner.os == 'Windows' uses: msys2/setup-msys2@v2 with: @@ -49,8 +50,10 @@ jobs: if: runner.os == 'Windows' shell: pwsh run: | - 'C:\msys64\mingw64\bin' >> $env:GITHUB_PATH - 'C:\msys64\usr\bin' >> $env:GITHUB_PATH + $msys = '${{ steps.msys2.outputs.msys2-location }}' + (Join-Path $msys 'mingw64/bin') >> $env:GITHUB_PATH + (Join-Path $msys 'usr/bin') >> $env:GITHUB_PATH + "ANDROID_USE_BUILD_BASH=$(Join-Path $msys 'usr/bin/bash.exe')" >> $env:GITHUB_ENV - run: uv sync --frozen --python 3.13.7 - run: uv pip install -r scripts/runtime-build-requirements.txt - name: Build native runtime and Dim plugin diff --git a/scripts/build_runtime.py b/scripts/build_runtime.py index 941978d..62c26cb 100644 --- a/scripts/build_runtime.py +++ b/scripts/build_runtime.py @@ -83,8 +83,15 @@ def build(output, cache, ffmpeg_binary=None): archive.extractall(work, filter="data") ffmpeg_binary = source / ("ffmpeg" + suffix) if not ffmpeg_binary.exists(): - run(["bash", "./configure", *CONFIGURE], cwd=source) - run(["make", "-j4", "ffmpeg"], cwd=source) + run( + [ + os.environ.get("ANDROID_USE_BUILD_BASH") or shutil.which("bash"), + "./configure", + *CONFIGURE, + ], + cwd=source, + ) + run([shutil.which("make"), "-j4", "ffmpeg"], cwd=source) config = subprocess.run( [str(ffmpeg_binary), "-buildconf"], capture_output=True, text=True, check=True ) From 76ae398ec3b34322e5c45624f41094052243a593 Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:46:23 +0800 Subject: [PATCH 03/13] docs: explain standalone onboarding and acknowledge iPhone Use --- README.md | 27 +++++++--- README.zh-CN.md | 26 +++++++--- docs/standalone.md | 122 +++++++++++++++++++++++++++++++++++++++++++++ docs/upgrading.md | 2 + 4 files changed, 163 insertions(+), 14 deletions(-) create mode 100644 docs/standalone.md diff --git a/README.md b/README.md index 76972e2..1b6e4a4 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,14 @@ For workflows that need repeated UI decisions, enable **Jev**. Your Agent keeps **No root, Appium, signing setup, or keyboard APK.** The compiled UI is included. Use USB or already-authorized wireless ADB. +## Standalone runtime (new source feature) + +**Python, ADB, ffmpeg, the screen UI and the control service in one native package.** The lightweight Dim plugin installs it automatically on first use. Later MCP connections start the installed version immediately and check for updates in the background; verified updates take effect on the next connection. Failed updates retain the previous version; rollback rechecks it before switching. + +**macOS OCR is an optional add-on**, omitted from the default package. Tree interaction, Agent screenshot inspection and Jev can be used without it. Ordinary users do not need Python, uv, Git, Node.js, a JDK or Xcode tools; the first-download bootstrap uses standard OS utilities. + +This is newer than the published v0.6.2 source-plugin ZIP. Use native workflow artifacts for offline trials until a release containing the runtime assets is published. [Install, automatic updates, optional OCR and rollback →](docs/standalone.md) + ## Quick start ### Use in Dim Agent @@ -39,8 +47,9 @@ https://github.com/arcships/android-use Read README.md, docs/guide.md and skills/android-use/SKILL.md. Reuse existing installations and preserve other MCP servers and uncommitted work. -Check Git, uv, ADB and ffmpeg; install missing dependencies from official sources. -Use scripts/install.py install --source . to create a stable managed runtime. +Read docs/standalone.md. Prefer the matching standalone runtime/Dim plugin when +available; verify its release SHA256. For a source-install fallback, check Git, uv, +ADB and ffmpeg, then use scripts/install.py install --source . for a stable runtime. Register its returned mcp_config as Dim's local stdio server named android_use; use Dim's MCP management or dim mcp add. Check for duplicate registrations first. Discover devices, select my intended phone, call aua_setup(action="status"), @@ -54,7 +63,7 @@ and unlocking. Leave Jev disabled for now.
Manual Dim setup — stable MCP entry -Prepare the dependencies and [clone the repository](#or-install-manually), then run from its root: +Prefer the [standalone package](docs/standalone.md), which returns a stable `mcp_config` without requiring a user Python/uv installation. For the source fallback, prepare dependencies and [clone the repository](#or-install-manually), then run from its root: ```bash uv run --no-project --python 3.13 python scripts/install.py install --source . @@ -62,15 +71,15 @@ uv run --no-project --python 3.13 python scripts/install.py install --source . The JSON result contains `mcp_config.command` and `mcp_config.args`. In Dim's **MCP management**, add a **local stdio** server named `android_use`, using that command and the arguments in their original order. The installer creates an independent runtime and verifies its MCP handshake before switching versions. -With the Dim CLI, the equivalent is below. Replace the two quoted placeholders with the exact `command` and `args[0]` returned by the installer: +With the Dim CLI, register the returned command and **all** arguments in order. This example is the standalone macOS/Linux entry; replace the launcher path with your actual install result: ```bash -dim mcp add --scope user android_use -- \ - "/absolute/path/from/mcp_config.command" \ - "/absolute/path/from/mcp_config.args[0]" serve +dim mcp add --scope user android_use -- /bin/sh "/absolute/path/runtime/launcher.sh" auto-serve dim mcp test android_use --json ``` +For Windows or the source installer, use their returned `mcp_config` instead of copying these arguments. See [native package installation](docs/standalone.md#offlinemanual-native-package). + Check that the MCP test returns a non-empty tool list. Some Dim CLI versions can return `success=true` with `tools=[]`; that alone does not confirm tools are loaded. In a new Dim chat, actually call `aua_setup` and `aua_ready`. If Android Use is already registered, inspect that entry before adding another. [Upgrade and rollback →](docs/upgrading.md)
@@ -295,6 +304,10 @@ Development comparisons include **18 source-level trials** and **12 live Agent / Multi-touch, arbitrary gesture paths, fine-grained text selection and custom-editor input fallbacks are not implemented. A matched UI condition proves that condition; the Agent must verify business outcomes. Control and preview run locally, and tool results are handled by your chosen client/model. +## Acknowledgements + +Thank you to [iPhone Use](https://github.com/zhongerxin/iPhone-use), its author and contributors for inspiring Android Use's phone-agent workflow, guided setup and live-screen experience. + ## Explore and contribute | Start here | Go deeper | diff --git a/README.zh-CN.md b/README.zh-CN.md index 14d08cf..9e30b3d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -23,6 +23,14 @@ Android Use 把你自己的 Android 手机或模拟器接入 **Dim Agent**,也 **无需 root、Appium、签名配置或键盘 APK。** 已包含编译好的界面,通过 USB 或已授权的无线 ADB 连接。 +## 独立运行包(新源码功能) + +**Python、ADB、ffmpeg、实时界面和控制服务,打成一个原生运行包。** 轻量 Dim 插件首次自动安装;后续 MCP 连接立即使用已安装版本,并在后台检查更新。新包校验、握手通过后,下一次连接使用新版;失败保留旧版,回滚前也会重新验证。 + +**macOS OCR 是可选组件,默认包不带。** 控件树操作、Agent 看图和 Jev 均可独立使用。普通用户无需准备 Python、uv、Git、Node.js、JDK 或 Xcode 工具,首次下载只使用系统基础工具。 + +此功能晚于已发布的 v0.6.2 源码插件 ZIP。正式 Release 尚未包含这些资产时,可用原生构建工作流产物离线体验。[安装、自动更新、可选 OCR 与回滚 →](docs/standalone.md#中文) + ## 快速开始 ### 在 Dim Agent 中使用 @@ -39,8 +47,8 @@ https://github.com/arcships/android-use 先阅读 README.md、docs/guide.zh-CN.md 和 skills/android-use/SKILL.md。 复用已有安装,保留其他 MCP 服务和未提交改动。 -检查 Git、uv、ADB、ffmpeg,从官方来源补齐依赖。 -用 scripts/install.py install --source . 创建固定入口的独立运行时。 +先读 docs/standalone.md,有对应原生包时优先使用独立运行包或轻量 Dim 插件,校验发行 SHA256。 +只有回退源码安装时,才检查 Git、uv、ADB、ffmpeg,并用 scripts/install.py install --source . 创建固定入口。 把返回的 mcp_config 注册为 Dim 的本地 stdio MCP,名称 android_use; 使用 Dim 的 MCP 管理或 dim mcp add,先检查已有注册,避免重复配置。 发现设备,明确选择我的目标手机,先调用 aua_setup(action="status"), @@ -53,7 +61,7 @@ https://github.com/arcships/android-use
手动配置 Dim:使用固定 MCP 入口 -准备依赖并[克隆仓库](#或者手动安装),在仓库根目录执行: +优先使用[独立运行包](docs/standalone.md#中文),它会返回固定 `mcp_config`,无需用户安装 Python/uv。回退源码安装时,准备依赖并[克隆仓库](#或者手动安装),在仓库根目录执行: ```bash uv run --no-project --python 3.13 python scripts/install.py install --source . @@ -61,15 +69,15 @@ uv run --no-project --python 3.13 python scripts/install.py install --source . 返回的 JSON 包含 `mcp_config.command` 和 `mcp_config.args`。在 Dim 的 **MCP 管理**中添加**本地 stdio** 服务,名称填 `android_use`,命令与参数按返回值逐项填写,保持参数顺序。安装器会创建独立运行时,真实 MCP 握手通过后才切换版本。 -已安装 Dim CLI 时,也可使用下方命令。两处带引号的占位路径分别替换为安装器返回的 `command` 和 `args[0]`: +已安装 Dim CLI 时,将返回的命令和**全部参数**依次注册。下方示例是独立包的 macOS/Linux 入口,启动器路径按安装结果替换: ```bash -dim mcp add --scope user android_use -- \ - "/absolute/path/from/mcp_config.command" \ - "/absolute/path/from/mcp_config.args[0]" serve +dim mcp add --scope user android_use -- /bin/sh "/absolute/path/runtime/launcher.sh" auto-serve dim mcp test android_use --json ``` +Windows 和源码安装器请使用各自返回的 `mcp_config`,不要照抄此参数。[原生包安装 →](docs/standalone.md#offlinemanual-native-package) + 检查 MCP 测试返回的工具列表是否非空;部分 Dim CLI 版本会返回 `success=true`、`tools=[]`,不能据此判断工具已加载。请在新的 Dim 聊天中实际调用 `aua_setup` 和 `aua_ready`。已有 Android Use 注册时,先检查原条目再配置。[升级与回退 →](docs/upgrading.md#中文)
@@ -295,6 +303,10 @@ v0.5.0 通过 **277 项 Python 测试、17 项界面测试**。内置 OCR 目前 多指手势、任意轨迹、精细文本选区及自绘编辑器输入兜底尚未实现。UI 条件满足仅证明该条件,Agent 仍需验收业务结果。控制和预览运行于本机,工具结果由你选择的客户端与模型处理。 +## 致谢 + +感谢 [iPhone Use](https://github.com/zhongerxin/iPhone-use) 的作者与贡献者,为 Android Use 在手机 Agent 交互、引导式安装和实时画面方面带来的启发。 + ## 文档与贡献 | 开始使用 | 深入了解 | diff --git a/docs/standalone.md b/docs/standalone.md new file mode 100644 index 0000000..83d54cd --- /dev/null +++ b/docs/standalone.md @@ -0,0 +1,122 @@ +# Standalone runtime / 独立运行包 + +**Source feature after v0.6.2.** Historical v0.6.2 source-plugin ZIPs do not contain this runtime. The **Standalone runtimes** workflow builds native archives and lightweight Dim plugins; tagged releases publish those artifacts only after their acceptance checks pass. Before a release containing these assets exists, use the workflow artifacts for offline installation. The lightweight plugin's production download URL cannot provision a runtime from an older release that lacks it. + +## What's included + +| Component | Default runtime | +| --- | --- | +| CPython + locked Python packages | Included. No user Python, pip or uv installation. | +| ADB / Android Platform Tools | Included; used by both shell transport and adbutils. | +| FFmpeg | Included; built from pinned source for H.264 input, screen filters and JPEG output. | +| Compiled screen and UiAutomator2 JAR | Included. No Node.js or JDK at runtime. | +| macOS OCR | **Separate optional component**, not in the default runtime. No Swift compiler needed when installed. | +| Git | Not required for runtime installation or updates. | + +Build targets are `macos-arm64`, `macos-x86_64`, `linux-x86_64` (Ubuntu 22.04 build environment) and `windows-x86_64`. Native acceptance results are reported per platform; a configured matrix is not itself a passing result. The Windows entry uses a fixed native bridge and inherits raw stdio, avoiding PowerShell text conversion in regular MCP calls. + +The phone still needs USB debugging, authorization and unlocking. OEM USB drivers/security settings and the phone's `screenrecord` capability are not supplied by a desktop package. Dim Agent must execute on the host with ADB access. Jev remains optional and uses the user's own TypeSafe key in the settings panel. + +## Install in Dim Agent + +### Lightweight plugin + +From a release containing native assets, download the matching `android-use-VERSION-PLATFORM-dim-plugin.zip`, verify its SHA256 from `SHA256SUMS`, extract it, and install that directory using Dim's plugin management or: + +```bash +dim plugin install /absolute/path/to/extracted-dim-plugin +``` + +This is a **Dim** plugin: its MCP root placeholder follows Dim's plugin loader. It is separate from the historical Codex/source plugin ZIP. Keep one Android Use registration enabled to avoid duplicate tools and competing device operations. + +On first use, its OS bootstrap downloads the matching runtime and checks SHA256 before executing its installer. POSIX bootstrap uses `/bin/sh`, curl, unzip and sha256sum/shasum; Windows uses the built-in PowerShell/.NET tools. Only the initial download needs these OS utilities; managed launches use the native runtime. Bootstrap diagnostics go to stderr, keeping stdout reserved for MCP. Initial provisioning needs network access and may take longer than the client's startup timeout; let the Agent run the bootstrap/setup first, then reconnect MCP if necessary. + +### Offline/manual native package + +Download `android-use-runtime-PLATFORM.zip` and the release's `SHA256SUMS`. For macOS/Linux, from the download directory: + +```bash +unzip android-use-runtime-macos-arm64.zip -d android-use-runtime +./android-use-runtime/app/android-use-runtime install \ + --archive android-use-runtime-macos-arm64.zip \ + --sha256 REPLACE_WITH_THE_64_HEX_VALUE_FROM_SHA256SUMS +``` + +Replace the platform in the filename for Intel macOS or Linux. Windows PowerShell: + +```powershell +Expand-Archive .\android-use-runtime-windows-x86_64.zip .\android-use-runtime +& .\android-use-runtime\app\android-use-runtime.exe install ` + --archive .\android-use-runtime-windows-x86_64.zip ` + --sha256 REPLACE_WITH_THE_64_HEX_VALUE_FROM_SHA256SUMS +``` + +Use the returned `mcp_config.command` and **all** `mcp_config.args`, unchanged, in Dim's local stdio MCP configuration. Then verify the actual tools and phone with `aua_setup(action="status")`, start once if absent, `aua_ready`, and `aua_screen`. A CLI response with `success=true` and `tools=[]` is not evidence of tool discovery. + +The install root defaults to `~/.local/share/android-use/runtime`. Set `ANDROID_USE_RUNTIME_DIR` to select another location. Managed launch paths remain stable; original ZIPs/extraction directories may be removed after installation. Keep the managed directory. Existing device and Jev state remain in the usual Android Use state directory, or the client's explicit `ANDROID_USE_STATE_DIR`. + +**Migrating from a source installation:** register the returned stable command once, keeping the existing MCP entry's `env` settings and intended state directory. The old source launcher's private `launch.env` is not silently imported: migrate required values privately into the new client's environment or configure Jev through the screen. No old installation or unrelated client configuration is deleted automatically. A full app restart is not intrinsic to this runtime; the host must reconnect/reload MCP for a new process to use an upgraded version. + +## Updates and rollback + +At a new MCP connection, the launcher starts the installed version immediately. If enabled and due, an independent background process checks the repository's latest stable GitHub release, at most once per 24 hours. It downloads to a temporary directory, checks SHA256, validates archive paths/platform/version, runs bundled dependency health checks and a real MCP `initialize` + `tools/list` probe, then switches one atomic pointer. The current task/process is not stopped. **The next MCP connection uses the promoted version.** This is not live replacement of an already-connected MCP process. + +Network/checksum/health failures leave the active pointer unchanged. Newer local versions are not automatically downgraded. A download cannot overwrite an installation that changed while it was downloading. Update-process/log/auxiliary-metadata failures do not prevent a healthy installed MCP from serving. An offline initial install requires a local runtime archive; offline updates continue using the installed version. + +On macOS/Linux, use the same fixed launcher for management: + +```bash +/bin/sh "$HOME/.local/share/android-use/runtime/launcher.sh" status +/bin/sh "$HOME/.local/share/android-use/runtime/launcher.sh" update +/bin/sh "$HOME/.local/share/android-use/runtime/launcher.sh" update --version 0.7.0 +/bin/sh "$HOME/.local/share/android-use/runtime/launcher.sh" rollback +/bin/sh "$HOME/.local/share/android-use/runtime/launcher.sh" cli tools +``` + +`0.7.0` is an example, not a claim that this version has been released. On Windows, replace the command with the `mcp_config.command` returned at installation, keep its `--root ROOT` arguments, and replace the final `auto-serve` with `status`, `update`, `rollback`, or `cli tools`. + +Rollback rechecks the previous runtime before switching. It pauses automatic updates to keep that selected version in place; an explicit successful `update` resumes checking. `ANDROID_USE_AUTO_UPDATE=0` in the MCP environment also disables automatic checks. Runtime directories are retained, including versions used by existing processes. No automatic deletion of potentially active versions occurs. + +Installation/promotion and rollback are serialized by `runtime.lock`; background downloads use `download.lock`. A forced process/OS termination can leave a lock. Confirm that no corresponding installer/updater is running before removing it. Pointer replacement is atomic; filesystem corruption, host process termination and external edits remain outside that guarantee. Release SHA256 fetched from the same trusted HTTPS release protects transfer integrity, not a compromised publishing account. The update repository is fixed to `arcships/android-use`. + +## Optional macOS OCR + +Tree-based interaction, Agent screenshot inspection and Jev decision/visual-location paths do not require the local OCR program. Automatic local OCR of text on pages without useful accessibility text does require it. **Jev Box location is not an OCR replacement.** Without the component, local OCR reports `ocr_unavailable`; it does not invoke Swift or install a compiler. + +Install only when needed: + +```bash +/bin/sh "$HOME/.local/share/android-use/runtime/launcher.sh" install-ocr +``` + +This downloads the matching release's `android-use-ocr-PLATFORM.zip`, checks its SHA256 and `vision-v1` interface/platform, runs the native helper against a local test image, then atomically activates it. Reconnect MCP afterward. Offline installation uses the same command with `--archive /path/to/android-use-ocr-macos-arm64.zip --sha256 VALUE`. Components and preferences live outside runtime versions and survive upgrades/rollback; failed component updates retain the old component. Linux/Windows do not gain the macOS Vision provider; the Agent can inspect screenshots or supply OCR text through the existing field interface. + +## Build and acceptance + +Build on the target OS with Python 3.13.7, uv, a C compiler, make and Bash; macOS additionally needs Swift for the optional component. Windows CI provisions a MinGW toolchain. End users do not need these build tools. + +```bash +uv sync --frozen --python 3.13.7 +uv pip install -r scripts/runtime-build-requirements.txt +uv run --no-sync python scripts/build_runtime.py +uv run --no-sync python scripts/build_runtime_upgrade_fixture.py +uv run --no-sync python scripts/accept_runtime.py \ + --archive dist/runtime/android-use-runtime-macos-arm64.zip \ + --upgrade-archive dist/runtime-upgrade/android-use-runtime-macos-arm64.zip +``` + +The upgrade fixture builds a distinct `+upgrade-test` version in a disposable source tree; it is never published. Native acceptance removes system Python/uv/ADB/ffmpeg from PATH, checks packaged tools and UI resources, retains a live MCP connection across install/rollback, deletes the original extraction, rejects corrupted/mismatched upgrades, preserves private settings, tests the frozen daemon dispatch and actual H.264-to-JPEG conversion. macOS also checks optional OCR installation and recognition. The lightweight plugin's first-install test stubs only download transport with local artifacts while checking production URLs; it is not a live GitHub release-download test. No phone or model calls are made. + +Inputs are pinned in `scripts/runtime-inputs.json`. Archives carry Python/ADB notices and corresponding FFmpeg source/configuration. The legacy source/Codex package and its installer continue to work independently. [Recorded results and limits](validation.md). + +## 中文 + +这是 v0.6.2 之后的新源码功能,旧 v0.6.2 插件包不包含独立运行时。跨平台工作流生成原生运行包、轻量 Dim 插件与 SHA256;正式发布需要对应 Release 中实际有这些资产,不能把旧 ZIP 当成新包。发布前可使用工作流产物离线安装。 + +默认包内置 Python、Python 依赖、ADB、ffmpeg、界面和控制 JAR,普通用户无需 Git、uv、Node.js 或 JDK。**macOS OCR 不默认携带**,需要本地识字时用固定入口的 `install-ocr` 安装可选组件,安装后也不需要 Xcode/Swift。未安装时明确返回不可用,不悄悄编译。Jev 决策和视觉定位不等同于 OCR;树缺失页面的自动离线文字提取仍需此组件。 + +轻量 Dim 插件首次自动下载匹配平台的运行包、校验并安装;离线包安装命令见上文,安装结果中的 `mcp_config` 可直接用于 Dim 的本地 stdio 配置。首次安装的网络等待可能超过客户端启动超时,可先由 Agent 完成准备再重新连接。手机 USB 授权、解锁、厂商驱动及系统录屏能力仍由设备和用户提供。 + +后续连接立即使用已安装版本,每 24 小时最多后台检查一次更新。新包验证和真实 MCP 握手通过后才切换单一指针;当前会话继续执行,下一次 MCP 连接使用新版。失败保留旧版,不自动降级,不覆盖下载期间发生的其他安装。回滚先验证旧包,再切换,并暂停自动更新;显式成功执行 `update` 后恢复检查,也可用 `ANDROID_USE_AUTO_UPDATE=0` 禁用。没有实现正在运行的 MCP 进程热替换。 + +固定目录、已有版本和可选组件保留,设备/Jev 设置不清除。迁移旧源码入口时要保留 MCP 的 `env` 和 `ANDROID_USE_STATE_DIR`;旧安装器的 `launch.env` 不会自动导入,应私下迁移必要配置,或在界面重新设置 Jev。普通升级不依赖解压目录或系统 Python;宿主仍需重连以加载新版。强制终止残留的锁必须确认进程已退出后处理。 diff --git a/docs/upgrading.md b/docs/upgrading.md index 552255a..0202b49 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -1,5 +1,7 @@ # Stable installation and upgrades +For the new self-contained runtime, automatic background updates and optional OCR, use the [standalone guide](standalone.md). The uv-based source/Codex installer described below remains supported; its external Python/uv prerequisites do not apply to the standalone package. + This installer ships in **v0.6.2** and later source/ZIP installations. Verify the release checksum, extract it, and run its `scripts/install.py`. The older v0.6.1 ZIP does not contain the installer; a current installer can also install an older extracted release with `--source /path/to/extracted-release`. ## Codex: one command, one registration From f8477ec1c2c2358e3d48f0b00fb35f6a76c607a0 Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:55:41 +0800 Subject: [PATCH 04/13] fix: verify shared build inputs and authenticate private runtime downloads --- .github/workflows/runtime.yml | 19 +++++ README.md | 2 +- README.zh-CN.md | 2 +- docs/standalone.md | 10 ++- scripts/accept_runtime.py | 31 ++++++++ scripts/build_runtime.py | 33 ++++++-- scripts/fetch_runtime_inputs.py | 16 ++++ scripts/runtime.ps1 | 15 +++- scripts/runtime.sh | 9 ++- src/android_use/portable.py | 136 ++++++++++++++++++++------------ tests/test_portable.py | 97 +++++++++++++++++++++++ tests/test_runtime_build.py | 50 ++++++++++++ 12 files changed, 353 insertions(+), 67 deletions(-) create mode 100644 scripts/fetch_runtime_inputs.py create mode 100644 tests/test_runtime_build.py diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index 3bac828..801ae8d 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -18,7 +18,22 @@ permissions: contents: read jobs: + inputs: + runs-on: ubuntu-22.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v6 + with: + python-version: '3.13.7' + - run: uv run --frozen python scripts/fetch_runtime_inputs.py --cache dist/runtime-inputs + - uses: actions/upload-artifact@v4 + with: + name: standalone-build-inputs + path: dist/runtime-inputs/* + retention-days: 7 build: + needs: inputs strategy: fail-fast: false matrix: @@ -54,6 +69,10 @@ jobs: (Join-Path $msys 'mingw64/bin') >> $env:GITHUB_PATH (Join-Path $msys 'usr/bin') >> $env:GITHUB_PATH "ANDROID_USE_BUILD_BASH=$(Join-Path $msys 'usr/bin/bash.exe')" >> $env:GITHUB_ENV + - uses: actions/download-artifact@v4 + with: + name: standalone-build-inputs + path: dist/runtime-build - run: uv sync --frozen --python 3.13.7 - run: uv pip install -r scripts/runtime-build-requirements.txt - name: Build native runtime and Dim plugin diff --git a/README.md b/README.md index 1b6e4a4..6b42d1d 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ For workflows that need repeated UI decisions, enable **Jev**. Your Agent keeps **Python, ADB, ffmpeg, the screen UI and the control service in one native package.** The lightweight Dim plugin installs it automatically on first use. Later MCP connections start the installed version immediately and check for updates in the background; verified updates take effect on the next connection. Failed updates retain the previous version; rollback rechecks it before switching. -**macOS OCR is an optional add-on**, omitted from the default package. Tree interaction, Agent screenshot inspection and Jev can be used without it. Ordinary users do not need Python, uv, Git, Node.js, a JDK or Xcode tools; the first-download bootstrap uses standard OS utilities. +**macOS OCR is an optional add-on**, omitted from the default package. Tree interaction, Agent screenshot inspection and Jev can be used without it. Ordinary users do not need Python, uv, Git, Node.js, a JDK or Xcode tools; public-release bootstrap uses standard OS utilities. Private-release bootstrap additionally supports GitHub CLI with a private token; offline native installation avoids that requirement. This is newer than the published v0.6.2 source-plugin ZIP. Use native workflow artifacts for offline trials until a release containing the runtime assets is published. [Install, automatic updates, optional OCR and rollback →](docs/standalone.md) diff --git a/README.zh-CN.md b/README.zh-CN.md index 9e30b3d..ed6b44a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -27,7 +27,7 @@ Android Use 把你自己的 Android 手机或模拟器接入 **Dim Agent**,也 **Python、ADB、ffmpeg、实时界面和控制服务,打成一个原生运行包。** 轻量 Dim 插件首次自动安装;后续 MCP 连接立即使用已安装版本,并在后台检查更新。新包校验、握手通过后,下一次连接使用新版;失败保留旧版,回滚前也会重新验证。 -**macOS OCR 是可选组件,默认包不带。** 控件树操作、Agent 看图和 Jev 均可独立使用。普通用户无需准备 Python、uv、Git、Node.js、JDK 或 Xcode 工具,首次下载只使用系统基础工具。 +**macOS OCR 是可选组件,默认包不带。** 控件树操作、Agent 看图和 Jev 均可独立使用。普通用户无需准备 Python、uv、Git、Node.js、JDK 或 Xcode 工具,公开发行包首次下载只使用系统基础工具。私有发行包自动安装支持 GitHub CLI 与私有令牌,也可用原生离线包省去此依赖。 此功能晚于已发布的 v0.6.2 源码插件 ZIP。正式 Release 尚未包含这些资产时,可用原生构建工作流产物离线体验。[安装、自动更新、可选 OCR 与回滚 →](docs/standalone.md#中文) diff --git a/docs/standalone.md b/docs/standalone.md index 83d54cd..f625d84 100644 --- a/docs/standalone.md +++ b/docs/standalone.md @@ -29,7 +29,11 @@ dim plugin install /absolute/path/to/extracted-dim-plugin This is a **Dim** plugin: its MCP root placeholder follows Dim's plugin loader. It is separate from the historical Codex/source plugin ZIP. Keep one Android Use registration enabled to avoid duplicate tools and competing device operations. -On first use, its OS bootstrap downloads the matching runtime and checks SHA256 before executing its installer. POSIX bootstrap uses `/bin/sh`, curl, unzip and sha256sum/shasum; Windows uses the built-in PowerShell/.NET tools. Only the initial download needs these OS utilities; managed launches use the native runtime. Bootstrap diagnostics go to stderr, keeping stdout reserved for MCP. Initial provisioning needs network access and may take longer than the client's startup timeout; let the Agent run the bootstrap/setup first, then reconnect MCP if necessary. +On first use, its OS bootstrap downloads the matching runtime and checks SHA256 before executing its installer. For public releases, POSIX bootstrap uses `/bin/sh`, curl, unzip and sha256sum/shasum; Windows uses the built-in PowerShell/.NET tools. Only the initial download needs these OS utilities; managed launches use the native runtime. Bootstrap diagnostics go to stderr, keeping stdout reserved for MCP. Initial provisioning needs network access and may take longer than the client's startup timeout; let the Agent run the bootstrap/setup first, then reconnect MCP if necessary. + +### Private releases + +Public releases use unauthenticated HTTPS downloads. For a private repository, set `ANDROID_USE_GITHUB_TOKEN` in the MCP client's private environment to a token with read access to the release assets. Never put it in a chat or commit it. Native updates and optional OCR downloads use validated GitHub API asset URLs; authorization is stripped on cross-origin redirects. The bootstrap can use GitHub CLI for the first private download when the token is set; alternatively install the native archive offline first. GitHub CLI is not needed afterward. Missing access leaves an existing runtime unchanged. ### Offline/manual native package @@ -77,7 +81,7 @@ On macOS/Linux, use the same fixed launcher for management: Rollback rechecks the previous runtime before switching. It pauses automatic updates to keep that selected version in place; an explicit successful `update` resumes checking. `ANDROID_USE_AUTO_UPDATE=0` in the MCP environment also disables automatic checks. Runtime directories are retained, including versions used by existing processes. No automatic deletion of potentially active versions occurs. -Installation/promotion and rollback are serialized by `runtime.lock`; background downloads use `download.lock`. A forced process/OS termination can leave a lock. Confirm that no corresponding installer/updater is running before removing it. Pointer replacement is atomic; filesystem corruption, host process termination and external edits remain outside that guarantee. Release SHA256 fetched from the same trusted HTTPS release protects transfer integrity, not a compromised publishing account. The update repository is fixed to `arcships/android-use`. +Installation/promotion and rollback are serialized by `runtime.lock`; background downloads use `download.lock`. A forced process/OS termination can leave a lock. Confirm that no corresponding installer/updater is running before removing it. Pointer replacement is atomic; filesystem corruption, host process termination and external edits remain outside that guarantee. Release SHA256 fetched from the same trusted HTTPS release protects transfer integrity, not a compromised publishing account. The update repository is fixed to `arcships/android-use`. HTTPS-only requests use the bundled Python HTTP client and CA bundle. ## Optional macOS OCR @@ -120,3 +124,5 @@ Inputs are pinned in `scripts/runtime-inputs.json`. Archives carry Python/ADB no 后续连接立即使用已安装版本,每 24 小时最多后台检查一次更新。新包验证和真实 MCP 握手通过后才切换单一指针;当前会话继续执行,下一次 MCP 连接使用新版。失败保留旧版,不自动降级,不覆盖下载期间发生的其他安装。回滚先验证旧包,再切换,并暂停自动更新;显式成功执行 `update` 后恢复检查,也可用 `ANDROID_USE_AUTO_UPDATE=0` 禁用。没有实现正在运行的 MCP 进程热替换。 固定目录、已有版本和可选组件保留,设备/Jev 设置不清除。迁移旧源码入口时要保留 MCP 的 `env` 和 `ANDROID_USE_STATE_DIR`;旧安装器的 `launch.env` 不会自动导入,应私下迁移必要配置,或在界面重新设置 Jev。普通升级不依赖解压目录或系统 Python;宿主仍需重连以加载新版。强制终止残留的锁必须确认进程已退出后处理。 + +私有发行包需要下载权限:可在 MCP 私有环境中设置 `ANDROID_USE_GITHUB_TOKEN`。首次自动安装还需 GitHub CLI,也可先离线安装运行包;后续更新和 OCR 下载使用包内 HTTP 客户端,无需 GitHub CLI。令牌仅发送到固定仓库的 GitHub API,跨域重定向不携带令牌,不在输出中回显。 diff --git a/scripts/accept_runtime.py b/scripts/accept_runtime.py index 70fda96..e432bba 100644 --- a/scripts/accept_runtime.py +++ b/scripts/accept_runtime.py @@ -290,6 +290,37 @@ def quote(value): passed.append( "packaged_plugin_first_install_and_clean_stdio_with_stubbed_download_transport" ) + fakebin = folder / "private-fakebin" + fakebin.mkdir() + driver = fakebin / "gh_driver.py" + driver.write_text(f"""import os,sys,shutil +from pathlib import Path +assert os.environ.get('GH_TOKEN') == 'fixture-private-token' +assert sys.argv[1:3] == ['release','download'] +assert sys.argv[sys.argv.index('--repo')+1] == 'arcships/android-use' +output=Path(sys.argv[sys.argv.index('--dir')+1]) +shutil.copyfile({str(sums)!r},output/'SHA256SUMS') +shutil.copyfile({str(archive)!r},output/{archive.name!r}) +""") + if os.name == "nt": + (fakebin / "gh.cmd").write_bytes( + ( + f'@echo off\r\n"{Path(sys.executable).resolve()}" "{driver}" %*\r\nexit /b %errorlevel%\r\n' + ).encode() + ) + else: + gh = fakebin / "gh" + gh.write_text(f"#!{Path(sys.executable).resolve()}\n" + driver.read_text()) + gh.chmod(0o755) + private_env = { + **bootstrap_env, + "ANDROID_USE_RUNTIME_DIR": str(folder / "private-bootstrap-runtime"), + "ANDROID_USE_GITHUB_TOKEN": "fixture-private-token", + "PATH": str(fakebin) + os.pathsep + os.environ.get("PATH", ""), + } + assert await connected(launch, private_env) == version + passed.append("private_plugin_bootstrap_with_stubbed_github_cli_and_clean_stdio") + return { "platform": target(), "version": version, diff --git a/scripts/build_runtime.py b/scripts/build_runtime.py index 62c26cb..4cec16c 100644 --- a/scripts/build_runtime.py +++ b/scripts/build_runtime.py @@ -11,9 +11,13 @@ import subprocess import sys import tarfile +import time +import uuid from pathlib import Path from zipfile import ZIP_DEFLATED, ZipFile +import httpx + ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) from android_use import __version__ # noqa: E402 @@ -47,13 +51,28 @@ def run(args, cwd=None): def locked_input(cache, item): path = cache / item["filename"] - if not path.exists(): - fetch(item["url"], path) - with path.open("rb") as stream: - digest = hashlib.file_digest(stream, "sha256").hexdigest() - if digest != item["sha256"]: - raise ValueError("Build input checksum mismatch: " + path.name) - return path + if path.exists(): + with path.open("rb") as stream: + if hashlib.file_digest(stream, "sha256").hexdigest() == item["sha256"]: + return path + temporary = cache / (item["filename"] + ".download-" + uuid.uuid4().hex) + try: + for attempt in range(3): + try: + fetch(item["url"], temporary) + break + except (OSError, httpx.TransportError): + if attempt == 2: + raise + time.sleep(attempt + 1) + with temporary.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + if digest != item["sha256"]: + raise ValueError("Build input checksum mismatch: " + path.name) + os.replace(temporary, path) + return path + finally: + temporary.unlink(missing_ok=True) def archive_folder(folder, destination): diff --git a/scripts/fetch_runtime_inputs.py b/scripts/fetch_runtime_inputs.py new file mode 100644 index 0000000..0a9da2f --- /dev/null +++ b/scripts/fetch_runtime_inputs.py @@ -0,0 +1,16 @@ +"""Fetch and verify upstream build inputs once, before native CI fan-out.""" + +import argparse +import json +from pathlib import Path + +from build_runtime import ROOT, locked_input + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cache", type=Path, required=True) + args = parser.parse_args() + args.cache.mkdir(parents=True, exist_ok=True) + lock = json.loads((ROOT / "scripts/runtime-inputs.json").read_text()) + for item in [lock["ffmpeg"], *lock["adb"].values()]: + print(locked_input(args.cache, item).name) diff --git a/scripts/runtime.ps1 b/scripts/runtime.ps1 index 0d6206b..f7b6376 100644 --- a/scripts/runtime.ps1 +++ b/scripts/runtime.ps1 @@ -19,8 +19,19 @@ $name = 'android-use-runtime-windows-x86_64.zip' $work = Join-Path ([System.IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString('N')) New-Item -ItemType Directory -Path $work | Out-Null try { - Invoke-WebRequest -UseBasicParsing -TimeoutSec 180 "$base/SHA256SUMS" -OutFile (Join-Path $work 'SHA256SUMS') - Invoke-WebRequest -UseBasicParsing -TimeoutSec 180 "$base/$name" -OutFile (Join-Path $work $name) + if ($env:ANDROID_USE_GITHUB_TOKEN) { + if (-not (Get-Command gh -ErrorAction SilentlyContinue)) { throw 'Private bootstrap requires GitHub CLI, or offline runtime installation' } + $previousToken = $env:GH_TOKEN + try { + $env:GH_TOKEN = $env:ANDROID_USE_GITHUB_TOKEN + $downloadOutput = & gh release download --repo arcships/android-use --pattern SHA256SUMS --pattern $name --dir $work + if ($downloadOutput) { [Console]::Error.WriteLine(($downloadOutput -join [Environment]::NewLine)) } + if ($LASTEXITCODE -ne 0) { throw 'Private runtime download failed' } + } finally { $env:GH_TOKEN = $previousToken } + } else { + Invoke-WebRequest -UseBasicParsing -TimeoutSec 180 "$base/SHA256SUMS" -OutFile (Join-Path $work 'SHA256SUMS') + Invoke-WebRequest -UseBasicParsing -TimeoutSec 180 "$base/$name" -OutFile (Join-Path $work $name) + } $lines = @(Get-Content (Join-Path $work 'SHA256SUMS') | Where-Object { $_ -match "^[a-fA-F0-9]{64}\s+\*?$([regex]::Escape($name))$" }) if ($lines.Count -ne 1) { throw 'Missing runtime checksum' } $expected = ($lines[0] -split '\s+')[0].ToLowerInvariant() diff --git a/scripts/runtime.sh b/scripts/runtime.sh index 59d8566..1689d21 100644 --- a/scripts/runtime.sh +++ b/scripts/runtime.sh @@ -15,8 +15,13 @@ base=https://github.com/arcships/android-use/releases/latest/download name=android-use-runtime-$target.zip work=$(mktemp -d) trap 'rm -rf "$work"' EXIT HUP INT TERM -curl -fL --retry 2 --connect-timeout 15 --max-time 180 "$base/SHA256SUMS" -o "$work/SHA256SUMS" >&2 -curl -fL --retry 2 --connect-timeout 15 --max-time 180 "$base/$name" -o "$work/$name" >&2 +if [ -n "${ANDROID_USE_GITHUB_TOKEN:-}" ]; then + command -v gh >/dev/null 2>&1 || { echo 'Private bootstrap requires GitHub CLI, or install the runtime archive offline first' >&2; exit 1; } + GH_TOKEN="$ANDROID_USE_GITHUB_TOKEN" gh release download --repo arcships/android-use --pattern SHA256SUMS --pattern "$name" --dir "$work" >&2 +else + curl -fL --retry 2 --connect-timeout 15 --max-time 180 "$base/SHA256SUMS" -o "$work/SHA256SUMS" >&2 + curl -fL --retry 2 --connect-timeout 15 --max-time 180 "$base/$name" -o "$work/$name" >&2 +fi expected=$(awk -v file="$name" '$2==file {print $1}' "$work/SHA256SUMS") case "$expected" in ''|*[!a-fA-F0-9]*) echo 'Invalid runtime checksum' >&2; exit 1;; esac [ "${#expected}" -eq 64 ] || exit 1 diff --git a/src/android_use/portable.py b/src/android_use/portable.py index 968a833..c661273 100644 --- a/src/android_use/portable.py +++ b/src/android_use/portable.py @@ -12,7 +12,6 @@ import sys import tempfile import time -import urllib.request import uuid from pathlib import Path from zipfile import ZipFile @@ -301,34 +300,93 @@ def rollback(root): def fetch(url, destination, limit=MAX_DOWNLOAD): + import httpx + if not url.startswith("https://"): raise InstallError("runtime_download_requires_https") - request = urllib.request.Request( - url, headers={"User-Agent": "android-use-runtime", "Accept": "application/octet-stream"} + asset_api = re.fullmatch( + r"https://api.github.com/repos/arcships/android-use/releases/assets/[0-9]+", url ) - with urllib.request.urlopen(request, timeout=15) as response, destination.open("wb") as stream: - total = 0 - while block := response.read(1024 * 1024): - total += len(block) - if total > limit: - raise InstallError("runtime_download_too_large") - stream.write(block) + headers = { + "User-Agent": "android-use-runtime", + "Accept": "application/octet-stream" + if asset_api or not url.startswith("https://api.github.com/") + else "application/vnd.github+json", + } + token = os.environ.get("ANDROID_USE_GITHUB_TOKEN") + if token and url.startswith(f"https://api.github.com/repos/{REPOSITORY}/"): + headers["Authorization"] = "Bearer " + token + + def https_only(request): + if request.url.scheme != "https": + raise InstallError("runtime_download_requires_https") + + # HTTPX removes Authorization on cross-origin redirects and includes bundled CAs. + with httpx.Client( + follow_redirects=True, timeout=15, event_hooks={"request": [https_only]} + ) as client: + with client.stream("GET", url, headers=headers) as response: + response.raise_for_status() + with destination.open("wb") as stream: + total = 0 + for block in response.iter_bytes(1024 * 1024): + total += len(block) + if total > limit: + raise InstallError("runtime_download_too_large") + stream.write(block) + + +def release_info(temporary, version=None): + if version is not None and not re.fullmatch(VERSION, version): + raise InstallError("invalid_runtime_version") + endpoint = "latest" if version is None else "tags/v" + version + release = temporary / "release.json" + fetch(f"https://api.github.com/repos/{REPOSITORY}/releases/{endpoint}", release, 2_000_000) + info = json.loads(release.read_text()) + tag = info.get("tag_name", "") + if info.get("draft") or info.get("prerelease") or not re.fullmatch("v" + VERSION, tag): + raise InstallError("invalid_runtime_release") + if version and tag != "v" + version: + raise InstallError("runtime_release_version_mismatch") + return info + + +def download_asset(info, name, temporary): + prefix = f"https://github.com/{REPOSITORY}/releases/download/{info['tag_name']}/" + assets = {a["name"]: a for a in info.get("assets", [])} + + def asset_url(filename): + asset = assets.get(filename, {}) + if asset.get("browser_download_url") != prefix + filename: + raise InstallError("runtime_release_assets_missing") + if os.environ.get("ANDROID_USE_GITHUB_TOKEN"): + url = asset.get("url", "") + if not re.fullmatch( + r"https://api.github.com/repos/arcships/android-use/releases/assets/[0-9]+", url + ): + raise InstallError("invalid_private_asset_url") + return url + return prefix + filename + + sums = temporary / "SHA256SUMS" + fetch(asset_url("SHA256SUMS"), sums, 1_000_000) + matches = [ + line.split()[0] + for line in sums.read_text().splitlines() + if len(line.split()) == 2 and line.split()[1].lstrip("*") == name + ] + if len(matches) != 1: + raise InstallError("runtime_checksum_missing") + archive = temporary / name + fetch(asset_url(name), archive) + return archive, matches[0] def update(root, version=None): with tempfile.TemporaryDirectory(prefix="android-use-update-") as temporary: temporary = Path(temporary) - release = temporary / "release.json" - if version is not None and not re.fullmatch(VERSION, version): - raise InstallError("invalid_runtime_version") - endpoint = "latest" if version is None else "tags/v" + version - fetch(f"https://api.github.com/repos/{REPOSITORY}/releases/{endpoint}", release, 2_000_000) - info = json.loads(release.read_text()) - tag = info.get("tag_name", "") - if info.get("draft") or info.get("prerelease") or not re.fullmatch("v" + VERSION, tag): - raise InstallError("invalid_runtime_release") - if version and tag != "v" + version: - raise InstallError("runtime_release_version_mismatch") + info = release_info(temporary, version) + tag = info["tag_name"] installed = status(root) installed_version = installed.get("version") if installed_version == tag[1:]: @@ -340,26 +398,11 @@ def numbers(text): if numbers(installed_version) >= numbers(tag[1:]): return installed - name = f"android-use-runtime-{target()}.zip" - prefix = f"https://github.com/{REPOSITORY}/releases/download/{tag}/" - assets = {a["name"]: a.get("browser_download_url") for a in info.get("assets", [])} - if assets.get(name) != prefix + name or assets.get("SHA256SUMS") != prefix + "SHA256SUMS": - raise InstallError("runtime_release_assets_missing") - checksums = temporary / "SHA256SUMS" - fetch(prefix + "SHA256SUMS", checksums, 1_000_000) - matches = [ - line.split()[0] - for line in checksums.read_text().splitlines() - if len(line.split()) == 2 and line.split()[1].lstrip("*") == name - ] - if len(matches) != 1: - raise InstallError("runtime_checksum_missing") - archive = temporary / name - fetch(prefix + name, archive) + archive, digest = download_asset(info, f"android-use-runtime-{target()}.zip", temporary) return activate( root, archive, - matches[0], + digest, expected_version=tag[1:], expected_current=installed.get("release"), ) @@ -496,22 +539,11 @@ def install_ocr(root, archive, digest): def download_ocr(root): version = metadata(root / "releases" / release_id(current_id(root)))["version"] - name = f"android-use-ocr-{target()}.zip" - prefix = f"https://github.com/{REPOSITORY}/releases/download/v{version}/" with tempfile.TemporaryDirectory(prefix="android-use-ocr-download-") as folder: folder = Path(folder) - sums = folder / "SHA256SUMS" - fetch(prefix + "SHA256SUMS", sums, 1_000_000) - matches = [ - line.split()[0] - for line in sums.read_text().splitlines() - if len(line.split()) == 2 and line.split()[1].lstrip("*") == name - ] - if len(matches) != 1: - raise InstallError("ocr_component_checksum_missing") - archive = folder / name - fetch(prefix + name, archive) - return install_ocr(root, archive, matches[0]) + info = release_info(folder, version) + archive, digest = download_asset(info, f"android-use-ocr-{target()}.zip", folder) + return install_ocr(root, archive, digest) def health(): diff --git a/tests/test_portable.py b/tests/test_portable.py index 0984593..8f3eca8 100644 --- a/tests/test_portable.py +++ b/tests/test_portable.py @@ -12,6 +12,11 @@ from android_use.installation import InstallError, probe +@pytest.fixture(autouse=True) +def isolated_download_credentials(monkeypatch): + monkeypatch.delenv("ANDROID_USE_GITHUB_TOKEN", raising=False) + + @pytest.fixture def bundle(tmp_path): if os.name == "nt": @@ -354,3 +359,95 @@ def test_cli_relative_install_root_returns_absolute_stable_config( result = json.loads(capsys.readouterr().out) assert Path(result["mcp_config"]["args"][0]).is_absolute() assert runtime.current_id(tmp_path / "relative root") == result["release"] + + +def test_private_asset_auth_is_scoped_and_removed_on_redirect(tmp_path, monkeypatch): + import httpx + + seen = [] + original = httpx.Client + monkeypatch.setenv("ANDROID_USE_GITHUB_TOKEN", "private-test-token") + + def transport(request): + seen.append((str(request.url), request.headers.get("Authorization"))) + if request.url.host == "api.github.com": + return httpx.Response( + 302, headers={"Location": "https://objects.githubusercontent.com/runtime.zip"} + ) + return httpx.Response(200, content=b"verified-by-caller") + + monkeypatch.setattr( + httpx, + "Client", + lambda **kwargs: original(transport=httpx.MockTransport(transport), **kwargs), + ) + output = tmp_path / "download" + runtime.fetch(f"https://api.github.com/repos/{runtime.REPOSITORY}/releases/assets/12", output) + assert seen[0][1] == "Bearer private-test-token" + assert seen[1][1] is None + assert output.read_bytes() == b"verified-by-caller" + + +def test_downloader_refuses_plain_http_redirect_and_size_overflow(tmp_path, monkeypatch): + import httpx + + original = httpx.Client + requests = [] + + def redirect(request): + requests.append(str(request.url)) + return httpx.Response(302, headers={"Location": "http://insecure.example/file"}) + + monkeypatch.setattr( + httpx, + "Client", + lambda **kwargs: original(transport=httpx.MockTransport(redirect), **kwargs), + ) + with pytest.raises(InstallError, match="requires_https"): + runtime.fetch("https://example.test/file", tmp_path / "file") + assert len(requests) == 1 + monkeypatch.setattr( + httpx, + "Client", + lambda **kwargs: original( + transport=httpx.MockTransport(lambda _: httpx.Response(200, content=b"too large")), + **kwargs, + ), + ) + with pytest.raises(InstallError, match="too_large"): + runtime.fetch("https://example.test/file", tmp_path / "file", limit=2) + + +def test_private_release_uses_validated_api_asset_endpoints(tmp_path, bundle, monkeypatch): + root = tmp_path / "install" + runtime.activate(root, *bundle()) + archive, digest = bundle("2.0.0") + monkeypatch.setenv("ANDROID_USE_GITHUB_TOKEN", "test-only") + name = f"android-use-runtime-{runtime.target()}.zip" + base = f"https://api.github.com/repos/{runtime.REPOSITORY}/releases/assets/" + prefix = f"https://github.com/{runtime.REPOSITORY}/releases/download/v2.0.0/" + info = { + "tag_name": "v2.0.0", + "assets": [ + { + "name": "SHA256SUMS", + "url": base + "1", + "browser_download_url": prefix + "SHA256SUMS", + }, + {"name": name, "url": base + "2", "browser_download_url": prefix + name}, + ], + } + requested = [] + + def fetch(url, destination, limit=runtime.MAX_DOWNLOAD): + requested.append(url) + if url.endswith("/latest"): + destination.write_text(json.dumps(info)) + elif url.endswith("/1"): + destination.write_text(digest + " " + name + "\n") + else: + destination.write_bytes(archive.read_bytes()) + + monkeypatch.setattr(runtime, "fetch", fetch) + assert runtime.checked_update(root)["version"] == "2.0.0" + assert requested[1:] == [base + "1", base + "2"] diff --git a/tests/test_runtime_build.py b/tests/test_runtime_build.py new file mode 100644 index 0000000..6459ac1 --- /dev/null +++ b/tests/test_runtime_build.py @@ -0,0 +1,50 @@ +import hashlib +import importlib.util +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +spec = importlib.util.spec_from_file_location("runtime_builder", ROOT / "scripts/build_runtime.py") +builder = importlib.util.module_from_spec(spec) +spec.loader.exec_module(builder) + + +def test_build_inputs_retry_partial_download_then_atomically_reuse_verified_cache( + tmp_path, monkeypatch +): + calls = [] + data = b"pinned-build-input" + item = { + "filename": "upstream.zip", + "url": "https://example.test/upstream.zip", + "sha256": hashlib.sha256(data).hexdigest(), + } + cached = tmp_path / item["filename"] + cached.write_bytes(b"older corrupt cache") + + def fetch(url, destination): + calls.append(url) + destination.write_bytes(b"partial" if len(calls) == 1 else data) + if len(calls) == 1: + raise OSError("interrupted read") + + monkeypatch.setattr(builder, "fetch", fetch) + monkeypatch.setattr(builder.time, "sleep", lambda _: None) + assert builder.locked_input(tmp_path, item).read_bytes() == data + assert builder.locked_input(tmp_path, item) == cached + assert len(calls) == 2 + assert list(tmp_path.iterdir()) == [cached] + + +def test_wrong_upstream_checksum_never_replaces_cached_input(tmp_path, monkeypatch): + cached = tmp_path / "upstream.zip" + cached.write_bytes(b"existing") + item = {"filename": cached.name, "url": "https://example.test/upstream.zip", "sha256": "0" * 64} + monkeypatch.setattr( + builder, "fetch", lambda _, destination: destination.write_bytes(b"untrusted") + ) + with pytest.raises(ValueError, match="checksum mismatch"): + builder.locked_input(tmp_path, item) + assert cached.read_bytes() == b"existing" + assert list(tmp_path.iterdir()) == [cached] From 35bcde8f378ed06231ea20c93319c3e0a195ae7b Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:24:58 +0800 Subject: [PATCH 05/13] build: audit runtime licenses and exclude optional copyleft modules --- .github/workflows/runtime.yml | 6 +- README.md | 2 + README.zh-CN.md | 2 + THIRD_PARTY_NOTICES.md | 2 + docs/license-audit.md | 49 + docs/licenses/LICENSE.bzip2.txt | 37 + docs/licenses/LICENSE.cpython-components.rst | 1134 +++++++++++++++++ docs/licenses/LICENSE.expat.txt | 21 + docs/licenses/LICENSE.gcc-gpl3.txt | 674 ++++++++++ .../LICENSE.gcc-runtime-exception.txt | 73 ++ docs/licenses/LICENSE.hacl.txt | 23 + docs/licenses/LICENSE.libffi.txt | 21 + docs/licenses/LICENSE.liblzma.txt | 13 + docs/licenses/LICENSE.libuuid.txt | 27 + docs/licenses/LICENSE.mpdecimal.txt | 24 + docs/licenses/LICENSE.ncurses.txt | 29 + docs/licenses/LICENSE.openssl-3.txt | 177 +++ docs/licenses/LICENSE.sqlite.txt | 23 + docs/licenses/LICENSE.uiautomator-server.txt | 20 + docs/licenses/LICENSE.zlib-ng.txt | 19 + docs/licenses/LICENSE.zlib.txt | 22 + docs/licenses/LICENSE.zstd.txt | 30 + docs/licenses/README.md | 5 + docs/licenses/sources.json | 87 ++ docs/standalone.md | 6 +- scripts/build_runtime.py | 70 +- scripts/runtime_licenses.py | 122 ++ skills/android-use/SKILL.md | 2 + tests/test_runtime_build.py | 62 + 29 files changed, 2743 insertions(+), 39 deletions(-) create mode 100644 docs/license-audit.md create mode 100644 docs/licenses/LICENSE.bzip2.txt create mode 100644 docs/licenses/LICENSE.cpython-components.rst create mode 100644 docs/licenses/LICENSE.expat.txt create mode 100644 docs/licenses/LICENSE.gcc-gpl3.txt create mode 100644 docs/licenses/LICENSE.gcc-runtime-exception.txt create mode 100644 docs/licenses/LICENSE.hacl.txt create mode 100644 docs/licenses/LICENSE.libffi.txt create mode 100644 docs/licenses/LICENSE.liblzma.txt create mode 100644 docs/licenses/LICENSE.libuuid.txt create mode 100644 docs/licenses/LICENSE.mpdecimal.txt create mode 100644 docs/licenses/LICENSE.ncurses.txt create mode 100644 docs/licenses/LICENSE.openssl-3.txt create mode 100644 docs/licenses/LICENSE.sqlite.txt create mode 100644 docs/licenses/LICENSE.uiautomator-server.txt create mode 100644 docs/licenses/LICENSE.zlib-ng.txt create mode 100644 docs/licenses/LICENSE.zlib.txt create mode 100644 docs/licenses/LICENSE.zstd.txt create mode 100644 docs/licenses/README.md create mode 100644 docs/licenses/sources.json create mode 100644 scripts/runtime_licenses.py diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index 801ae8d..e6d2dde 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -50,9 +50,11 @@ jobs: timeout-minutes: 30 steps: - uses: actions/checkout@v4 - - uses: astral-sh/setup-uv@v6 + - uses: actions/setup-python@v6 + id: build-python with: python-version: '3.13.7' + - uses: astral-sh/setup-uv@v6 - name: Prepare Windows compiler id: msys2 if: runner.os == 'Windows' @@ -73,7 +75,7 @@ jobs: with: name: standalone-build-inputs path: dist/runtime-build - - run: uv sync --frozen --python 3.13.7 + - run: uv sync --frozen --python "${{ steps.build-python.outputs.python-path }}" - run: uv pip install -r scripts/runtime-build-requirements.txt - name: Build native runtime and Dim plugin run: uv run --no-sync python scripts/build_runtime.py diff --git a/README.md b/README.md index 6b42d1d..72e82eb 100644 --- a/README.md +++ b/README.md @@ -304,6 +304,8 @@ Development comparisons include **18 source-level trials** and **12 live Agent / Multi-touch, arbitrary gesture paths, fine-grained text selection and custom-editor input fallbacks are not implemented. A matched UI condition proves that condition; the Agent must verify business outcomes. Control and preview run locally, and tool results are handled by your chosen client/model. +Android Use source is MIT; bundled runtime dependencies retain their own licenses. [License audit and package notices →](docs/license-audit.md) + ## Acknowledgements Thank you to [iPhone Use](https://github.com/zhongerxin/iPhone-use), its author and contributors for inspiring Android Use's phone-agent workflow, guided setup and live-screen experience. diff --git a/README.zh-CN.md b/README.zh-CN.md index ed6b44a..c0b2037 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -303,6 +303,8 @@ v0.5.0 通过 **277 项 Python 测试、17 项界面测试**。内置 OCR 目前 多指手势、任意轨迹、精细文本选区及自绘编辑器输入兜底尚未实现。UI 条件满足仅证明该条件,Agent 仍需验收业务结果。控制和预览运行于本机,工具结果由你选择的客户端与模型处理。 +Android Use 源码采用 MIT;运行包依赖保留各自协议。[协议审计与随包声明 →](docs/license-audit.md#中文) + ## 致谢 感谢 [iPhone Use](https://github.com/zhongerxin/iPhone-use) 的作者与贡献者,为 Android Use 在手机 Agent 交互、引导式安装和实时画面方面带来的启发。 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 930e47a..1db70de 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -2,6 +2,8 @@ Android Use source code is licensed under MIT. The bundled browser SDK and its dependencies retain their own licenses, reproduced below. Source installations obtain Python dependencies and ffmpeg separately. Standalone runtime archives include CPython, Python dependencies, Android Platform Tools and a minimal FFmpeg build; they retain their upstream licenses. Each runtime carries CPython and Python-package notices under `licenses/`, Android Platform Tools notices under `tools/adb/`, and the corresponding FFmpeg source archive plus exact configure options under `licenses/`. Native runtime inputs and SHA256 values are pinned in `scripts/runtime-inputs.json`. The optional macOS OCR component uses the system Vision framework and is distributed separately. +The standalone FFmpeg executable uses LGPL-2.1-or-later under the exact restricted build configuration. Its corresponding source, license and build options are inside the same runtime archive. Certifi's MPL-2.0 source form is included under `licenses/sources/certifi`. Original native/package notices and an inventory are included under `licenses/`; they are not replaced by this project's MIT license. See `docs/license-audit.md` for the build gate, exclusions and remaining scope. + ## @modelcontextprotocol/ext-apps@1.7.5 Declared license: MIT diff --git a/docs/license-audit.md b/docs/license-audit.md new file mode 100644 index 0000000..957ff79 --- /dev/null +++ b/docs/license-audit.md @@ -0,0 +1,49 @@ +# License audit — 2026-11-06 + +This review covers the Android Use source, dependency declarations, native-package construction and sampled build artifacts. The project remains **MIT**, with its existing copyright notice preserved. A native archive is not uniformly MIT: bundled dependencies retain their own terms. + +| Component | Observed terms | Packaging treatment | +| --- | --- | --- | +| Android Use | MIT | Preserve `LICENSE`, including existing author attribution. | +| [iPhone Use](https://github.com/zhongerxin/iPhone-use) | MIT in the referenced repository | Acknowledge the inspiration in both READMEs. This acknowledgement does not replace license/copyright retention if code is reused. | +| CPython | PSF and its bundled-component terms | Carry the actual interpreter's license and upstream component notices. Freeze from a modular interpreter so optional DBM/readline modules can be excluded. | +| Most declared Python packages | MIT, BSD, Apache or related permissive expressions | Copy installed package notices; record exact versions, declarations and native file hashes. The environment inventory can include build-only packages and is labelled as a superset. | +| certifi | MPL-2.0 | Include its unmodified Python source and CA data under `licenses/sources/certifi`, in addition to the MPL license. | +| PyInstaller | GPL with a bundling exception; some Apache files | The exception permits generated applications to use their own licenses, subject to dependency terms. It does not mean the PyInstaller tool itself is MIT. Preserve available upstream notices. [Upstream explanation](https://pyinstaller.org/en/stable/license.html). | +| FFmpeg | LGPL-2.1-or-later for this restricted configuration | Enforce the exact build flags; no GPL/nonfree/version3 or extra-library flags. Ship the corresponding unmodified tarball, LGPL text, configure record and empty changes diff with each native archive. [FFmpeg licensing](https://www.ffmpeg.org/legal.html). | +| ADB and runtime libraries | Per-component Android Platform Tools notices | Ship only ADB, required DLLs/lib64, notices and version metadata. Exclude fastboot and filesystem utilities rather than distributing the entire upstream tools directory. | +| Pillow and native image libraries | MIT-CMU plus the wheel's bundled-library terms | Preserve Pillow's full LICENSE, including FreeType/JPEG and other dependency notices; do not label all native image libraries MIT-CMU. | +| macOS OCR | Android Use code plus system Apple frameworks | The helper is optional. Apple system frameworks are used, not included in the archive. | + +## Findings addressed + +1. **A real build-interpreter issue:** the first local uv-managed Python exposed `_dbm` as a built-in module and reported GNU gdbm. Excluding a Python import cannot remove code already linked into the interpreter. New builds reject built-in `_dbm`, `_gdbm` and `readline`; CI uses `actions/setup-python` rather than assuming every uv-managed interpreter has the same redistribution footprint. PyInstaller excludes the optional DBM/readline/Tk modules and the native-file check rejects unexpected DBM/readline binaries. +2. **The whole Platform Tools ZIP was unnecessary:** it includes utilities outside Android Use's needs, with additional licensing considerations. The runtime now selects ADB and its runtime support files and retains the upstream notice. Original upstream build-input archives are not copied wholesale into the runtime. +3. **Package-level MIT metadata was insufficient:** certifi is MPL-2.0 and image/crypto wheels include native dependencies. Add source-form certifi files, original package notices, pinned native notices and a machine-readable inventory. +4. **FFmpeg flags could previously be a superset:** checking only required flags could allow an unexpected extra feature/license option in a supplied binary. The builder now requires an exact option set. FFmpeg is a separate executable; the program's Python code is not linked against libavcodec. The FFmpeg executable and its own static libraries remain covered by their applicable terms and corresponding source materials. + +## Evidence carried by each runtime + +- `licenses/CPython-LICENSE.txt`: from the interpreter actually used to build it. +- `licenses/native/`: upstream component notices and `sources.json` provenance/digests. Some notices are a superset of components used on a particular platform. Modified pinned notice text fails the build. +- `licenses/python/`: notices from installed Python distributions. +- `licenses/sources/certifi/`: unmodified source form and CA data. +- `licenses/FFmpeg-LGPL-2.1.txt`, `ffmpeg-8.0.tar.xz`, `ffmpeg-build.json`, `ffmpeg-changes.diff`. +- `licenses/inventory.json`: actual Python/OpenSSL versions, package metadata and native file hashes. It is an inventory, not a complete SPDX dependency graph. +- `tools/adb/NOTICE.txt`: upstream notices for Android Platform Tools, retained as supplied. + +The FFmpeg source is inside the same downloadable native archive as its binary. The package builder does not enable optional GPL libraries such as libx264. The small H.264 test fixture is encoded data, not a redistribution of the encoder executable. + +## Scope and remaining limits + +Metadata and filename checks alone cannot prove every statically linked component's provenance. The pinned notices and Python build gate reduce known risks; they are not a blanket legal certification for every OS, wheel and future dependency update. In particular, Windows distributions may contain Microsoft runtime DLLs with separate redistribution terms; the native inventory records their actual filenames. Those binaries are not reclassified as MIT or open source by this project. + +This PR does not publish a release. Keep the per-platform acceptance artifacts and inventory with the release review, and repeat the scan when the interpreter, wheels, compiler or FFmpeg configuration changes. The first pre-audit local artifacts are diagnostic evidence, not the release-approved packages. + +## 中文 + +项目源码仍采用 MIT,并保留原作者版权。**独立运行包不能整体称为 MIT**:FFmpeg 按当前配置适用 LGPL-2.1-or-later,certifi 采用 MPL-2.0,Python 和各原生库也保留自身条款。PyInstaller 有打包例外,不能仅看到 GPL 标签就推断应用必须改协议。 + +本轮发现首个构建 Python 内置 GNU gdbm;仅排除模块导入不能移除已静态链接的代码。因此增加构建门禁,改用可排除模块的 CPython,并检查原生文件。ADB 只带实际需要的文件,避免附带无关工具;certifi 源码、Python/原生库声明、FFmpeg 对应源码与精确编译选项一并随包提供。中英文 README 已感谢 iPhone Use 的启发;实际代码复用仍需要保留原许可证和版权,不能只用致谢替代。 + +审计按当前声明、构建和产物执行,不把元数据扫描等同于完整二进制溯源或法律认证。Windows 可能包含微软可再分发运行库,其条款单独适用。本次保持 PR 审阅,不发布新版本;后续更新基础环境或依赖时,应连同原生清单一起复查。 diff --git a/docs/licenses/LICENSE.bzip2.txt b/docs/licenses/LICENSE.bzip2.txt new file mode 100644 index 0000000..a5c4cdb --- /dev/null +++ b/docs/licenses/LICENSE.bzip2.txt @@ -0,0 +1,37 @@ +This program, "bzip2", the associated library "libbzip2", and all +documentation, are copyright (C) 1996-2010 Julian R Seward. All +rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product + documentation would be appreciated but is not required. + +3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + +4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Julian Seward, jseward@bzip.org +bzip2/libbzip2 version 1.0.6 of 6 September 2010 diff --git a/docs/licenses/LICENSE.cpython-components.rst b/docs/licenses/LICENSE.cpython-components.rst new file mode 100644 index 0000000..dd27e90 --- /dev/null +++ b/docs/licenses/LICENSE.cpython-components.rst @@ -0,0 +1,1134 @@ +.. highlight:: none + +.. _history-and-license: + +******************* +History and License +******************* + + +History of the software +======================= + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands as a +successor of a language called ABC. Guido remains Python's principal author, +although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for National +Research Initiatives (CNRI, see https://www.cnri.reston.va.us) in Reston, +Virginia where he released several versions of the software. + +In May 2000, Guido and the Python core development team moved to BeOpen.com to +form the BeOpen PythonLabs team. In October of the same year, the PythonLabs +team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization created +specifically to own Python-related Intellectual Property. Zope Corporation was a +sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org for the Open +Source Definition). Historically, most, but not all, Python releases have also +been GPL-compatible; the table below summarizes the various releases. + ++----------------+--------------+------------+------------+---------------------+ +| Release | Derived from | Year | Owner | GPL-compatible? (1) | ++================+==============+============+============+=====================+ +| 0.9.0 thru 1.2 | n/a | 1991-1995 | CWI | yes | ++----------------+--------------+------------+------------+---------------------+ +| 1.3 thru 1.5.2 | 1.2 | 1995-1999 | CNRI | yes | ++----------------+--------------+------------+------------+---------------------+ +| 1.6 | 1.5.2 | 2000 | CNRI | no | ++----------------+--------------+------------+------------+---------------------+ +| 2.0 | 1.6 | 2000 | BeOpen.com | no | ++----------------+--------------+------------+------------+---------------------+ +| 1.6.1 | 1.6 | 2001 | CNRI | yes (2) | ++----------------+--------------+------------+------------+---------------------+ +| 2.1 | 2.0+1.6.1 | 2001 | PSF | no | ++----------------+--------------+------------+------------+---------------------+ +| 2.0.1 | 2.0+1.6.1 | 2001 | PSF | yes | ++----------------+--------------+------------+------------+---------------------+ +| 2.1.1 | 2.1+2.0.1 | 2001 | PSF | yes | ++----------------+--------------+------------+------------+---------------------+ +| 2.1.2 | 2.1.1 | 2002 | PSF | yes | ++----------------+--------------+------------+------------+---------------------+ +| 2.1.3 | 2.1.2 | 2002 | PSF | yes | ++----------------+--------------+------------+------------+---------------------+ +| 2.2 and above | 2.1.1 | 2001-now | PSF | yes | ++----------------+--------------+------------+------------+---------------------+ + +.. note:: + + (1) GPL-compatible doesn't mean that we're distributing Python under the GPL. + All Python licenses, unlike the GPL, let you distribute a modified version + without making your changes open source. The GPL-compatible licenses make + it possible to combine Python with other software that is released under + the GPL; the others don't. + + (2) According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license + has a choice of law clause. According to CNRI, however, Stallman's lawyer has + told CNRI's lawyer that 1.6.1 is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's direction to +make these releases possible. + + +Terms and conditions for accessing or otherwise using Python +============================================================ + +Python software and documentation are licensed under the +Python Software Foundation License Version 2. + +Starting with Python 3.8.6, examples, recipes, and other code in +the documentation are dual licensed under the PSF License Version 2 +and the :ref:`Zero-Clause BSD license `. + +Some software incorporated into Python is under different licenses. +The licenses are listed with code falling under that license. +See :ref:`OtherLicenses` for an incomplete list of these licenses. + + +.. _PSF-license: + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +.. parsed-literal:: + + 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and + the Individual or Organization ("Licensee") accessing and otherwise using this + software ("Python") in source or binary form and its associated documentation. + + 2. Subject to the terms and conditions of this License Agreement, PSF hereby + grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, + analyze, test, perform and/or display publicly, prepare derivative works, + distribute, and otherwise use Python alone or in any derivative + version, provided, however, that PSF's License Agreement and PSF's notice of + copyright, i.e., "Copyright © 2001-2024 Python Software Foundation; All Rights + Reserved" are retained in Python alone or in any derivative version + prepared by Licensee. + + 3. In the event Licensee prepares a derivative work that is based on or + incorporates Python or any part thereof, and wants to make the + derivative work available to others as provided herein, then Licensee hereby + agrees to include in any such work a brief summary of the changes made to Python. + + 4. PSF is making Python available to Licensee on an "AS IS" basis. + PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF + EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR + WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE + USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + + 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON + FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF + MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE + THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + + 6. This License Agreement will automatically terminate upon a material breach of + its terms and conditions. + + 7. Nothing in this License Agreement shall be deemed to create any relationship + of agency, partnership, or joint venture between PSF and Licensee. This License + Agreement does not grant permission to use PSF trademarks or trade name in a + trademark sense to endorse or promote products or services of Licensee, or any + third party. + + 8. By copying, installing or otherwise using Python, Licensee agrees + to be bound by the terms and conditions of this License Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +.. parsed-literal:: + + 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at + 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization + ("Licensee") accessing and otherwise using this software in source or binary + form and its associated documentation ("the Software"). + + 2. Subject to the terms and conditions of this BeOpen Python License Agreement, + BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license + to reproduce, analyze, test, perform and/or display publicly, prepare derivative + works, distribute, and otherwise use the Software alone or in any derivative + version, provided, however, that the BeOpen Python License is retained in the + Software, alone or in any derivative version prepared by Licensee. + + 3. BeOpen is making the Software available to Licensee on an "AS IS" basis. + BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF + EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR + WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE + USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + + 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR + ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, + MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF + ADVISED OF THE POSSIBILITY THEREOF. + + 5. This License Agreement will automatically terminate upon a material breach of + its terms and conditions. + + 6. This License Agreement shall be governed by and interpreted in all respects + by the law of the State of California, excluding conflict of law provisions. + Nothing in this License Agreement shall be deemed to create any relationship of + agency, partnership, or joint venture between BeOpen and Licensee. This License + Agreement does not grant permission to use BeOpen trademarks or trade names in a + trademark sense to endorse or promote products or services of Licensee, or any + third party. As an exception, the "BeOpen Python" logos available at + http://www.pythonlabs.com/logos.html may be used according to the permissions + granted on that web page. + + 7. By copying, installing or otherwise using the software, Licensee agrees to be + bound by the terms and conditions of this License Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +.. parsed-literal:: + + 1. This LICENSE AGREEMENT is between the Corporation for National Research + Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 + ("CNRI"), and the Individual or Organization ("Licensee") accessing and + otherwise using Python 1.6.1 software in source or binary form and its + associated documentation. + + 2. Subject to the terms and conditions of this License Agreement, CNRI hereby + grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, + analyze, test, perform and/or display publicly, prepare derivative works, + distribute, and otherwise use Python 1.6.1 alone or in any derivative version, + provided, however, that CNRI's License Agreement and CNRI's notice of copyright, + i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All + Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version + prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, + Licensee may substitute the following text (omitting the quotes): "Python 1.6.1 + is made available subject to the terms and conditions in CNRI's License + Agreement. This Agreement together with Python 1.6.1 may be located on the + internet using the following unique, persistent identifier (known as a handle): + 1895.22/1013. This Agreement may also be obtained from a proxy server on the + internet using the following URL: http://hdl.handle.net/1895.22/1013". + + 3. In the event Licensee prepares a derivative work that is based on or + incorporates Python 1.6.1 or any part thereof, and wants to make the derivative + work available to others as provided herein, then Licensee hereby agrees to + include in any such work a brief summary of the changes made to Python 1.6.1. + + 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI + MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, + BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY + OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF + PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + + 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR + ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF + MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE + THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + + 6. This License Agreement will automatically terminate upon a material breach of + its terms and conditions. + + 7. This License Agreement shall be governed by the federal intellectual property + law of the United States, including without limitation the federal copyright + law, and, to the extent such U.S. federal law does not apply, by the law of the + Commonwealth of Virginia, excluding Virginia's conflict of law provisions. + Notwithstanding the foregoing, with regard to derivative works based on Python + 1.6.1 that incorporate non-separable material that was previously distributed + under the GNU General Public License (GPL), the law of the Commonwealth of + Virginia shall govern this License Agreement only as to issues arising under or + with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in + this License Agreement shall be deemed to create any relationship of agency, + partnership, or joint venture between CNRI and Licensee. This License Agreement + does not grant permission to use CNRI trademarks or trade name in a trademark + sense to endorse or promote products or services of Licensee, or any third + party. + + 8. By clicking on the "ACCEPT" button where indicated, or by copying, installing + or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and + conditions of this License Agreement. + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +.. parsed-literal:: + + Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The + Netherlands. All rights reserved. + + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee is hereby granted, provided that + the above copyright notice appear in all copies and that both that copyright + notice and this permission notice appear in supporting documentation, and that + the name of Stichting Mathematisch Centrum or CWI not be used in advertising or + publicity pertaining to distribution of the software without specific, written + prior permission. + + STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT + OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + SOFTWARE. + + +.. _BSD0: + +ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION +------------------------------------------------------------ + +.. parsed-literal:: + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + + +.. _OtherLicenses: + +Licenses and Acknowledgements for Incorporated Software +======================================================= + +This section is an incomplete, but growing list of licenses and acknowledgements +for third-party software incorporated in the Python distribution. + + +Mersenne Twister +---------------- + +The :mod:`!_random` C extension underlying the :mod:`random` module +includes code based on a download from +http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html. The following are +the verbatim comments from the original code:: + + A C-program for MT19937, with initialization improved 2002/1/26. + Coded by Takuji Nishimura and Makoto Matsumoto. + + Before using, initialize the state by using init_genrand(seed) + or init_by_array(init_key, key_length). + + Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. The names of its contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + + Any feedback is very welcome. + http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html + email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space) + + +Sockets +------- + +The :mod:`socket` module uses the functions, :c:func:`!getaddrinfo`, and +:c:func:`!getnameinfo`, which are coded in separate source files from the WIDE +Project, https://www.wide.ad.jp/. :: + + Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + 3. Neither the name of the project nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + +Asynchronous socket services +---------------------------- + +The :mod:`!test.support.asynchat` and :mod:`!test.support.asyncore` +modules contain the following notice:: + + Copyright 1996 by Sam Rushing + + All Rights Reserved + + Permission to use, copy, modify, and distribute this software and + its documentation for any purpose and without fee is hereby + granted, provided that the above copyright notice appear in all + copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of Sam + Rushing not be used in advertising or publicity pertaining to + distribution of the software without specific, written prior + permission. + + SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN + NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR + CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, + NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + +Cookie management +----------------- + +The :mod:`http.cookies` module contains the following notice:: + + Copyright 2000 by Timothy O'Malley + + All Rights Reserved + + Permission to use, copy, modify, and distribute this software + and its documentation for any purpose and without fee is hereby + granted, provided that the above copyright notice appear in all + copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Timothy O'Malley not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR + ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + + +Execution tracing +----------------- + +The :mod:`trace` module contains the following notice:: + + portions copyright 2001, Autonomous Zones Industries, Inc., all rights... + err... reserved and offered to the public under the terms of the + Python 2.2 license. + Author: Zooko O'Whielacronx + http://zooko.com/ + mailto:zooko@zooko.com + + Copyright 2000, Mojam Media, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1999, Bioreason, Inc., all rights reserved. + Author: Andrew Dalke + + Copyright 1995-1997, Automatrix, Inc., all rights reserved. + Author: Skip Montanaro + + Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved. + + + Permission to use, copy, modify, and distribute this Python software and + its associated documentation for any purpose without fee is hereby + granted, provided that the above copyright notice appears in all copies, + and that both that copyright notice and this permission notice appear in + supporting documentation, and that the name of neither Automatrix, + Bioreason or Mojam Media be used in advertising or publicity pertaining to + distribution of the software without specific, written prior permission. + + +UUencode and UUdecode functions +------------------------------- + +The ``uu`` codec contains the following notice:: + + Copyright 1994 by Lance Ellinghouse + Cathedral City, California Republic, United States of America. + All Rights Reserved + Permission to use, copy, modify, and distribute this software and its + documentation for any purpose and without fee is hereby granted, + provided that the above copyright notice appear in all copies and that + both that copyright notice and this permission notice appear in + supporting documentation, and that the name of Lance Ellinghouse + not be used in advertising or publicity pertaining to distribution + of the software without specific, written prior permission. + LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO + THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE + FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + + Modified by Jack Jansen, CWI, July 1995: + - Use binascii module to do the actual line-by-line conversion + between ascii and binary. This results in a 1000-fold speedup. The C + version is still 5 times faster, though. + - Arguments more compliant with Python standard + + +XML Remote Procedure Calls +-------------------------- + +The :mod:`xmlrpc.client` module contains the following notice:: + + The XML-RPC client interface is + + Copyright (c) 1999-2002 by Secret Labs AB + Copyright (c) 1999-2002 by Fredrik Lundh + + By obtaining, using, and/or copying this software and/or its + associated documentation, you agree that you have read, understood, + and will comply with the following terms and conditions: + + Permission to use, copy, modify, and distribute this software and + its associated documentation for any purpose and without fee is + hereby granted, provided that the above copyright notice appears in + all copies, and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + Secret Labs AB or the author not be used in advertising or publicity + pertaining to distribution of the software without specific, written + prior permission. + + SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD + TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- + ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR + BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY + DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + OF THIS SOFTWARE. + + +test_epoll +---------- + +The :mod:`!test.test_epoll` module contains the following notice:: + + Copyright (c) 2001-2006 Twisted Matrix Laboratories. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Select kqueue +------------- + +The :mod:`select` module contains the following notice for the kqueue +interface:: + + Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + +SipHash24 +--------- + +The file :file:`Python/pyhash.c` contains Marek Majkowski' implementation of +Dan Bernstein's SipHash24 algorithm. It contains the following note:: + + + Copyright (c) 2013 Marek Majkowski + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + + Original location: + https://github.com/majek/csiphash/ + + Solution inspired by code from: + Samuel Neves (supercop/crypto_auth/siphash24/little) + djb (supercop/crypto_auth/siphash24/little2) + Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c) + + +strtod and dtoa +--------------- + +The file :file:`Python/dtoa.c`, which supplies C functions dtoa and +strtod for conversion of C doubles to and from strings, is derived +from the file of the same name by David M. Gay, currently available +from https://web.archive.org/web/20220517033456/http://www.netlib.org/fp/dtoa.c. +The original file, as retrieved on March 16, 2009, contains the following +copyright and licensing notice:: + + /**************************************************************** + * + * The author of this software is David M. Gay. + * + * Copyright (c) 1991, 2000, 2001 by Lucent Technologies. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose without fee is hereby granted, provided that this entire notice + * is included in all copies of any software which is or includes a copy + * or modification of this software and in all copies of the supporting + * documentation for such software. + * + * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED + * WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY + * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY + * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. + * + ***************************************************************/ + + +OpenSSL +------- + +The modules :mod:`hashlib`, :mod:`posix` and :mod:`ssl` use +the OpenSSL library for added performance if made available by the +operating system. Additionally, the Windows and macOS installers for +Python may include a copy of the OpenSSL libraries, so we include a copy +of the OpenSSL license here. For the OpenSSL 3.0 release, +and later releases derived from that, the Apache License v2 applies:: + + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + +expat +----- + +The :mod:`pyexpat ` extension is built using an included copy of the expat +sources unless the build is configured ``--with-system-expat``:: + + Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd + and Clark Cooper + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +libffi +------ + +The :mod:`!_ctypes` C extension underlying the :mod:`ctypes` module +is built using an included copy of the libffi +sources unless the build is configured ``--with-system-libffi``:: + + Copyright (c) 1996-2008 Red Hat, Inc and others. + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + +zlib +---- + +The :mod:`zlib` extension is built using an included copy of the zlib +sources if the zlib version found on the system is too old to be +used for the build:: + + Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + +cfuhash +------- + +The implementation of the hash table used by the :mod:`tracemalloc` is based +on the cfuhash project:: + + Copyright (c) 2005 Don Owens + All rights reserved. + + This code is released under the BSD license: + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the author nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + OF THE POSSIBILITY OF SUCH DAMAGE. + + +libmpdec +-------- + +The :mod:`!_decimal` C extension underlying the :mod:`decimal` module +is built using an included copy of the libmpdec +library unless the build is configured ``--with-system-libmpdec``:: + + Copyright (c) 2008-2020 Stefan Krah. All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + +W3C C14N test suite +------------------- + +The C14N 2.0 test suite in the :mod:`test` package +(``Lib/test/xmltestdata/c14n-20/``) was retrieved from the W3C website at +https://www.w3.org/TR/xml-c14n2-testcases/ and is distributed under the +3-clause BSD license:: + + Copyright (c) 2013 W3C(R) (MIT, ERCIM, Keio, Beihang), + All Rights Reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of works must retain the original copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the original copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the W3C nor the names of its contributors may be + used to endorse or promote products derived from this work without + specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +.. _mimalloc-license: + +mimalloc +-------- + +MIT License:: + + Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + + +asyncio +---------- + +Parts of the :mod:`asyncio` module are incorporated from +`uvloop 0.16 `_, +which is distributed under the MIT license:: + + Copyright (c) 2015-2021 MagicStack Inc. http://magic.io + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +Global Unbounded Sequences (GUS) +-------------------------------- + +The file :file:`Python/qsbr.c` is adapted from FreeBSD's "Global Unbounded +Sequences" safe memory reclamation scheme in +`subr_smr.c `_. +The file is distributed under the 2-Clause BSD License:: + + Copyright (c) 2019,2020 Jeffrey Roberson + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + 1. Redistributions of source code must retain the above copyright + notice unmodified, this list of conditions, and the following + disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR + IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/licenses/LICENSE.expat.txt b/docs/licenses/LICENSE.expat.txt new file mode 100644 index 0000000..ce9e593 --- /dev/null +++ b/docs/licenses/LICENSE.expat.txt @@ -0,0 +1,21 @@ +Copyright (c) 1998-2000 Thai Open Source Software Center Ltd and Clark Cooper +Copyright (c) 2001-2022 Expat maintainers + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/docs/licenses/LICENSE.gcc-gpl3.txt b/docs/licenses/LICENSE.gcc-gpl3.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/docs/licenses/LICENSE.gcc-gpl3.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/licenses/LICENSE.gcc-runtime-exception.txt b/docs/licenses/LICENSE.gcc-runtime-exception.txt new file mode 100644 index 0000000..e1b3c69 --- /dev/null +++ b/docs/licenses/LICENSE.gcc-runtime-exception.txt @@ -0,0 +1,73 @@ +GCC RUNTIME LIBRARY EXCEPTION + +Version 3.1, 31 March 2009 + +Copyright (C) 2009 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +This GCC Runtime Library Exception ("Exception") is an additional +permission under section 7 of the GNU General Public License, version +3 ("GPLv3"). It applies to a given file (the "Runtime Library") that +bears a notice placed by the copyright holder of the file stating that +the file is governed by GPLv3 along with this Exception. + +When you use GCC to compile a program, GCC may combine portions of +certain GCC header files and runtime libraries with the compiled +program. The purpose of this Exception is to allow compilation of +non-GPL (including proprietary) programs to use, in this way, the +header files and runtime libraries covered by this Exception. + +0. Definitions. + +A file is an "Independent Module" if it either requires the Runtime +Library for execution after a Compilation Process, or makes use of an +interface provided by the Runtime Library, but is not otherwise based +on the Runtime Library. + +"GCC" means a version of the GNU Compiler Collection, with or without +modifications, governed by version 3 (or a specified later version) of +the GNU General Public License (GPL) with the option of using any +subsequent versions published by the FSF. + +"GPL-compatible Software" is software whose conditions of propagation, +modification and use would permit combination with GCC in accord with +the license of GCC. + +"Target Code" refers to output from any compiler for a real or virtual +target processor architecture, in executable form or suitable for +input to an assembler, loader, linker and/or execution +phase. Notwithstanding that, Target Code does not include data in any +format that is used as a compiler intermediate representation, or used +for producing a compiler intermediate representation. + +The "Compilation Process" transforms code entirely represented in +non-intermediate languages designed for human-written code, and/or in +Java Virtual Machine byte code, into Target Code. Thus, for example, +use of source code generators and preprocessors need not be considered +part of the Compilation Process, since the Compilation Process can be +understood as starting with the output of the generators or +preprocessors. + +A Compilation Process is "Eligible" if it is done using GCC, alone or +with other GPL-compatible software, or if it is done without using any +work based on GCC. For example, using non-GPL-compatible Software to +optimize any GCC intermediate representations would not qualify as an +Eligible Compilation Process. + +1. Grant of Additional Permission. + +You have permission to propagate a work of Target Code formed by +combining the Runtime Library with Independent Modules, even if such +propagation would otherwise violate the terms of GPLv3, provided that +all Target Code was generated by Eligible Compilation Processes. You +may then convey such a combination under terms of your choice, +consistent with the licensing of the Independent Modules. + +2. No Weakening of GCC Copyleft. + +The availability of this Exception does not imply any general +presumption that third-party software is unaffected by the copyleft +requirements of the license of GCC. + diff --git a/docs/licenses/LICENSE.hacl.txt b/docs/licenses/LICENSE.hacl.txt new file mode 100644 index 0000000..ffdc21a --- /dev/null +++ b/docs/licenses/LICENSE.hacl.txt @@ -0,0 +1,23 @@ +/* MIT License + * + * Copyright (c) 2016-2022 INRIA, CMU and Microsoft Corporation + * Copyright (c) 2022-2023 HACL* Contributors + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ diff --git a/docs/licenses/LICENSE.libffi.txt b/docs/licenses/LICENSE.libffi.txt new file mode 100644 index 0000000..acb2f7a --- /dev/null +++ b/docs/licenses/LICENSE.libffi.txt @@ -0,0 +1,21 @@ +libffi - Copyright (c) 1996-2019 Anthony Green, Red Hat, Inc and others. +See source files for details. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +``Software''), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/docs/licenses/LICENSE.liblzma.txt b/docs/licenses/LICENSE.liblzma.txt new file mode 100644 index 0000000..2d78851 --- /dev/null +++ b/docs/licenses/LICENSE.liblzma.txt @@ -0,0 +1,13 @@ +Copyright (C) The XZ Utils authors and contributors + +Permission to use, copy, modify, and/or distribute this +software for any purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL +WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL +THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR +CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, +NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/docs/licenses/LICENSE.libuuid.txt b/docs/licenses/LICENSE.libuuid.txt new file mode 100644 index 0000000..ec87a77 --- /dev/null +++ b/docs/licenses/LICENSE.libuuid.txt @@ -0,0 +1,27 @@ +Copyright (C) 1996, 1997 Theodore Ts'o. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, and the entire permission notice in its entirety, + including the disclaimer of warranties. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. The name of the author may not be used to endorse or promote + products derived from this software without specific prior + written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF +WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT +OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE +USE OF THIS SOFTWARE, EVEN IF NOT ADVISED OF THE POSSIBILITY OF SUCH +DAMAGE. diff --git a/docs/licenses/LICENSE.mpdecimal.txt b/docs/licenses/LICENSE.mpdecimal.txt new file mode 100644 index 0000000..c7688a9 --- /dev/null +++ b/docs/licenses/LICENSE.mpdecimal.txt @@ -0,0 +1,24 @@ +Copyright (c) 2008-2020 Stefan Krah. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/docs/licenses/LICENSE.ncurses.txt b/docs/licenses/LICENSE.ncurses.txt new file mode 100644 index 0000000..3a22975 --- /dev/null +++ b/docs/licenses/LICENSE.ncurses.txt @@ -0,0 +1,29 @@ +Copyright 2018-2020,2021 Thomas E. Dickey +Copyright 1998-2017,2018 Free Software Foundation, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, distribute with modifications, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR +THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name(s) of the above copyright +holders shall not be used in advertising or otherwise to promote the +sale, use or other dealings in this Software without prior written +authorization. + +-- vile:txtmode fc=72 +-- $Id: COPYING,v 1.10 2021/01/01 09:54:30 tom Exp $ diff --git a/docs/licenses/LICENSE.openssl-3.txt b/docs/licenses/LICENSE.openssl-3.txt new file mode 100644 index 0000000..49cc83d --- /dev/null +++ b/docs/licenses/LICENSE.openssl-3.txt @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/docs/licenses/LICENSE.sqlite.txt b/docs/licenses/LICENSE.sqlite.txt new file mode 100644 index 0000000..68b36eb --- /dev/null +++ b/docs/licenses/LICENSE.sqlite.txt @@ -0,0 +1,23 @@ +All of the code and documentation in SQLite has been dedicated to the public +domain by the authors. All code authors, and representatives of the companies +they work for, have signed affidavits dedicating their contributions to the +public domain and originals of those signed affidavits are stored in a firesafe +at the main offices of Hwaci. Anyone is free to copy, modify, publish, use, +compile, sell, or distribute the original SQLite code, either in source code form +or as a compiled binary, for any purpose, commercial or non-commercial, and by +any means. + +The previous paragraph applies to the deliverable code and documentation in +SQLite - those parts of the SQLite library that you actually bundle and ship +with a larger application. Some scripts used as part of the build process (for +example the "configure" scripts generated by autoconf) might fall under other +open-source licenses. Nothing from these build scripts ever reaches the final +deliverable SQLite library, however, and so the licenses associated with those +scripts should not be a factor in assessing your rights to copy and use the +SQLite library. + +All of the deliverable code in SQLite has been written from scratch. No code has +been taken from other projects or from the open internet. Every line of code can +be traced back to its original author, and all of those authors have public +domain dedications on file. So the SQLite code base is clean and is +uncontaminated with licensed code from other projects. diff --git a/docs/licenses/LICENSE.uiautomator-server.txt b/docs/licenses/LICENSE.uiautomator-server.txt new file mode 100644 index 0000000..9920fcc --- /dev/null +++ b/docs/licenses/LICENSE.uiautomator-server.txt @@ -0,0 +1,20 @@ +The MIT License (MIT) +Copyright (c) 2015 xiaocong@gmail.com + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/docs/licenses/LICENSE.zlib-ng.txt b/docs/licenses/LICENSE.zlib-ng.txt new file mode 100644 index 0000000..e866d7a --- /dev/null +++ b/docs/licenses/LICENSE.zlib-ng.txt @@ -0,0 +1,19 @@ +(C) 1995-2024 Jean-loup Gailly and Mark Adler + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + +3. This notice may not be removed or altered from any source distribution. diff --git a/docs/licenses/LICENSE.zlib.txt b/docs/licenses/LICENSE.zlib.txt new file mode 100644 index 0000000..b7a69d0 --- /dev/null +++ b/docs/licenses/LICENSE.zlib.txt @@ -0,0 +1,22 @@ +Copyright notice: + + (C) 1995-2026 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu diff --git a/docs/licenses/LICENSE.zstd.txt b/docs/licenses/LICENSE.zstd.txt new file mode 100644 index 0000000..7580028 --- /dev/null +++ b/docs/licenses/LICENSE.zstd.txt @@ -0,0 +1,30 @@ +BSD License + +For Zstandard software + +Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook, nor Meta, nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/licenses/README.md b/docs/licenses/README.md new file mode 100644 index 0000000..ca31653 --- /dev/null +++ b/docs/licenses/README.md @@ -0,0 +1,5 @@ +# Upstream native notices + +These files reproduce upstream license texts with source URLs and SHA256 values in `sources.json`. The HACL file contains the original leading license header from the referenced CPython source file. CPython's component-license document and the native notice set are a superset; inclusion here does not assert that every described library is in every platform's binary. + +The build copies these notices together with the actual interpreter/package licenses and a native-file inventory. FFmpeg's corresponding source and LGPL text come from its pinned upstream tarball. See [the audit](../license-audit.md) for findings, exclusions and limits. diff --git a/docs/licenses/sources.json b/docs/licenses/sources.json new file mode 100644 index 0000000..c23db3c --- /dev/null +++ b/docs/licenses/sources.json @@ -0,0 +1,87 @@ +[ + { + "file": "LICENSE.openssl-3.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.openssl-3.txt", + "sha256": "7d5450cb2d142651b8afa315b5f238efc805dad827d91ba367d8516bc9d49e7a" + }, + { + "file": "LICENSE.bzip2.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.bzip2.txt", + "sha256": "1f38bbc7caacafd65169276d759c0d88c991b753b643ce35d0e45ea1971dd441" + }, + { + "file": "LICENSE.expat.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.expat.txt", + "sha256": "122f2c27000472a201d337b9b31f7eb2b52d091b02857061a8880371612d9534" + }, + { + "file": "LICENSE.libffi.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.libffi.txt", + "sha256": "deaf3a42effb551a5b140fa9afefed183a27f1341c6d1bf430d106a5e6931fc0" + }, + { + "file": "LICENSE.liblzma.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.liblzma.txt", + "sha256": "9a4062de0a2c388a98cf35a35d348b62fa97c838a71c3c28ee1a2d7d0a565b02" + }, + { + "file": "LICENSE.libuuid.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.libuuid.txt", + "sha256": "122ee1f7e258f2c3c0e538a75c037684f420454bf3850ddc74ce750bbf5fe86b" + }, + { + "file": "LICENSE.mpdecimal.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.mpdecimal.txt", + "sha256": "669512af7219f58be03a398766d7c9da11a3b3df9d3f05cb74c5ceca25c8da3b" + }, + { + "file": "LICENSE.ncurses.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.ncurses.txt", + "sha256": "87a4c4442337b8968ef956031c406b74f9cb7149b7ba87311bdaba534816201c" + }, + { + "file": "LICENSE.sqlite.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.sqlite.txt", + "sha256": "38bef3d28b24f145ea293bd3b6eb4b20396982abc8303128fb493986ea5bc719" + }, + { + "file": "LICENSE.zlib.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.zlib.txt", + "sha256": "e32ff4e00d9d94930537635291da39e7e612703334bf6fde8c7f1686fe8a45a2" + }, + { + "file": "LICENSE.zlib-ng.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.zlib-ng.txt", + "sha256": "6c9f0d975b41afaa34d22f55bb8986ce69e5cb7ad327cb2b28820cd425edf5ee" + }, + { + "file": "LICENSE.zstd.txt", + "source": "https://github.com/astral-sh/python-build-standalone/blob/de549958c79576345140088bd5482d0b0f8a2614/LICENSE.zstd.txt", + "sha256": "7055266497633c9025b777c78eb7235af13922117480ed5c674677adc381c9d8" + }, + { + "file": "LICENSE.cpython-components.rst", + "source": "https://github.com/python/cpython/blob/v3.13.7/Doc/license.rst", + "sha256": "62f2c9c2c75d511170eb464ad5f83b78cc1f37eb2eb49c2846c9aa6c4557ee99" + }, + { + "file": "LICENSE.hacl.txt", + "source": "https://github.com/python/cpython/blob/v3.13.7/Modules/_hacl/Hacl_Hash_SHA2.c", + "sha256": "998ce04fb8ad9dedb0bc1b44938f8c3dcf1089780fa105ce1c8c30fb5554d78c" + }, + { + "file": "LICENSE.uiautomator-server.txt", + "source": "https://github.com/openatx/android-uiautomator-server/blob/master/LICENSE", + "sha256": "494e9ca2718c1b3242e2c6eb75a55ff0325b18b384c0d6551d16db1a21f07141" + }, + { + "file": "LICENSE.gcc-runtime-exception.txt", + "source": "https://github.com/gcc-mirror/gcc/blob/releases/gcc-15.2.0/COPYING.RUNTIME", + "sha256": "9d6b43ce4d8de0c878bf16b54d8e7a10d9bd42b75178153e3af6a815bdc90f74" + }, + { + "file": "LICENSE.gcc-gpl3.txt", + "source": "https://github.com/gcc-mirror/gcc/blob/releases/gcc-15.2.0/COPYING3", + "sha256": "8ceb4b9ee5adedde47b31e975c1d90c73ad27b6b165a1dcd80c7c545eb65b903" + } +] diff --git a/docs/standalone.md b/docs/standalone.md index f625d84..b696386 100644 --- a/docs/standalone.md +++ b/docs/standalone.md @@ -97,10 +97,10 @@ This downloads the matching release's `android-use-ocr-PLATFORM.zip`, checks its ## Build and acceptance -Build on the target OS with Python 3.13.7, uv, a C compiler, make and Bash; macOS additionally needs Swift for the optional component. Windows CI provisions a MinGW toolchain. End users do not need these build tools. +Build on the target OS with a modular CPython (CI uses 3.13.7 from actions/setup-python), uv, a C compiler, make and Bash; macOS additionally needs Swift for the optional component. Windows CI provisions a MinGW toolchain. End users do not need these build tools. ```bash -uv sync --frozen --python 3.13.7 +uv sync --frozen --python /absolute/path/to/modular/python3 uv pip install -r scripts/runtime-build-requirements.txt uv run --no-sync python scripts/build_runtime.py uv run --no-sync python scripts/build_runtime_upgrade_fixture.py @@ -111,7 +111,7 @@ uv run --no-sync python scripts/accept_runtime.py \ The upgrade fixture builds a distinct `+upgrade-test` version in a disposable source tree; it is never published. Native acceptance removes system Python/uv/ADB/ffmpeg from PATH, checks packaged tools and UI resources, retains a live MCP connection across install/rollback, deletes the original extraction, rejects corrupted/mismatched upgrades, preserves private settings, tests the frozen daemon dispatch and actual H.264-to-JPEG conversion. macOS also checks optional OCR installation and recognition. The lightweight plugin's first-install test stubs only download transport with local artifacts while checking production URLs; it is not a live GitHub release-download test. No phone or model calls are made. -Inputs are pinned in `scripts/runtime-inputs.json`. Archives carry Python/ADB notices and corresponding FFmpeg source/configuration. The legacy source/Codex package and its installer continue to work independently. [Recorded results and limits](validation.md). +Builds reject statically embedded optional DBM/readline modules and exclude their loadable versions. [License audit](license-audit.md). Inputs are pinned in `scripts/runtime-inputs.json`. Archives carry Python/ADB notices and corresponding FFmpeg source/configuration. The legacy source/Codex package and its installer continue to work independently. [Recorded results and limits](validation.md). ## 中文 diff --git a/scripts/build_runtime.py b/scripts/build_runtime.py index 4cec16c..901d444 100644 --- a/scripts/build_runtime.py +++ b/scripts/build_runtime.py @@ -5,8 +5,10 @@ import argparse import hashlib +import importlib.metadata import json import os +import shlex import shutil import subprocess import sys @@ -20,6 +22,8 @@ ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) +from runtime_licenses import EXCLUDED_MODULES, check_interpreter, collect # noqa: E402 + from android_use import __version__ # noqa: E402 from android_use.portable import fetch, target # noqa: E402 @@ -85,6 +89,8 @@ def archive_folder(folder, destination): def build(output, cache, ffmpeg_binary=None): from android_use.installation import probe + check_interpreter() + output.mkdir(parents=True, exist_ok=True) cache.mkdir(parents=True, exist_ok=True) lock = json.loads((ROOT / "scripts/runtime-inputs.json").read_text()) @@ -110,15 +116,18 @@ def build(output, cache, ffmpeg_binary=None): ], cwd=source, ) - run([shutil.which("make"), "-j4", "ffmpeg"], cwd=source) + run([shutil.which("make"), "-j4", "ffmpeg" + suffix], cwd=source) config = subprocess.run( [str(ffmpeg_binary), "-buildconf"], capture_output=True, text=True, check=True ) - configuration = (config.stdout + config.stderr).replace("'", "").replace('"', "") - if not all(flag in configuration for flag in CONFIGURE) or any( - flag in configuration for flag in ["--enable-gpl", "--enable-nonfree"] - ): - raise ValueError("FFmpeg must be built with the locked minimal configuration") + configurations = [ + line.split("configuration:", 1)[1].strip() + for line in (config.stdout + config.stderr).splitlines() + if "configuration:" in line + ] + configured = next((shlex.split(line) for line in configurations if line), []) + if set(configured) != set(CONFIGURE) or len(configured) != len(CONFIGURE): + raise ValueError("FFmpeg must use exactly the pinned minimal build flags") run( [ sys.executable, @@ -129,6 +138,7 @@ def build(output, cache, ffmpeg_binary=None): "--onedir", "--name", "android-use-runtime", + *[argument for module in EXCLUDED_MODULES for argument in ("--exclude-module", module)], "--distpath", work / "dist", "--workpath", @@ -156,7 +166,21 @@ def build(output, cache, ffmpeg_binary=None): shutil.copytree(work / "dist/android-use-runtime", bundle / "app", symlinks=False) with ZipFile(adb_zip) as archive: archive.extractall(work / "adb") - shutil.copytree(work / "adb/platform-tools", bundle / "tools/adb", dirs_exist_ok=True) + adb_source = work / "adb/platform-tools" + adb_destination = bundle / "tools/adb" + adb_destination.mkdir(parents=True) + for filename in ( + "adb", + "adb.exe", + "AdbWinApi.dll", + "AdbWinUsbApi.dll", + "NOTICE.txt", + "source.properties", + ): + if (adb_source / filename).is_file(): + shutil.copyfile(adb_source / filename, adb_destination / filename) + if (adb_source / "lib64").is_dir(): + shutil.copytree(adb_source / "lib64", adb_destination / "lib64") (bundle / "tools/adb" / ("adb" + suffix)).chmod(0o755) shutil.copyfile(ffmpeg_binary, bundle / "tools" / ("ffmpeg" + suffix)) (bundle / "tools" / ("ffmpeg" + suffix)).chmod(0o755) @@ -173,38 +197,16 @@ def build(output, cache, ffmpeg_binary=None): shutil.copyfile(ROOT / "LICENSE", component / "LICENSE") ocr_archive = output / f"android-use-ocr-{plat}.zip" archive_folder(component, ocr_archive) + collect(ROOT, bundle) licenses = bundle / "licenses" - licenses.mkdir() - for filename in ("LICENSE", "THIRD_PARTY_NOTICES.md"): - shutil.copyfile(ROOT / filename, licenses / filename) - # Carry corresponding FFmpeg source and exact configure options with the binary. shutil.copyfile(ffmpeg_source, licenses / ffmpeg_source.name) + with tarfile.open(ffmpeg_source) as archive: + license_text = archive.extractfile("ffmpeg-8.0/COPYING.LGPLv2.1").read() + (licenses / "FFmpeg-LGPL-2.1.txt").write_bytes(license_text) + (licenses / "ffmpeg-changes.diff").write_text("") (licenses / "ffmpeg-build.json").write_text( json.dumps({"source": lock["ffmpeg"], "configure": CONFIGURE}, indent=2) ) - import sysconfig - - python_license = Path(sysconfig.get_path("stdlib")) / "LICENSE.txt" - if not python_license.is_file(): - python_license = Path(sys.base_prefix) / "LICENSE.txt" - if not python_license.is_file(): - raise ValueError("CPython license missing from build interpreter") - shutil.copyfile(python_license, licenses / "CPython-LICENSE.txt") - # Include license metadata for every installed Python distribution in the build env. - import importlib.metadata - - for distribution in importlib.metadata.distributions(): - for file in distribution.files or []: - if any( - part.lower() - in {"licenses", "license", "license.txt", "copying", "notice", "notice.txt"} - for part in file.parts - ): - path = Path(distribution.locate_file(file)) - if path.is_file(): - destination = licenses / "python" / str(file) - destination.parent.mkdir(parents=True, exist_ok=True) - shutil.copyfile(path, destination) info = { "schema": 1, "version": __version__, diff --git a/scripts/runtime_licenses.py b/scripts/runtime_licenses.py new file mode 100644 index 0000000..2902f32 --- /dev/null +++ b/scripts/runtime_licenses.py @@ -0,0 +1,122 @@ +"""Collect redistributable notices/source and audit the actual frozen native files.""" + +import hashlib +import importlib.metadata +import json +import platform +import shutil +import ssl +import sys +import sysconfig +from pathlib import Path + +EXCLUDED_MODULES = ("_dbm", "_gdbm", "readline", "tkinter", "PIL.ImageTk") + + +def check_interpreter(): + forbidden = {"_dbm", "_gdbm", "readline"}.intersection(sys.builtin_module_names) + if forbidden: + raise ValueError( + "Build Python statically includes optional DBM/readline: " + + ", ".join(sorted(forbidden)) + + ". Use a modular CPython build; these modules must be excludable." + ) + + +def collect(root, bundle): + licenses = bundle / "licenses" + licenses.mkdir() + for filename in ("LICENSE", "THIRD_PARTY_NOTICES.md"): + shutil.copyfile(root / filename, licenses / filename) + vendor = root / "docs/licenses" + if not (vendor / "sources.json").is_file(): + raise ValueError("Pinned native dependency notices are missing") + sources = json.loads((vendor / "sources.json").read_text()) + (licenses / "native").mkdir() + for source in sources: + if Path(source["file"]).name != source["file"]: + raise ValueError("Invalid native notice filename") + if hashlib.sha256((vendor / source["file"]).read_bytes()).hexdigest() != source["sha256"]: + raise ValueError("A pinned dependency notice was modified") + shutil.copyfile(vendor / source["file"], licenses / "native" / source["file"]) + shutil.copyfile(vendor / "sources.json", licenses / "native/sources.json") + if (vendor / "README.md").is_file(): + shutil.copyfile(vendor / "README.md", licenses / "native/README.md") + python_license = Path(sysconfig.get_path("stdlib")) / "LICENSE.txt" + if not python_license.is_file(): + python_license = Path(sys.base_prefix) / "LICENSE.txt" + if not python_license.is_file(): + raise ValueError("CPython license missing from build interpreter") + shutil.copyfile(python_license, licenses / "CPython-LICENSE.txt") + packages = [] + for distribution in sorted( + importlib.metadata.distributions(), key=lambda d: d.metadata["Name"].lower() + ): + copied = [] + for file in distribution.files or []: + if any(part in {"..", "."} for part in file.parts) or file.is_absolute(): + continue + if any( + part.lower().startswith(("license", "copying", "notice", "copyright")) + for part in file.parts + ): + path = Path(distribution.locate_file(file)) + if path.is_file(): + destination = licenses / "python" / str(file) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(path, destination) + copied.append(str(destination.relative_to(bundle))) + packages.append( + { + "name": distribution.metadata["Name"], + "version": distribution.version, + "declared_license": distribution.metadata.get("License-Expression") + or distribution.metadata.get("License"), + "license_classifiers": [ + c + for c in distribution.metadata.get_all("Classifier", []) + if c.startswith("License") + ], + "notices": copied, + } + ) + # Certifi's MPL-2.0 applies at file level: carry its unmodified source form too. + certifi = importlib.metadata.distribution("certifi") + for file in certifi.files or []: + if file.parts[0] == "certifi" and str(file).endswith((".py", ".pem")): + source = Path(certifi.locate_file(file)) + destination = licenses / "sources" / str(file) + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + native_files = [] + for file in sorted(bundle.rglob("*")): + if file.is_file() and ( + file.suffix in {".dll", ".so", ".dylib", ".pyd", ".exe"} + or str(file.relative_to(bundle)) + in {"app/android-use-runtime", "tools/adb/adb", "tools/ffmpeg"} + ): + if any( + part in file.name.lower() + for part in ( + "libgdbm", + "readline", + "_gdbm", + "_dbm", + "fastboot", + "mke2fs", + "make_f2fs", + ) + ): + raise ValueError("Unexpected optional DBM/readline binary: " + file.name) + with file.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + native_files.append({"file": str(file.relative_to(bundle)), "sha256": digest}) + report = { + "scope": "Python build environment declarations (a superset of frozen imports), notices and native file hashes; not a complete binary provenance/legal certification", + "python": platform.python_version(), + "openssl": ssl.OPENSSL_VERSION, + "excluded_optional_modules": list(EXCLUDED_MODULES), + "packages": packages, + "native_files": native_files, + } + (licenses / "inventory.json").write_text(json.dumps(report, indent=2) + "\n") diff --git a/skills/android-use/SKILL.md b/skills/android-use/SKILL.md index 3f48da5..cdc82fb 100644 --- a/skills/android-use/SKILL.md +++ b/skills/android-use/SKILL.md @@ -41,4 +41,6 @@ aua_apps 查询已安装的第三方 **包名**,不支持按 App 显示名查 独立运行包的固定入口也支持 `cli <操作> ''`,使用安装返回的启动命令,将最后的 `auto-serve` 改为 `cli` 并追加操作及参数,无需 uv。回滚使用固定入口的 `rollback`;后台更新只影响后续 MCP 会话,不重启当前任务。 +独立运行包默认不带 macOS OCR;控件树不足时可由宿主 Agent 看图,确需自动离线识字时,用固定入口的 `install-ocr` 安装可选组件。`ocr_unavailable` 不意味着需要给用户安装 Swift/Xcode。Jev Box 视觉定位不是 OCR,截图上传仍需已有独立授权。 + MCP 不可用且使用源码安装时,使用同一仓库 CLI:`uv run --frozen --directory <仓库路径> android-use <操作> ''`。CLI 截图保存到 image_paths 中的本机绝对路径,使用图片查看工具实际查看。MCP 图片必须转发 image 块,不输出 base64。CLI 的每次运行是新 Runtime,不能跨进程传 observation_id。 diff --git a/tests/test_runtime_build.py b/tests/test_runtime_build.py index 6459ac1..4edb5e2 100644 --- a/tests/test_runtime_build.py +++ b/tests/test_runtime_build.py @@ -1,10 +1,12 @@ import hashlib import importlib.util +import sys from pathlib import Path import pytest ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) spec = importlib.util.spec_from_file_location("runtime_builder", ROOT / "scripts/build_runtime.py") builder = importlib.util.module_from_spec(spec) spec.loader.exec_module(builder) @@ -48,3 +50,63 @@ def test_wrong_upstream_checksum_never_replaces_cached_input(tmp_path, monkeypat builder.locked_input(tmp_path, item) assert cached.read_bytes() == b"existing" assert list(tmp_path.iterdir()) == [cached] + + +def test_statically_linked_optional_gpl_modules_are_rejected(monkeypatch): + import runtime_licenses + + monkeypatch.setattr(runtime_licenses.sys, "builtin_module_names", ("_dbm", "_ssl")) + with pytest.raises(ValueError, match="statically includes"): + runtime_licenses.check_interpreter() + monkeypatch.setattr(runtime_licenses.sys, "builtin_module_names", ("_ssl", "sys")) + runtime_licenses.check_interpreter() + + +def test_native_package_contains_original_notices_and_mpl_source_form(tmp_path): + import json + + import runtime_licenses + + bundle = tmp_path / "bundle" + (bundle / "app").mkdir(parents=True) + (bundle / "app/android-use-runtime").write_bytes(b"test-native-runtime") + runtime_licenses.collect(ROOT, bundle) + licenses = bundle / "licenses" + assert (licenses / "CPython-LICENSE.txt").is_file() + assert (licenses / "native/LICENSE.uiautomator-server.txt").is_file() + assert (licenses / "sources/certifi/core.py").is_file() + inventory = json.loads((licenses / "inventory.json").read_text()) + assert any( + p["name"].lower() == "certifi" and p["declared_license"] == "MPL-2.0" + for p in inventory["packages"] + ) + assert inventory["native_files"][0]["file"] == "app/android-use-runtime" + + +def test_unexpected_gdbm_native_binary_blocks_packaging(tmp_path): + import runtime_licenses + + bundle = tmp_path / "bundle" + (bundle / "app").mkdir(parents=True) + (bundle / "app/libgdbm.so").write_bytes(b"unexpected-native-library") + with pytest.raises(ValueError, match="DBM/readline binary"): + runtime_licenses.collect(ROOT, bundle) + + +def test_changed_upstream_notice_blocks_packaging(tmp_path): + import json + + import runtime_licenses + + root = tmp_path / "source" + (root / "docs/licenses").mkdir(parents=True) + (root / "LICENSE").write_text("Project license") + (root / "THIRD_PARTY_NOTICES.md").write_text("Notices") + (root / "docs/licenses/COPYING.txt").write_text("changed notice") + (root / "docs/licenses/sources.json").write_text( + json.dumps([{"file": "COPYING.txt", "sha256": "0" * 64}]) + ) + bundle = tmp_path / "bundle" + bundle.mkdir() + with pytest.raises(ValueError, match="notice was modified"): + runtime_licenses.collect(root, bundle) From 3723d92b01d14bacb6c0376eb73f303b1c93e99d Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:29:04 +0800 Subject: [PATCH 06/13] ci: avoid duplicate native matrices and preserve upstream license bytes --- .gitattributes | 2 ++ .github/workflows/runtime.yml | 8 ++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6fcce84 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Preserve upstream license bytes, including original whitespace, for provenance hashes. +docs/licenses/LICENSE.* -whitespace diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index e6d2dde..a7102b0 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -3,8 +3,6 @@ name: Standalone runtimes on: workflow_dispatch: workflow_call: - push: - branches: [codex/standalone-runtime] pull_request: paths: - 'src/android_use/portable.py' @@ -13,10 +11,16 @@ on: - 'scripts/*runtime*' - 'scripts/frozen_entry.py' - '.github/workflows/runtime.yml' + - 'docs/licenses/**' + - 'THIRD_PARTY_NOTICES.md' permissions: contents: read +concurrency: + group: standalone-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + jobs: inputs: runs-on: ubuntu-22.04 From 887227ac035f10faee449d9d0ccf6dda2de8363c Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:33:47 +0800 Subject: [PATCH 07/13] build: inventory native libraries without filename extensions --- scripts/runtime_licenses.py | 17 ++++++++++++++++- tests/test_runtime_build.py | 5 ++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/scripts/runtime_licenses.py b/scripts/runtime_licenses.py index 2902f32..687b80f 100644 --- a/scripts/runtime_licenses.py +++ b/scripts/runtime_licenses.py @@ -90,7 +90,22 @@ def collect(root, bundle): shutil.copyfile(source, destination) native_files = [] for file in sorted(bundle.rglob("*")): - if file.is_file() and ( + if not file.is_file(): + continue + with file.open("rb") as stream: + magic = stream.read(4) + executable_magic = magic.startswith(b"MZ") or magic in { + b"\x7fELF", + b"\xcf\xfa\xed\xfe", + b"\xfe\xed\xfa\xcf", + b"\xce\xfa\xed\xfe", + b"\xfe\xed\xfa\xce", + b"\xca\xfe\xba\xbe", + b"\xbe\xba\xfe\xca", + b"\xca\xfe\xba\xbf", + b"\xbf\xba\xfe\xca", + } + if executable_magic or ( file.suffix in {".dll", ".so", ".dylib", ".pyd", ".exe"} or str(file.relative_to(bundle)) in {"app/android-use-runtime", "tools/adb/adb", "tools/ffmpeg"} diff --git a/tests/test_runtime_build.py b/tests/test_runtime_build.py index 4edb5e2..e2d81f7 100644 --- a/tests/test_runtime_build.py +++ b/tests/test_runtime_build.py @@ -70,6 +70,7 @@ def test_native_package_contains_original_notices_and_mpl_source_form(tmp_path): bundle = tmp_path / "bundle" (bundle / "app").mkdir(parents=True) (bundle / "app/android-use-runtime").write_bytes(b"test-native-runtime") + (bundle / "app/Python").write_bytes(b"\xcf\xfa\xed\xfe" + b"test-framework-library") runtime_licenses.collect(ROOT, bundle) licenses = bundle / "licenses" assert (licenses / "CPython-LICENSE.txt").is_file() @@ -80,7 +81,9 @@ def test_native_package_contains_original_notices_and_mpl_source_form(tmp_path): p["name"].lower() == "certifi" and p["declared_license"] == "MPL-2.0" for p in inventory["packages"] ) - assert inventory["native_files"][0]["file"] == "app/android-use-runtime" + assert {"app/android-use-runtime", "app/Python"} <= { + item["file"] for item in inventory["native_files"] + } def test_unexpected_gdbm_native_binary_blocks_packaging(tmp_path): From fc9695e73da1292e465bebafa6ee562985af6a51 Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:44:09 +0800 Subject: [PATCH 08/13] fix: preserve pinned license hashes on Windows checkouts --- .gitattributes | 2 +- .github/workflows/runtime.yml | 1 + tests/test_runtime_build.py | 42 +++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index 6fcce84..b627ae5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,2 @@ # Preserve upstream license bytes, including original whitespace, for provenance hashes. -docs/licenses/LICENSE.* -whitespace +docs/licenses/LICENSE.* -text -whitespace diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index a7102b0..e5da28a 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -13,6 +13,7 @@ on: - '.github/workflows/runtime.yml' - 'docs/licenses/**' - 'THIRD_PARTY_NOTICES.md' + - '.gitattributes' permissions: contents: read diff --git a/tests/test_runtime_build.py b/tests/test_runtime_build.py index e2d81f7..2b1681c 100644 --- a/tests/test_runtime_build.py +++ b/tests/test_runtime_build.py @@ -113,3 +113,45 @@ def test_changed_upstream_notice_blocks_packaging(tmp_path): bundle.mkdir() with pytest.raises(ValueError, match="notice was modified"): runtime_licenses.collect(root, bundle) + + +def test_git_checkout_preserves_pinned_license_bytes_under_windows_line_endings(tmp_path): + import subprocess + + repository = tmp_path / "git checkout" + (repository / "docs/licenses").mkdir(parents=True) + hooks = repository / "empty-hooks" + hooks.mkdir() + original = b"upstream license\noriginal LF bytes\n" + notice = repository / "docs/licenses/LICENSE.fixture.txt" + notice.write_bytes(original) + (repository / ".gitattributes").write_bytes((ROOT / ".gitattributes").read_bytes()) + + def git(*args): + subprocess.run( + [ + "git", + "-C", + str(repository), + "-c", + "core.autocrlf=true", + "-c", + "core.hooksPath=" + str(hooks), + "-c", + "commit.gpgsign=false", + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + *args, + ], + check=True, + capture_output=True, + ) + + git("init") + git("add", ".") + git("commit", "-m", "Fixture") + notice.unlink() + git("checkout", "--", "docs/licenses/LICENSE.fixture.txt") + assert notice.read_bytes() == original From b9e71a19ddf9dc938e18f610394469dcf3b2defa Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:58:26 +0800 Subject: [PATCH 09/13] fix: decode bundled previews as UTF-8 and preserve generated license notices --- docs/third-party-introduction.md | 5 +++++ src/android_use/preview_daemon.py | 6 +++++- src/android_use/server.py | 4 +++- tests/test_mcp.py | 24 ++++++++++++++++++++++++ tests/test_settings_http.py | 22 ++++++++++++++++++++++ ui/build.mjs | 7 +++---- 6 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 docs/third-party-introduction.md diff --git a/docs/third-party-introduction.md b/docs/third-party-introduction.md new file mode 100644 index 0000000..cfee2e2 --- /dev/null +++ b/docs/third-party-introduction.md @@ -0,0 +1,5 @@ +# Third-party notices + +Android Use source code is licensed under MIT. The bundled browser SDK and its dependencies retain their own licenses, reproduced below. Source installations obtain Python dependencies and ffmpeg separately. Standalone runtime archives include CPython, Python dependencies, Android Platform Tools and a minimal FFmpeg build; they retain their upstream licenses. Each runtime carries CPython and Python-package notices under `licenses/`, Android Platform Tools notices under `tools/adb/`, and the corresponding FFmpeg source archive plus exact configure options under `licenses/`. Native runtime inputs and SHA256 values are pinned in `scripts/runtime-inputs.json`. The optional macOS OCR component uses the system Vision framework and is distributed separately. + +The standalone FFmpeg executable uses LGPL-2.1-or-later under the exact restricted build configuration. Its corresponding source, license and build options are inside the same runtime archive. Certifi's MPL-2.0 source form is included under `licenses/sources/certifi`. Original native/package notices and an inventory are included under `licenses/`; they are not replaced by this project's MIT license. See `docs/license-audit.md` for the build gate, exclusions and remaining scope. diff --git a/src/android_use/preview_daemon.py b/src/android_use/preview_daemon.py index 1985a90..9e02c2a 100644 --- a/src/android_use/preview_daemon.py +++ b/src/android_use/preview_daemon.py @@ -112,7 +112,11 @@ def _send(self, status, body, mime="application/json"): def do_GET(self): if not self._allowed() or self.path != prefix: return self._send(404, b"Not found", "text/plain") - html = files("android_use").joinpath("assets/phone-screen.html").read_text() + html = ( + files("android_use") + .joinpath("assets/phone-screen.html") + .read_text(encoding="utf-8") + ) html = html.replace( "", "" ) diff --git a/src/android_use/server.py b/src/android_use/server.py index 148e48b..4a69926 100644 --- a/src/android_use/server.py +++ b/src/android_use/server.py @@ -272,7 +272,9 @@ async def read_resource(uri): raise ValueError("Unknown screen resource") return [ ReadResourceContents( - content=files("android_use").joinpath("assets/phone-screen.html").read_text(), + content=files("android_use") + .joinpath("assets/phone-screen.html") + .read_text(encoding="utf-8"), mime_type="text/html;profile=mcp-app", meta=SCREEN_META, ) diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 0770101..6feb3a3 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -115,3 +115,27 @@ async def exercise(): assert absent.structuredContent["error"]["code"] == "device_selection_required" asyncio.run(exercise()) + + +def test_screen_resource_uses_utf8_with_windows_legacy_default(monkeypatch): + from importlib.resources import files + + from mcp.types import ReadResourceRequest, ReadResourceRequestParams + + from android_use import server + + raw = files("android_use").joinpath("assets/phone-screen.html").read_bytes() + + class LegacyDefault: + def joinpath(self, _): + return self + + def read_text(self, encoding="cp1252"): + return raw.decode(encoding) + + monkeypatch.setattr(server, "files", lambda _: LegacyDefault()) + request = ReadResourceRequest( + method="resources/read", params=ReadResourceRequestParams(uri=server.SCREEN_URI) + ) + result = asyncio.run(server.create_server().request_handlers[ReadResourceRequest](request)) + assert result.root.contents[0].text == raw.decode("utf-8") diff --git a/tests/test_settings_http.py b/tests/test_settings_http.py index c3f500f..377e27e 100644 --- a/tests/test_settings_http.py +++ b/tests/test_settings_http.py @@ -152,3 +152,25 @@ def test_stopped_preview_reuses_its_private_address_on_restart(preview_factory): assert second_url == first_url with httpx.Client(trust_env=False) as client: assert client.post(second_url + "api/status", json={}).json()["ok"] + + +def test_preview_html_uses_utf8_with_windows_legacy_default(preview, monkeypatch): + from importlib.resources import files + + raw = files("android_use").joinpath("assets/phone-screen.html").read_bytes() + + class LegacyDefault: + def joinpath(self, _): + return self + + def read_text(self, encoding="cp1252"): + return raw.decode(encoding) + + monkeypatch.setattr(preview_daemon, "files", lambda _: LegacyDefault()) + with httpx.Client(trust_env=False) as client: + reply = client.get(preview[0]) + assert reply.status_code == 200 + assert "Android Use" in reply.text and "__ANDROID_USE_STANDALONE__=true" in reply.text + assert reply.text == raw.decode("utf-8").replace( + "", "" + ) diff --git a/ui/build.mjs b/ui/build.mjs index 341d48b..b7c0b39 100644 --- a/ui/build.mjs +++ b/ui/build.mjs @@ -1,6 +1,6 @@ import { build } from 'esbuild'; import { readFile, writeFile, readdir } from 'node:fs/promises'; -import { dirname, join, resolve, sep } from 'node:path'; +import { dirname, join, resolve } from 'node:path'; const result = await build({entryPoints:['src/app.ts'],bundle:true,format:'esm',target:'es2022', minify:true,write:false,metafile:true,pure:['console.debug'],legalComments:'inline'}); const html = await readFile('index.html','utf8'); @@ -12,7 +12,7 @@ await writeFile('../src/android_use/assets/phone-screen.html',html // Preserve license texts for precisely the packages included in the browser bundle. const packages=new Map(); for(const input of Object.keys(result.metafile.inputs)){ - if(!input.includes(`node_modules${sep}`))continue; + if(!input.replaceAll('\\','/').includes('node_modules/'))continue; let directory=dirname(resolve(input)); while(directory!==dirname(directory)){ try{ @@ -22,8 +22,7 @@ for(const input of Object.keys(result.metafile.inputs)){ directory=dirname(directory); } } -const notices=['# Third-party notices','', - 'Android Use source code is licensed under MIT. The bundled browser SDK and its dependencies retain their own licenses, reproduced below. Python dependencies and ffmpeg are installed separately and retain their upstream licenses.','']; +const notices=[(await readFile('../docs/third-party-introduction.md','utf8')).trimEnd(),'']; for(const [name,{directory,pkg}] of [...packages.entries()].sort()){ notices.push(`## ${name}`,'',`Declared license: ${typeof pkg.license==='string'?pkg.license:JSON.stringify(pkg.license)}`,''); const licenseFiles=(await readdir(directory)).filter(name=>/^(licen[sc]e|notice|copying)([.\-_]|$)/i.test(name)).sort(); From 72415f219ba88f4fc254996c941f9a0711501ce6 Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:59:23 +0800 Subject: [PATCH 10/13] ci: validate native packages for runtime and dependency changes --- .github/workflows/runtime.yml | 9 ++++++--- docs/license-audit.md | 2 ++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index e5da28a..373608e 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -5,13 +5,16 @@ on: workflow_call: pull_request: paths: - - 'src/android_use/portable.py' - - 'src/android_use/screen.py' - - 'src/android_use/ocr.py' + - 'src/android_use/**' + - 'pyproject.toml' + - 'uv.lock' - 'scripts/*runtime*' - 'scripts/frozen_entry.py' - '.github/workflows/runtime.yml' - 'docs/licenses/**' + - 'docs/third-party-introduction.md' + - 'ui/build.mjs' + - 'tests/fixtures/runtime-sample.h264' - 'THIRD_PARTY_NOTICES.md' - '.gitattributes' diff --git a/docs/license-audit.md b/docs/license-audit.md index 957ff79..c1076aa 100644 --- a/docs/license-audit.md +++ b/docs/license-audit.md @@ -22,6 +22,8 @@ This review covers the Android Use source, dependency declarations, native-packa 3. **Package-level MIT metadata was insufficient:** certifi is MPL-2.0 and image/crypto wheels include native dependencies. Add source-form certifi files, original package notices, pinned native notices and a machine-readable inventory. 4. **FFmpeg flags could previously be a superset:** checking only required flags could allow an unexpected extra feature/license option in a supplied binary. The builder now requires an exact option set. FFmpeg is a separate executable; the program's Python code is not linked against libavcodec. The FFmpeg executable and its own static libraries remain covered by their applicable terms and corresponding source materials. +5. **Notice regeneration and checkout fidelity:** the browser build now reads the maintained native-distribution introduction instead of overwriting it with source-only text. Windows checkouts preserve pinned upstream license bytes rather than converting LF to CRLF; a real Git checkout regression verifies the SHA256 stays unchanged. + ## Evidence carried by each runtime - `licenses/CPython-LICENSE.txt`: from the interpreter actually used to build it. From 1ad951c54a836ca59fb8174f84b1c1c5f79335e9 Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:06:54 +0800 Subject: [PATCH 11/13] docs: make native runtime optional and attribute project to Archship --- .github/workflows/runtime.yml | 1 + LICENSE | 2 +- README.md | 27 ++++++++++++++++++++------- README.zh-CN.md | 24 ++++++++++++++++++------ docs/guide.md | 10 ++++++---- docs/guide.zh-CN.md | 11 +++++++---- docs/license-audit.md | 6 +++--- docs/standalone.md | 4 ++++ scripts/build_runtime.py | 4 ++-- skills/android-use/SKILL.md | 2 ++ 10 files changed, 64 insertions(+), 27 deletions(-) diff --git a/.github/workflows/runtime.yml b/.github/workflows/runtime.yml index 373608e..cb7e1ff 100644 --- a/.github/workflows/runtime.yml +++ b/.github/workflows/runtime.yml @@ -16,6 +16,7 @@ on: - 'ui/build.mjs' - 'tests/fixtures/runtime-sample.h264' - 'THIRD_PARTY_NOTICES.md' + - 'LICENSE' - '.gitattributes' permissions: diff --git a/LICENSE b/LICENSE index e828220..b1e2edc 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2026 JackCaow +Copyright (c) 2026 Archship Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 72e82eb..d531431 100644 --- a/README.md +++ b/README.md @@ -23,11 +23,22 @@ For workflows that need repeated UI decisions, enable **Jev**. Your Agent keeps **No root, Appium, signing setup, or keyboard APK.** The compiled UI is included. Use USB or already-authorized wireless ADB. -## Standalone runtime (new source feature) +## Choose an installation path + +**The standalone runtime is optional.** The Agent inspects the environment and chooses the appropriate route; a working installation is reused. + +| Environment | Installation choice | +| --- | --- | +| Existing healthy Android Use / MCP | Reuse it and verify the connection. | +| Python/uv, ADB and ffmpeg already available | Use the source installation and existing tools. | +| Dependencies missing, matching verified native assets available | Use the optional standalone runtime to avoid installing dependencies individually. | +| Offline, unsupported native target, or no native release assets yet | Use a suitable local archive or source setup; report any missing prerequisites. | + +### Optional standalone runtime (new source feature) **Python, ADB, ffmpeg, the screen UI and the control service in one native package.** The lightweight Dim plugin installs it automatically on first use. Later MCP connections start the installed version immediately and check for updates in the background; verified updates take effect on the next connection. Failed updates retain the previous version; rollback rechecks it before switching. -**macOS OCR is an optional add-on**, omitted from the default package. Tree interaction, Agent screenshot inspection and Jev can be used without it. Ordinary users do not need Python, uv, Git, Node.js, a JDK or Xcode tools; public-release bootstrap uses standard OS utilities. Private-release bootstrap additionally supports GitHub CLI with a private token; offline native installation avoids that requirement. +**macOS OCR is an optional add-on**, omitted from the default package. Tree interaction, Agent screenshot inspection and Jev can be used without it. Users choosing this package do not need Python, uv, Git, Node.js, a JDK or Xcode tools; public-release bootstrap uses standard OS utilities. Private-release bootstrap additionally supports GitHub CLI with a private token; offline native installation avoids that requirement. This is newer than the published v0.6.2 source-plugin ZIP. Use native workflow artifacts for offline trials until a release containing the runtime assets is published. [Install, automatic updates, optional OCR and rollback →](docs/standalone.md) @@ -47,9 +58,11 @@ https://github.com/arcships/android-use Read README.md, docs/guide.md and skills/android-use/SKILL.md. Reuse existing installations and preserve other MCP servers and uncommitted work. -Read docs/standalone.md. Prefer the matching standalone runtime/Dim plugin when -available; verify its release SHA256. For a source-install fallback, check Git, uv, -ADB and ffmpeg, then use scripts/install.py install --source . for a stable runtime. +Inspect Python/uv, ADB, ffmpeg, platform, network and available release assets. +Choose source installation or the optional standalone package for this environment; +do not migrate a healthy installation just to use a runtime. Read docs/standalone.md. +For source setup use scripts/install.py install --source .; for native setup verify +the matching archive SHA256. Both routes must return a stable MCP launch command. Register its returned mcp_config as Dim's local stdio server named android_use; use Dim's MCP management or dim mcp add. Check for duplicate registrations first. Discover devices, select my intended phone, call aua_setup(action="status"), @@ -63,7 +76,7 @@ and unlocking. Leave Jev disabled for now.
Manual Dim setup — stable MCP entry -Prefer the [standalone package](docs/standalone.md), which returns a stable `mcp_config` without requiring a user Python/uv installation. For the source fallback, prepare dependencies and [clone the repository](#or-install-manually), then run from its root: +Choose the source route when its dependencies are available, or the [optional standalone package](docs/standalone.md) when it better fits the environment. Both return a stable `mcp_config`. For source setup, prepare dependencies and [clone the repository](#or-install-manually), then run from its root: ```bash uv run --no-project --python 3.13 python scripts/install.py install --source . @@ -304,7 +317,7 @@ Development comparisons include **18 source-level trials** and **12 live Agent / Multi-touch, arbitrary gesture paths, fine-grained text selection and custom-editor input fallbacks are not implemented. A matched UI condition proves that condition; the Agent must verify business outcomes. Control and preview run locally, and tool results are handled by your chosen client/model. -Android Use source is MIT; bundled runtime dependencies retain their own licenses. [License audit and package notices →](docs/license-audit.md) +Android Use is maintained by **Archship** and its source is MIT; bundled runtime dependencies retain their own licenses. [License audit and package notices →](docs/license-audit.md) ## Acknowledgements diff --git a/README.zh-CN.md b/README.zh-CN.md index c0b2037..396fa0f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -23,11 +23,22 @@ Android Use 把你自己的 Android 手机或模拟器接入 **Dim Agent**,也 **无需 root、Appium、签名配置或键盘 APK。** 已包含编译好的界面,通过 USB 或已授权的无线 ADB 连接。 -## 独立运行包(新源码功能) +## 按环境选择安装方式 + +**独立 runtime 不是必需项。** Agent 先检查用户环境,再自主选择合适的安装方式;已有健康安装直接复用。 + +| 用户环境 | 安装选择 | +| --- | --- | +| 已有正常工作的 Android Use / MCP | 复用现有入口并验证连接。 | +| 已有 Python/uv、ADB 和 ffmpeg | 使用源码安装,复用现有依赖。 | +| 缺少依赖,且有匹配、可校验的原生发行包 | 可选独立 runtime,减少逐项安装依赖。 | +| 离线、不支持的原生平台或尚无原生发行资产 | 选择可用的本地包或源码安装,明确缺失条件。 | + +### 可选独立运行包(新源码功能) **Python、ADB、ffmpeg、实时界面和控制服务,打成一个原生运行包。** 轻量 Dim 插件首次自动安装;后续 MCP 连接立即使用已安装版本,并在后台检查更新。新包校验、握手通过后,下一次连接使用新版;失败保留旧版,回滚前也会重新验证。 -**macOS OCR 是可选组件,默认包不带。** 控件树操作、Agent 看图和 Jev 均可独立使用。普通用户无需准备 Python、uv、Git、Node.js、JDK 或 Xcode 工具,公开发行包首次下载只使用系统基础工具。私有发行包自动安装支持 GitHub CLI 与私有令牌,也可用原生离线包省去此依赖。 +**macOS OCR 是可选组件,默认包不带。** 控件树操作、Agent 看图和 Jev 均可独立使用。选择独立包的用户无需准备 Python、uv、Git、Node.js、JDK 或 Xcode 工具,公开发行包首次下载只使用系统基础工具。私有发行包自动安装支持 GitHub CLI 与私有令牌,也可用原生离线包省去此依赖。 此功能晚于已发布的 v0.6.2 源码插件 ZIP。正式 Release 尚未包含这些资产时,可用原生构建工作流产物离线体验。[安装、自动更新、可选 OCR 与回滚 →](docs/standalone.md#中文) @@ -47,8 +58,9 @@ https://github.com/arcships/android-use 先阅读 README.md、docs/guide.zh-CN.md 和 skills/android-use/SKILL.md。 复用已有安装,保留其他 MCP 服务和未提交改动。 -先读 docs/standalone.md,有对应原生包时优先使用独立运行包或轻量 Dim 插件,校验发行 SHA256。 -只有回退源码安装时,才检查 Git、uv、ADB、ffmpeg,并用 scripts/install.py install --source . 创建固定入口。 +检查 Python/uv、ADB、ffmpeg、系统架构、网络与可用发行资产,自主选择源码安装或可选独立包。 +不要为了使用 runtime 迁移已有健康安装,先读 docs/standalone.md。 +源码方式用 scripts/install.py install --source .;独立包核对平台与发行 SHA256,均使用返回的固定入口。 把返回的 mcp_config 注册为 Dim 的本地 stdio MCP,名称 android_use; 使用 Dim 的 MCP 管理或 dim mcp add,先检查已有注册,避免重复配置。 发现设备,明确选择我的目标手机,先调用 aua_setup(action="status"), @@ -61,7 +73,7 @@ https://github.com/arcships/android-use
手动配置 Dim:使用固定 MCP 入口 -优先使用[独立运行包](docs/standalone.md#中文),它会返回固定 `mcp_config`,无需用户安装 Python/uv。回退源码安装时,准备依赖并[克隆仓库](#或者手动安装),在仓库根目录执行: +已有依赖可使用源码方式;缺少依赖时,可按环境选择[独立运行包](docs/standalone.md#中文)。两种方式均返回固定 `mcp_config`。选择源码方式时,准备依赖并[克隆仓库](#或者手动安装),在仓库根目录执行: ```bash uv run --no-project --python 3.13 python scripts/install.py install --source . @@ -303,7 +315,7 @@ v0.5.0 通过 **277 项 Python 测试、17 项界面测试**。内置 OCR 目前 多指手势、任意轨迹、精细文本选区及自绘编辑器输入兜底尚未实现。UI 条件满足仅证明该条件,Agent 仍需验收业务结果。控制和预览运行于本机,工具结果由你选择的客户端与模型处理。 -Android Use 源码采用 MIT;运行包依赖保留各自协议。[协议审计与随包声明 →](docs/license-audit.md#中文) +Android Use 由 **Archship** 维护,源码采用 MIT;运行包依赖保留各自协议。[协议审计与随包声明 →](docs/license-audit.md#中文) ## 致谢 diff --git a/docs/guide.md b/docs/guide.md index a11c138..61d1990 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -2,7 +2,7 @@ Optional feature in v0.4.0: [optional Jev decision integration and comparison](jev.md). Default off; original tools remain compatible. Included in the v0.4.0 release ZIP. -v0.5.1 includes [read-only automatic OCR and execution guards](jev.md#automatic-read-only-ocr), plus automatic preview recovery. v0.5.2 adds [stable preview endpoints and frame-confirmed reconnection](preview-reconnection.md). v0.6.0 adds the [keyless host decider and opt-in Jev Box visual location](jev.md#no-key-host-decider). v0.6.1 returns `ambiguous` with tree candidates when a Box spans several text labels. Built-in OCR requires macOS and Xcode Command Line Tools. +v0.5.1 includes [read-only automatic OCR and execution guards](jev.md#automatic-read-only-ocr), plus automatic preview recovery. v0.5.2 adds [stable preview endpoints and frame-confirmed reconnection](preview-reconnection.md). v0.6.0 adds the [keyless host decider and opt-in Jev Box visual location](jev.md#no-key-host-decider). v0.6.1 returns `ambiguous` with tree candidates when a Box spans several text labels. Source-mode local OCR requires macOS and Xcode Command Line Tools; the optional standalone package uses a separately installed precompiled OCR component. **English** · [简体中文](guide.zh-CN.md) · [Project home](../README.md) @@ -25,8 +25,8 @@ The process running the server must have ADB access to the device. A cloud agent Use the [copyable installation prompt](../README.md#let-your-agent-install-it) with an agent that has local terminal access. The agent should perform these steps: -1. Inspect the host, repository, installed tools, and existing MCP/plugin config. Reuse suitable installations; preserve uncommitted work and unrelated server entries. Install missing Git, uv, ADB, ffmpeg, and Python from official sources. Codex CLI is needed only for the Codex routes. -2. Clone or reuse the repository. Run `uv sync --frozen --python 3.13` in its root. Node.js is not required for normal use. +1. Inspect the host, installed tools and existing MCP/plugin config. Reuse a healthy installation; preserve uncommitted work and unrelated server entries. **Runtime is optional:** choose source setup or a verified matching native package based on dependencies, platform, network and asset availability. See [installation choices](../README.md#choose-an-installation-path). +2. For source setup, clone/reuse the repository, prepare missing Git, uv, ADB, ffmpeg and Python from official sources, then run `uv sync --frozen --python 3.13`. Codex CLI is needed only for the Codex routes. For native setup, follow [standalone installation](standalone.md), without installing these bundled dependencies separately. Node.js is not required for normal use. 3. Configure the current client. For Codex, use the stable installer and diagnose conflicts before migrating an existing registration. For other clients, configure the local stdio command directly. Check existing registrations before changing them. 4. Discover ADB devices. Reuse the user's intended target, or select a clearly identifiable unique device. Ask which device to use when the target is ambiguous. The user handles USB trust, unlocking, and system permission prompts. 5. Save the chosen serial with `setup configure`, check service status, and reuse a healthy service. If absent, start it once. Diagnose errors rather than repeatedly reinstalling or restarting. @@ -38,7 +38,9 @@ Installation authorizes setup and read-screen acceptance. Wait for a concrete ph ## Installation -### Dependencies +### Source installation dependencies + +These apply to the source route. The [optional standalone package](standalone.md) bundles its own runtime dependencies; the Agent can choose either route for the environment. | Dependency | Purpose | | --- | --- | diff --git a/docs/guide.zh-CN.md b/docs/guide.zh-CN.md index a3fa29c..9b3ccfb 100644 --- a/docs/guide.zh-CN.md +++ b/docs/guide.zh-CN.md @@ -33,8 +33,9 @@ https://github.com/arcships/android-use 先阅读 README.md、docs/guide.zh-CN.md 和 skills/android-use/SKILL.md,然后实际完成安装与验收。 检查当前系统、已有仓库、插件和依赖;复用现有安装,只补齐缺项,不覆盖未提交修改。 -从官方来源安装缺失的 Git、uv、Python 3.11+、ADB、ffmpeg 和所需的 Codex CLI。 -克隆或复用仓库,安装锁定依赖,生成 dist/android-use,再注册本地市场并安装插件。 +独立 runtime 可选:根据已有依赖、平台、网络和发行资产自主选择源码或独立包,不强制迁移健康安装。 +源码方式才从官方来源补齐 Git、uv、Python 3.11+、ADB、ffmpeg 和所需的 Codex CLI;独立包见 docs/standalone.md。 +按所选方式安装并配置当前客户端;Codex 源码插件才需要打包、市场注册与插件安装。 检查 ADB 设备,只有一个明确目标时直接配置;目标不明确时让我选择。 复用健康控制服务,缺少服务时启动一次,完成 READY 验证并打开实时手机屏幕。 如果当前聊天还没加载新工具,先用仓库 CLI 完成可执行的配置和验收,并说明如何在新聊天使用插件。 @@ -45,7 +46,7 @@ https://github.com/arcships/android-use ### Agent 的执行顺序 -1. **检查并复用环境。** 检查 `git`、`uv`、`adb`、`ffmpeg` 和 `codex`,按本机系统补齐缺失依赖。Python 推荐使用下方已验证的 3.13;普通安装无需 Node.js。仓库已存在时先检查状态,保留用户未提交内容。 +1. **检查并选择安装方式。** 先复用健康安装,检查依赖、平台、网络和可用发行资产,自主选择源码或可选独立 runtime。已有依赖可继续源码;缺少依赖且有匹配原生包时可用独立包,不强制迁移。独立包按 [standalone.md](standalone.md#中文) 操作;下方第 2–3 步是源码 Codex 路径。仓库已存在时先检查状态,保留用户未提交内容。 2. **检查升级配置。** 执行 `uv run --no-project --python 3.13 python scripts/install.py doctor`,识别同名 MCP、重复插件、项目覆盖和已失效路径。 3. **安装并核对插件。** 执行 `uv run --no-project --python 3.13 python scripts/install.py install --source . --codex`。已有注册需要显式加 `--migrate-codex`;安装器先准备独立运行时并验证真实 MCP 握手,再切换固定入口和注册 `android-use@android-use-managed`,保留其他服务与设备/Jev 设置。 @@ -66,7 +67,9 @@ https://github.com/arcships/android-use ## 安装 -### 1. 准备依赖 +### 1. 准备源码安装依赖 + +下表适用于源码方式;[可选独立运行包](standalone.md#中文)已包含对应运行依赖。由 Agent 根据用户环境选择,无需两套都安装。 | 依赖 | 用途 | | --- | --- | diff --git a/docs/license-audit.md b/docs/license-audit.md index c1076aa..a4c2a49 100644 --- a/docs/license-audit.md +++ b/docs/license-audit.md @@ -1,10 +1,10 @@ # License audit — 2026-11-06 -This review covers the Android Use source, dependency declarations, native-package construction and sampled build artifacts. The project remains **MIT**, with its existing copyright notice preserved. A native archive is not uniformly MIT: bundled dependencies retain their own terms. +This review covers the Android Use source, dependency declarations, native-package construction and sampled build artifacts. The project remains **MIT**, with the project copyright attributed to **Archship**. A native archive is not uniformly MIT: bundled dependencies retain their own terms. | Component | Observed terms | Packaging treatment | | --- | --- | --- | -| Android Use | MIT | Preserve `LICENSE`, including existing author attribution. | +| Android Use | MIT | Ship `LICENSE` with the Archship project copyright notice. | | [iPhone Use](https://github.com/zhongerxin/iPhone-use) | MIT in the referenced repository | Acknowledge the inspiration in both READMEs. This acknowledgement does not replace license/copyright retention if code is reused. | | CPython | PSF and its bundled-component terms | Carry the actual interpreter's license and upstream component notices. Freeze from a modular interpreter so optional DBM/readline modules can be excluded. | | Most declared Python packages | MIT, BSD, Apache or related permissive expressions | Copy installed package notices; record exact versions, declarations and native file hashes. The environment inventory can include build-only packages and is labelled as a superset. | @@ -44,7 +44,7 @@ This PR does not publish a release. Keep the per-platform acceptance artifacts a ## 中文 -项目源码仍采用 MIT,并保留原作者版权。**独立运行包不能整体称为 MIT**:FFmpeg 按当前配置适用 LGPL-2.1-or-later,certifi 采用 MPL-2.0,Python 和各原生库也保留自身条款。PyInstaller 有打包例外,不能仅看到 GPL 标签就推断应用必须改协议。 +项目源码仍采用 MIT,项目版权归属为 **Archship**。**独立运行包不能整体称为 MIT**:FFmpeg 按当前配置适用 LGPL-2.1-or-later,certifi 采用 MPL-2.0,Python 和各原生库也保留自身条款。PyInstaller 有打包例外,不能仅看到 GPL 标签就推断应用必须改协议。 本轮发现首个构建 Python 内置 GNU gdbm;仅排除模块导入不能移除已静态链接的代码。因此增加构建门禁,改用可排除模块的 CPython,并检查原生文件。ADB 只带实际需要的文件,避免附带无关工具;certifi 源码、Python/原生库声明、FFmpeg 对应源码与精确编译选项一并随包提供。中英文 README 已感谢 iPhone Use 的启发;实际代码复用仍需要保留原许可证和版权,不能只用致谢替代。 diff --git a/docs/standalone.md b/docs/standalone.md index b696386..c009e9f 100644 --- a/docs/standalone.md +++ b/docs/standalone.md @@ -2,6 +2,8 @@ **Source feature after v0.6.2.** Historical v0.6.2 source-plugin ZIPs do not contain this runtime. The **Standalone runtimes** workflow builds native archives and lightweight Dim plugins; tagged releases publish those artifacts only after their acceptance checks pass. Before a release containing these assets exists, use the workflow artifacts for offline installation. The lightweight plugin's production download URL cannot provision a runtime from an older release that lacks it. +**Optional installation route.** Android Use does not require this runtime. The Agent first reuses a healthy installation, then checks existing Python/uv, ADB, ffmpeg, platform, network and available assets. Use source setup when it fits the host; choose a verified native package when it saves dependency setup. Do not migrate a working source installation solely to use the runtime. Only selecting the lightweight native plugin opts into its runtime bootstrap. + ## What's included | Component | Default runtime | @@ -115,6 +117,8 @@ Builds reject statically embedded optional DBM/readline modules and exclude thei ## 中文 +**runtime 是可选安装方式,不是使用 Android Use 的前提。** Agent 先复用健康安装,再检查 Python/uv、ADB、ffmpeg、平台、网络和发行包可用性,自主选择源码或独立包;不因提供了 runtime 就迁移已有正常环境。仅选择轻量原生插件时,才使用它的运行包自动安装流程。 + 这是 v0.6.2 之后的新源码功能,旧 v0.6.2 插件包不包含独立运行时。跨平台工作流生成原生运行包、轻量 Dim 插件与 SHA256;正式发布需要对应 Release 中实际有这些资产,不能把旧 ZIP 当成新包。发布前可使用工作流产物离线安装。 默认包内置 Python、Python 依赖、ADB、ffmpeg、界面和控制 JAR,普通用户无需 Git、uv、Node.js 或 JDK。**macOS OCR 不默认携带**,需要本地识字时用固定入口的 `install-ocr` 安装可选组件,安装后也不需要 Xcode/Swift。未安装时明确返回不可用,不悄悄编译。Jev 决策和视觉定位不等同于 OCR;树缺失页面的自动离线文字提取仍需此组件。 diff --git a/scripts/build_runtime.py b/scripts/build_runtime.py index 901d444..6b77c28 100644 --- a/scripts/build_runtime.py +++ b/scripts/build_runtime.py @@ -229,7 +229,7 @@ def build(output, cache, ffmpeg_binary=None): shutil.copytree(ROOT / "skills", plugin / "skills") shutil.copyfile(ROOT / "LICENSE", plugin / "LICENSE") (plugin / "README.md").write_text( - "# Android Use for Dim Agent\n\nThis lightweight plugin automatically installs a standalone runtime on first use.\nPython, ADB, ffmpeg and the screen UI are included in that runtime.\n\nDocumentation: https://github.com/arcships/android-use#quick-start\n" + "# Android Use for Dim Agent\n\nThis optional native plugin installs a standalone runtime on first use. Agents may instead reuse an existing installation or select source setup for the host environment.\nPython, ADB, ffmpeg and the screen UI are included in that runtime.\n\nDocumentation: https://github.com/arcships/android-use#quick-start\n" ) (plugin / "docs").mkdir() for name in ( @@ -247,7 +247,7 @@ def build(output, cache, ffmpeg_binary=None): manifest = { "name": "android-use", "version": __version__, - "description": "Android control with an automatically provisioned standalone runtime", + "description": "Android control with an optional standalone runtime installation", "skills": "./skills/", "mcpServers": "./.mcp.json", "interface": {"displayName": "Android Use"}, diff --git a/skills/android-use/SKILL.md b/skills/android-use/SKILL.md index cdc82fb..a058730 100644 --- a/skills/android-use/SKILL.md +++ b/skills/android-use/SKILL.md @@ -5,6 +5,8 @@ description: 通过 Android Use 的 MCP 工具或 CLI 操作 ADB 已授权的 An # Android Use +安装或升级时,独立 runtime 是可选项。先检查已有 MCP/插件是否健康,再检查 Python/uv、ADB、ffmpeg、平台、网络和可用发行资产;由 Agent 按环境选择源码方式或已校验的独立包。已有依赖可继续源码安装,缺少依赖且有匹配原生包时可选独立包。不为采用 runtime 迁移正常安装,不重复注册 MCP;保留设备、Jev 设置和其他服务。安装细节见 README 与 `docs/standalone.md`。 + 优化目标按完成任务的端到端速度、成功率、宿主大模型往返次数排序。Jev token 费用不作为路由约束,usage 只作辅助记录。连续局部决策在一次 `aua_execute_goal` 内处理,不逐个动作交回宿主审批;复用安全返回的 observation 规划后续步骤,避免紧接着重复读树。已知路径仍用更直接的 batch / scroll_until,遇到不确定、接管、业务验收时由 Agent 处理。 `aua_execute_goal` 的 `input_macros=true` 默认将有稳定唯一标识的非密码输入框提供为“聚焦→精确输入→原生回读”候选,需同时允许 tap/type_text。无稳定标识或界面意外变化时沿用单步或交回,不强行输入;输入法覆盖层同样会停止。宏不提交、不换行、不生成新文本。max_steps 统计候选次数,一个输入宏最多两次原生动作;检查 steps[].substeps 的执行、partial/uncertain 和验证状态,handoff.completed_actions 统计原生子动作,不能据此重放整个宏。需要对照或禁用宏时传 input_macros=false。 From 7b764d48cb7f9153baeaa3895999bfc01a1f9711 Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:18:17 +0800 Subject: [PATCH 12/13] fix: use .NET hashing and extraction in Windows bootstrap --- scripts/runtime.ps1 | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/scripts/runtime.ps1 b/scripts/runtime.ps1 index f7b6376..ddd0aeb 100644 --- a/scripts/runtime.ps1 +++ b/scripts/runtime.ps1 @@ -35,8 +35,15 @@ try { $lines = @(Get-Content (Join-Path $work 'SHA256SUMS') | Where-Object { $_ -match "^[a-fA-F0-9]{64}\s+\*?$([regex]::Escape($name))$" }) if ($lines.Count -ne 1) { throw 'Missing runtime checksum' } $expected = ($lines[0] -split '\s+')[0].ToLowerInvariant() - if ((Get-FileHash (Join-Path $work $name) -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expected) { throw 'Runtime checksum mismatch' } - Expand-Archive -LiteralPath (Join-Path $work $name) -DestinationPath (Join-Path $work 'bundle') + # Use .NET rather than optional functions/modules inherited from a pwsh host. + $stream = [System.IO.File]::OpenRead((Join-Path $work $name)) + $sha = [System.Security.Cryptography.SHA256]::Create() + try { + $actual = [System.BitConverter]::ToString($sha.ComputeHash($stream)).Replace('-', '').ToLowerInvariant() + } finally { $stream.Dispose(); $sha.Dispose() } + if ($actual -ne $expected) { throw 'Runtime checksum mismatch' } + Add-Type -AssemblyName System.IO.Compression.FileSystem + [System.IO.Compression.ZipFile]::ExtractToDirectory((Join-Path $work $name), (Join-Path $work 'bundle')) $result = & (Join-Path $work 'bundle/app/android-use-runtime.exe') --root $root install --archive (Join-Path $work $name) --sha256 $expected [Console]::Error.WriteLine(($result -join [Environment]::NewLine)) if ($LASTEXITCODE -ne 0) { throw 'Runtime installation failed' } From 3517d7d7ef1d2679067ef916684ed78937d79595 Mon Sep 17 00:00:00 2001 From: JackCaow <158038224+JackCaow@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:19:30 +0800 Subject: [PATCH 13/13] docs: record native acceptance evidence and remaining validation boundaries --- docs/benchmarks/standalone-runtime.json | 139 ++++++++++++++++++++++++ docs/guide.zh-CN.md | 2 +- docs/validation.md | 10 ++ 3 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 docs/benchmarks/standalone-runtime.json diff --git a/docs/benchmarks/standalone-runtime.json b/docs/benchmarks/standalone-runtime.json new file mode 100644 index 0000000..3c56df0 --- /dev/null +++ b/docs/benchmarks/standalone-runtime.json @@ -0,0 +1,139 @@ +{ + "date": "2026-11-06", + "scope": "Standalone runtime source feature after v0.6.2; no release published", + "local": { + "platform": "macos-arm64", + "source_commit": "1ad951c54a836ca59fb8174f84b1c1c5f79335e9", + "build_python": "3.12.12 (modular Homebrew CPython)", + "acceptance": { + "platform": "macos-arm64", + "version": "0.6.2", + "upgraded_version": "0.6.2+upgrade-test", + "passed": [ + "health_without_system_python_uv_adb_ffmpeg", + "first_install_stable_stdio_and_embedded_ui_resource", + "corrupt_download_keeps_previous_runtime", + "upgrade_switches_new_sessions_without_interrupting_old_session", + "deleted_original_extraction_does_not_break_stable_entry", + "native_health_failure_preserves_active_version", + "rollback_reprobes_previous_runtime_and_pauses_auto_update", + "private_settings_preserved", + "bundled_cli_dispatch", + "frozen_preview_daemon_dispatch", + "bundled_ffmpeg_h264_filter_scale_and_jpeg_decode", + "ocr_omitted_by_default_optional_component_verified_and_bad_update_refused", + "precompiled_ocr_without_swift_compiler", + "packaged_plugin_first_install_and_clean_stdio_with_stubbed_download_transport", + "private_plugin_bootstrap_with_stubbed_github_cli_and_clean_stdio" + ], + "phone_actions": false, + "model_calls": false, + "runtime_system_tools_removed_from_PATH": true, + "bootstrap_download_transport": "local stub; production URLs checked", + "runtime_sha256": "dc829b3201ee366f6aedcb37cf1dbed61d73ab760e8c31e16b29686337d3e89b" + }, + "native_file_count": 118, + "package_metadata_count": 51, + "package_inventory_scope": "build environment superset, not a complete binary provenance graph", + "source_artifacts": [ + "wheel", + "sdist", + "source plugin ZIP" + ] + }, + "regressions": { + "python_passed": 481, + "browser_passed": 24, + "ruff": "passed", + "notice_regeneration": "unchanged after frontend rebuild" + }, + "ci": { + "run": "https://github.com/arcships/android-use/actions/runs/42185381161", + "source_commit": "1ad951c54a836ca59fb8174f84b1c1c5f79335e9", + "platforms": [ + { + "platform": "linux-x86_64", + "version": "0.6.2", + "upgraded_version": "0.6.2+upgrade-test", + "passed": [ + "health_without_system_python_uv_adb_ffmpeg", + "first_install_stable_stdio_and_embedded_ui_resource", + "corrupt_download_keeps_previous_runtime", + "upgrade_switches_new_sessions_without_interrupting_old_session", + "deleted_original_extraction_does_not_break_stable_entry", + "native_health_failure_preserves_active_version", + "rollback_reprobes_previous_runtime_and_pauses_auto_update", + "private_settings_preserved", + "bundled_cli_dispatch", + "frozen_preview_daemon_dispatch", + "bundled_ffmpeg_h264_filter_scale_and_jpeg_decode", + "packaged_plugin_first_install_and_clean_stdio_with_stubbed_download_transport", + "private_plugin_bootstrap_with_stubbed_github_cli_and_clean_stdio" + ], + "phone_actions": false, + "model_calls": false, + "runtime_system_tools_removed_from_PATH": true, + "bootstrap_download_transport": "local stub; production URLs checked", + "runtime_sha256": "eab60b5705b6f5dff18a23174873c8256fa438a96a78a7ea8f63c70b1a46a384", + "job_id": 127785046874, + "result": "passed" + }, + { + "platform": "macos-arm64", + "version": "0.6.2", + "upgraded_version": "0.6.2+upgrade-test", + "passed": [ + "health_without_system_python_uv_adb_ffmpeg", + "first_install_stable_stdio_and_embedded_ui_resource", + "corrupt_download_keeps_previous_runtime", + "upgrade_switches_new_sessions_without_interrupting_old_session", + "deleted_original_extraction_does_not_break_stable_entry", + "native_health_failure_preserves_active_version", + "rollback_reprobes_previous_runtime_and_pauses_auto_update", + "private_settings_preserved", + "bundled_cli_dispatch", + "frozen_preview_daemon_dispatch", + "bundled_ffmpeg_h264_filter_scale_and_jpeg_decode", + "ocr_omitted_by_default_optional_component_verified_and_bad_update_refused", + "precompiled_ocr_without_swift_compiler", + "packaged_plugin_first_install_and_clean_stdio_with_stubbed_download_transport", + "private_plugin_bootstrap_with_stubbed_github_cli_and_clean_stdio" + ], + "phone_actions": false, + "model_calls": false, + "runtime_system_tools_removed_from_PATH": true, + "bootstrap_download_transport": "local stub; production URLs checked", + "runtime_sha256": "bb45b0f3fa9beba629a533ff5994f8653c404cc7748203991ed5472c30f05161", + "job_id": 127785046865, + "result": "passed" + } + ], + "scope": "Recorded completed platform snapshots from this run; it also exposed the Windows bootstrap failure retained below. These are not a claim that the whole run passed." + }, + "retained_initial_failures": [ + "Optional gdbm was built into the first local uv-managed Python. Those diagnostic artifacts are not approved; the builder now requires excludable DBM/readline and inventories native files.", + "Windows initially selected the wrong Bash path; use the MSYS2 action-provided installation path.", + "A Windows upstream FFmpeg download timed out; one verified input job now supplies all native jobs.", + "Windows make required the ffmpeg.exe target rather than ffmpeg.", + "Git autocrlf changed pinned license hashes on Windows; preserve upstream bytes with attributes and a real checkout regression.", + "Windows MCP initialized but HTML resource reading failed with a charmap decoding error; explicitly read UTF-8 in MCP and HTTP preview and add two regressions.", + "The first local source-distribution check included the custom .build-venv from the build sandbox. A separate clean index export, without build environments, passed wheel/sdist/plugin construction.", + "Windows PowerShell 5.1 bootstrap inherited a host module environment without Get-FileHash; compute SHA256 and extract ZIPs through .NET instead.", + "On the native PowerShell path, core health/MCP/upgrade checks completed before the initial-bootstrap failure; the run as a whole is not counted as passing." + ], + "limits": [ + "No phone actions, real device video, Jev calls or model performance comparisons in this package acceptance.", + "Bootstrap download transport is stubbed locally; a live release download cannot be accepted until native assets are published.", + "Current MCP processes are not hot-replaced; the next connection uses the promoted version.", + "Existing runtime directories are retained. A forced process exit can leave a lock that requires operator verification before cleanup.", + "macOS and Windows packages are unsigned. New-user OS security prompts and OEM USB drivers were not accepted in CI.", + "Licensing evidence is scoped to current declarations, build configuration and collected notices; not blanket legal certification of every static native dependency." + ], + "installation_policy": "Agent selects source or optional standalone runtime from the host environment; reuse healthy installs", + "project_license": { + "spdx": "MIT", + "copyright": "Copyright (c) 2026 Archship", + "verified_in_source_and_native_archives": true + }, + "latest_validation": "https://github.com/arcships/android-use/pull/1/checks" +} diff --git a/docs/guide.zh-CN.md b/docs/guide.zh-CN.md index 9b3ccfb..fb1e156 100644 --- a/docs/guide.zh-CN.md +++ b/docs/guide.zh-CN.md @@ -2,7 +2,7 @@ v0.4.0 可选功能:[可选 Jev 决策集成与对比测试](jev.zh-CN.md)。默认关闭,原有工具兼容保留;v0.4.0 Release ZIP 已包含。 -v0.5.1 已包含[只读自动 OCR 与执行守卫](jev.zh-CN.md#自动只读-ocr),并修复预览自动恢复;v0.5.2 进一步加入[稳定预览入口与新帧确认重连](preview-reconnection.md);v0.6.0 新增[无 Key 宿主决策与可选 Jev Box 视觉定位](jev.zh-CN.md#无-key宿主决策模式);v0.6.1 在 Box 框住多个文字标签时返回 `ambiguous` 和树中候选;内置 OCR 需要 macOS 与 Xcode Command Line Tools。 +v0.5.1 已包含[只读自动 OCR 与执行守卫](jev.zh-CN.md#自动只读-ocr),并修复预览自动恢复;v0.5.2 进一步加入[稳定预览入口与新帧确认重连](preview-reconnection.md);v0.6.0 新增[无 Key 宿主决策与可选 Jev Box 视觉定位](jev.zh-CN.md#无-key宿主决策模式);v0.6.1 在 Box 框住多个文字标签时返回 `ambiguous` 和树中候选;源码方式的本地 OCR 需要 macOS 与 Xcode Command Line Tools;可选独立包使用另行安装的预编译 OCR 组件。 [English](guide.md) · **简体中文** · [返回项目首页](../README.zh-CN.md) diff --git a/docs/validation.md b/docs/validation.md index 200d28c..ccefd39 100644 --- a/docs/validation.md +++ b/docs/validation.md @@ -2,6 +2,16 @@ 日期:2026-11-03 至 2026-11-06。手机序列号、账号内容和截图不提交到源码中。 +## 2026-11-06:可选独立运行包、升级与协议检查 + +- **runtime 可选**:Agent 按用户已有安装、Python/uv、ADB、ffmpeg、平台、网络及发行资产选择源码或独立包,不迁移健康环境。原有 MCP 工具和源码方式继续可用。项目 MIT 版权归属改为 **Archship**;第三方保留自身协议。 +- 481 项 Python 回归、24 项浏览器测试、Ruff 通过;干净提交索引导出的 wheel、sdist 与源码插件 ZIP 构建通过。最终源码 ZIP 的项目 LICENSE 已核对为 Archship。 +- macOS ARM64 本机原生包通过 15 项验收,执行环境 PATH 移除了系统 Python、uv、ADB 与 ffmpeg。覆盖真实 MCP 握手和 UI 资源、首次安装、不同版本升级时旧会话继续服务、新连接切换、删除原解压目录、坏包/版本健康失败保留旧版、回滚再验证、暂停自动更新、私有设置保留、CLI/守护进程分派、实际 H.264→JPEG,以及可选 OCR 安装/识别与失败更新保留。 +- 原生工作流在 macOS ARM64/Intel、Linux x86_64、Windows x86_64 上构建两份不同版本并执行真实 MCP 验收。本记录已收录 CI macOS ARM64 的 15 项和 Linux 的 13 项通过快照;各平台后续结果及 `acceptance.json` 以 [PR 的最新检查与产物](https://github.com/arcships/android-use/pull/1/checks) 为准,不将尚未完成的矩阵视作通过。 +- 协议扫描发现首个本机构建 Python 内置 GNU gdbm,旧诊断包不作为交付包;现用可排除模块的 Python,构建门禁拒绝已静态嵌入的 DBM/readline,并检查原生文件。随包提供 CPython/依赖声明、certifi 源码、FFmpeg 对应源码/精确编译参数和原生清单。前端重新构建保留这些声明。[协议审计](license-audit.md)。 +- **保留首轮失败**:Windows 的 Bash 路径、上游下载超时、make 目标、Git CRLF 导致声明 SHA256 变化,HTML 按默认编码读取失败,以及首次引导缺少 PowerShell `Get-FileHash` 函数均记录在脱敏报告;引导改用 .NET 哈希和解压。编码问题已在 MCP 资源和 HTTP 预览两条路径加回归,声明字节通过真实 Git 检出回归验证。 +- 本轮没有手机操作、真机视频或 Jev 请求;首次公开/私有下载仅对传输层使用本地桩,不能据此宣称真实 GitHub Release 下载已验收。macOS/Windows 未签名,也未覆盖新用户的系统安全提示和 OEM 驱动。当前版本继续执行,升级只影响后续连接;强杀残留锁需确认进程退出后处理。没有合并 PR 或发布新版本,历史 v0.6.2 ZIP 不含此功能。[脱敏记录](benchmarks/standalone-runtime.json) · [安装与边界](standalone.md)。 + ## 2026-11-06:可选交互变化(v0.6.2 之后的源码更新) - 437 项 Python 回归、Ruff 通过,新增覆盖固定种子、边界、默认路径读取次数、参数拒绝、页面/锁屏/旋转/接管变化、预算、不确定动作不重放、滚动与 Agent/Jev 配置透传。Jev 在此轮使用假决策接口测试,没有发出真实模型请求。