diff --git a/AGENTS.md b/AGENTS.md index 8facd0244..5a018b46e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -7,7 +7,7 @@ ## Project -- Stack: Python 3.12+ framework, Python 3.13 agent execution runtime, Flask, Alpine.js, LiteLLM, and Socket.IO. +- Stack: Python 3.12+ framework, Flask, Alpine.js, LiteLLM, and Socket.IO. Docker uses the official Python image's global environment. - Start the WebUI with `python run_ui.py`; discover its URL from startup output, Docker mappings, or explicit configuration rather than assuming a port. - Run the full test suite with `pytest` or a focused file with `pytest tests/test_name.py`. - Human-facing documentation lives in `README.md` and `docs/`. @@ -49,7 +49,8 @@ - System section owners register request-only alternatives with `helpers.responses_tools`; `helpers.responses_history` owns their per-build state and prepared-history capture in existing loop parameters. Responses applies them to copied input, preserving original Chat/fallback messages and stored history. - Copy live core-plugin changes back into tracked source under `plugins/`. - Develop new custom plugins under ignored `usr/plugins/`; tracked bundled plugins live under `plugins/`. -- Use the framework runtime for backend and plugin-hook verification, not the separate agent execution runtime. +- In Docker, use the global `/usr/local/bin/python` runtime for framework, plugin-hook, and local agent-code verification. +- `requirements.py` activates Depfix defaults from the repository-relative `requirements.txt` and must remain the first application import in production Python entrypoints. - Dependency changes must cover both image installation declarations and existing self-updated instances. Use startup migrations for core dependencies and the owning installation hooks for plugin dependencies. ## Permissions diff --git a/DockerfileLocal b/DockerfileLocal index f934d9749..d3826e21a 100644 --- a/DockerfileLocal +++ b/DockerfileLocal @@ -1,6 +1,8 @@ # Use the pre-built base image for A0 -# FROM agent-zero-base:local -FROM agent0ai/agent-zero-base:latest +ARG BASE_IMAGE=agent-zero-base:local +FROM ${BASE_IMAGE} +# FROM agent0ai/agent-zero-base:testing +# FROM agent0ai/agent-zero-base:latest # Set BRANCH to "local" if not provided ARG BRANCH=local @@ -14,13 +16,14 @@ COPY ./ /git/agent-zero # pre installation steps RUN bash /ins/pre_install.sh $BRANCH -# install A0 +# Prime the Depfix store from the copied local source snapshot. RUN bash /ins/install_A0.sh $BRANCH # install additional software RUN bash /ins/install_additional.sh $BRANCH -# cleanup repo and install A0 without caching, this speeds up builds +# Reuse exact Depfix packages and install runtime assets once from the final +# local source snapshot. ARG CACHE_DATE=none RUN echo "cache buster $CACHE_DATE" && bash /ins/install_A02.sh $BRANCH @@ -30,7 +33,7 @@ RUN bash /ins/post_install.sh $BRANCH # Expose ports EXPOSE 22 80 9000-9009 -RUN chmod +x /exe/initialize.sh /exe/run_A0.sh /exe/run_searxng.sh /exe/run_tunnel_api.sh +RUN chmod +x /exe/initialize.sh /exe/run_A0.sh /exe/run_tunnel_api.sh /exe/trigger_self_update.sh # initialize runtime and switch to supervisord CMD ["/exe/initialize.sh", "$BRANCH"] diff --git a/agents/hacker/prompts/agent.system.main.environment.md b/agents/hacker/prompts/agent.system.main.environment.md index 5750d7cdd..ca2dbdabb 100644 --- a/agents/hacker/prompts/agent.system.main.environment.md +++ b/agents/hacker/prompts/agent.system.main.environment.md @@ -1,7 +1,7 @@ ## Environment -live in kali linux docker container use debian kali packages +live in an official Python docker image based on Debian Trixie slim and use Debian packages agent zero framework is python project in /a0 folder linux fully root accessible via terminal -utilize kali hacking tools for job +install only the Debian security tools needed for the job; do not assume Kali tools are preinstalled wordlists need downloading -consider fact running in docker for network operations \ No newline at end of file +consider fact running in docker for network operations diff --git a/docker/AGENTS.md b/docker/AGENTS.md index eef40563a..aae3afa33 100644 --- a/docker/AGENTS.md +++ b/docker/AGENTS.md @@ -3,7 +3,7 @@ ## Purpose - Own Docker build contexts and runtime container definitions. -- Keep framework runtime, agent execution runtime, exposed ports, mounted paths, and image build assumptions explicit. +- Keep the shared Python runtime, exposed ports, mounted paths, and image build assumptions explicit. ## Ownership @@ -13,8 +13,10 @@ ## Local Contracts -- Preserve the two-runtime model: the Python 3.12 framework runtime under `/opt/venv-a0` runs the WebUI, APIs, scheduler, framework imports, and plugin hooks; the Python 3.13 agent execution runtime under `/opt/venv` runs agent terminal tasks and user code. -- Verify backend imports and plugin hooks with `/opt/venv-a0`; packages installed into `/opt/venv` do not prove framework compatibility. +- Base the outer image on `python:3.12-slim-trixie`; do not add Kali repositories, pyenv, or a virtual environment. +- Install WebUI, API, scheduler, framework, plugin-hook, and local agent/user dependencies into the image's global Python environment. +- Verify backend imports, plugin hooks, and local code execution with `/usr/local/bin/python`. +- Keep build-time apt transactions self-contained: update, install or upgrade, and remove `/var/lib/apt/lists/*` in the same Docker `RUN`. - Do not bake secrets, local `.env` values, or user data into images. - Keep compose mounts aligned with `usr/` and other runtime-state expectations. - Image changes that affect GitHub publishing must stay synchronized with `.github/workflows/docker-publish.yml`. diff --git a/docker/base/AGENTS.md b/docker/base/AGENTS.md index bcfb986d7..f74c23a72 100644 --- a/docker/base/AGENTS.md +++ b/docker/base/AGENTS.md @@ -3,7 +3,7 @@ ## Purpose - Own the Agent Zero base image build context. -- Build the operating system, package, Python, SearXNG, SSH, and bootstrap layers reused by runnable images. +- Build the operating system, package, Python, SSH, and bootstrap layers reused by runnable images. ## Ownership @@ -15,7 +15,16 @@ ## Local Contracts - Preserve cache-friendly package and runtime installation stages. -- Keep locale and timezone defaults compatible with the root Docker contract. +- Keep the outer image based on `python:3.12-slim-trixie` and install Python packages into its global environment. +- Do not install another Python through apt or pyenv, and do not create a virtual environment. +- Copy Node and bundled npm from the matching official `node:22-trixie-slim` build stage; do not install Debian's unbundled `nodejs` or `npm` packages. +- Install the signed gVisor apt package in a throwaway stage and copy only `runsc` plus `gvisor-bin/gvisor_sentry` into the final image; do not include its containerd shim, checkpoint gofer, or metric server. +- Keep daemonless `skopeo` and `umoci` image tooling available to the bundled sandboxing plugin. +- Keep Debian's `build-essential` toolchain and CMake available for source-distributed Python dependencies resolved into Depfix's shared store. +- Sandbox root filesystems are runtime-managed cache content; do not add a baked sandbox rootfs unless its lifecycle and provenance contract is updated with the plugin. +- Do not install SearXNG, create its service user or virtualenv, or copy its configuration into the base image; the placeholder integration is owned by `plugins/_searxng/`. +- Do not install Tesseract, OCR language packs, or Poppler in the base image; `plugins/_document_query/` installs those system packages only when a legacy OCR fallback reaches its first use. +- Use Debian's built-in `C.UTF-8` locale without installing or generating locale data, and keep the timezone set to UTC. - Do not add secrets, user data, or local environment files to the image context. - Installation scripts must be noninteractive and suitable for multi-architecture buildx runs. diff --git a/docker/base/Dockerfile b/docker/base/Dockerfile index 7e94ed80a..e9e4f5853 100644 --- a/docker/base/Dockerfile +++ b/docker/base/Dockerfile @@ -1,18 +1,49 @@ -# Use the latest slim version of Kali Linux -FROM kalilinux/kali-rolling +# Import the official Node runtime and its bundled npm without Debian's large +# unbundled npm dependency tree. +FROM node:22-trixie-slim AS node-runtime + +# Install the signed gVisor package outside the final image. Current gVisor +# releases split the Sentry from runsc, while the other packaged executables +# support containerd, remote checkpoints, or optional metrics. +FROM debian:trixie-slim AS gvisor-package + +ARG DEBIAN_FRONTEND=noninteractive +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl gnupg \ + && curl -fsSL https://gvisor.dev/archive.key \ + | gpg --dearmor -o /usr/share/keyrings/gvisor-archive-keyring.gpg \ + && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/gvisor-archive-keyring.gpg] https://storage.googleapis.com/gvisor/releases release main" \ + > /etc/apt/sources.list.d/gvisor.list \ + && apt-get update \ + && apt-get install -y --no-install-recommends runsc \ + && test -x /usr/bin/runsc \ + && test -x /usr/bin/gvisor-bin/gvisor_sentry \ + && rm -rf /var/lib/apt/lists/* + +# Use the official Python image and install packages into its global runtime. +FROM python:3.12-slim-trixie AS runtime + +ARG DEBIAN_FRONTEND=noninteractive +ENV UV_SYSTEM_PYTHON=1 \ + PIP_ROOT_USER_ACTION=ignore + +COPY --from=node-runtime /usr/local/bin/node /usr/local/bin/node +COPY --from=node-runtime /usr/local/lib/node_modules /usr/local/lib/node_modules +COPY --from=gvisor-package /usr/bin/runsc /usr/bin/runsc +COPY --from=gvisor-package /usr/bin/gvisor-bin/gvisor_sentry /usr/bin/gvisor-bin/gvisor_sentry +RUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm \ + && ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx -# Set locale to en_US.UTF-8 and timezone to UTC -RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y locales tzdata -RUN sed -i -e 's/# \(en_US\.UTF-8 .*\)/\1/' /etc/locale.gen && \ - dpkg-reconfigure --frontend=noninteractive locales && \ - update-locale LANG=en_US.UTF-8 LANGUAGE=en_US:en LC_ALL=en_US.UTF-8 -RUN ln -sf /usr/share/zoneinfo/UTC /etc/localtime -RUN echo "UTC" > /etc/timezone -RUN dpkg-reconfigure -f noninteractive tzdata -ENV LANG=en_US.UTF-8 -ENV LANGUAGE=en_US:en -ENV LC_ALL=en_US.UTF-8 +# Use Debian's built-in UTF-8 locale and configure the UTC timezone. +RUN apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends tzdata \ + && ln -sf /usr/share/zoneinfo/UTC /etc/localtime \ + && echo "UTC" > /etc/timezone \ + && dpkg-reconfigure -f noninteractive tzdata \ + && rm -rf /var/lib/apt/lists/* +ENV LANG=C.UTF-8 +ENV LC_ALL=C.UTF-8 ENV TZ=UTC # Copy contents of the project to / @@ -24,12 +55,9 @@ RUN bash /ins/install_base_packages2.sh RUN bash /ins/install_base_packages3.sh RUN bash /ins/install_base_packages4.sh -# install python after packages to ensure version overriding +# install shared Python tooling into the image's global environment RUN bash /ins/install_python.sh -# install searxng -RUN bash /ins/install_searxng.sh - # configure ssh RUN bash /ins/configure_ssh.sh diff --git a/docker/base/fs/etc/searxng/limiter.toml b/docker/base/fs/etc/searxng/limiter.toml deleted file mode 100644 index d5cddbc9f..000000000 --- a/docker/base/fs/etc/searxng/limiter.toml +++ /dev/null @@ -1,33 +0,0 @@ -[botdetection] -# Number of values to trust for X-Forwarded-For. -trusted_proxies = ["127.0.0.1"] - -# The prefix defines the number of leading bits in an address that are compared -# to determine whether or not an address is part of a (client) network. -ipv4_prefix = 32 -ipv6_prefix = 48 - -[botdetection.ip_limit] -# To get unlimited access in a local network, by default link-local addresses -# (networks) are not monitored by the ip_limit -filter_link_local = false - -# Activate link_token method in the ip_limit method -link_token = false - -[botdetection.ip_lists] -# In the limiter, the ip_lists method has priority over all other methods. -# If an IP is in the pass_ip list, it has unrestricted access and is not -# checked if, for example, the "user agent" suggests a bot (e.g., curl). -block_ip = [ - # '93.184.216.34', # Example IPv4 address - # '257.1.1.1', # Invalid IP --> will be ignored, logged in ERROR class -] -pass_ip = [ - # '192.168.0.0/16', # IPv4 private network - # 'fe80::/10', # IPv6 link-local; overrides botdetection.ip_limit.filter_link_local -] - -# Activate passlist of (hardcoded) IPs from the SearXNG organization, -# e.g., `check.searx.space`. -pass_searxng_org = true diff --git a/docker/base/fs/etc/searxng/settings.yml b/docker/base/fs/etc/searxng/settings.yml deleted file mode 100644 index e8cc4ef37..000000000 --- a/docker/base/fs/etc/searxng/settings.yml +++ /dev/null @@ -1,91 +0,0 @@ -# SearXNG settings - -# Keep a minimal default engine set. Wikidata currently returns -# variant payloads that break the 2026.04 searxng bootstrap init path. -use_default_settings: - engines: - remove: - - wikidata - -general: - debug: false - instance_name: "SearXNG" - -search: - safe_search: 0 - # autocomplete: 'duckduckgo' - formats: - - json - # - html - -server: - # Is overwritten by ${SEARXNG_SECRET} - secret_key: "dummy" - port: 55510 - limiter: false - image_proxy: false - # public URL of the instance, to ensure correct inbound links. Is overwritten - # by ${SEARXNG_URL}. - # base_url: http://example.com/location - -# redis: -# # URL to connect redis database. Is overwritten by ${SEARXNG_REDIS_URL}. -# url: unix:///usr/local/searxng-redis/run/redis.sock?db=0 - -ui: - static_use_hash: true - -# preferences: -# lock: -# - autocomplete -# - method - -enabled_plugins: - - 'Hash plugin' - - 'Self Informations' - - 'Tracker URL remover' - # - 'Ahmia blacklist' - # - 'Hostnames plugin' # see 'hostnames' configuration below - # - 'Open Access DOI rewrite' - -# plugins: -# - only_show_green_results - -# hostnames: -# replace: -# '(.*\.)?youtube\.com$': 'invidious.example.com' -# '(.*\.)?youtu\.be$': 'invidious.example.com' -# remove: -# - '(.*\.)?facebook.com$' -# low_priority: -# - '(.*\.)?google\.com$' -# high_priority: -# - '(.*\.)?wikipedia.org$' - -engines: - - - name: ahmia - disabled: true - inactive: true - - - name: torch - disabled: true - inactive: true - -# - name: fdroid -# disabled: false -# -# - name: apk mirror -# disabled: false -# -# - name: mediathekviewweb -# categories: TV -# disabled: false -# -# - name: invidious -# disabled: false -# base_url: -# - https://invidious.snopyta.org -# - https://invidious.tiekoetter.com -# - https://invidio.xamh.de -# - https://inv.riverside.rocks diff --git a/docker/base/fs/ins/after_install.sh b/docker/base/fs/ins/after_install.sh index ca2028add..150e00df7 100644 --- a/docker/base/fs/ins/after_install.sh +++ b/docker/base/fs/ins/after_install.sh @@ -1,5 +1,7 @@ #!/bin/bash set -e -# clean up apt cache +# Keep this final cleanup as a safeguard for future install steps. Each current +# apt installation layer also removes its own lists before that layer ends. sudo apt-get clean +sudo rm -rf /var/lib/apt/lists/* diff --git a/docker/base/fs/ins/install_base_packages1.sh b/docker/base/fs/ins/install_base_packages1.sh index 9bd108c1e..2c02f0c18 100644 --- a/docker/base/fs/ins/install_base_packages1.sh +++ b/docker/base/fs/ins/install_base_packages1.sh @@ -6,6 +6,9 @@ echo "====================BASE PACKAGES1 START====================" apt-get update && apt-get upgrade -y apt-get install -y --no-install-recommends \ - sudo curl wget git cron unzip 7zip + sudo curl wget git cron unzip 7zip \ + build-essential cmake + +rm -rf /var/lib/apt/lists/* echo "====================BASE PACKAGES1 END====================" diff --git a/docker/base/fs/ins/install_base_packages2.sh b/docker/base/fs/ins/install_base_packages2.sh index 1c33313e8..f43ff19cb 100644 --- a/docker/base/fs/ins/install_base_packages2.sh +++ b/docker/base/fs/ins/install_base_packages2.sh @@ -3,8 +3,10 @@ set -e echo "====================BASE PACKAGES2 START====================" - +apt-get update apt-get install -y --no-install-recommends \ - openssh-server ffmpeg supervisor + libasound2t64 openssh-server supervisor + +rm -rf /var/lib/apt/lists/* # for docker layers size echo "====================BASE PACKAGES2 END====================" diff --git a/docker/base/fs/ins/install_base_packages3.sh b/docker/base/fs/ins/install_base_packages3.sh index c77f6d492..4073aa77e 100644 --- a/docker/base/fs/ins/install_base_packages3.sh +++ b/docker/base/fs/ins/install_base_packages3.sh @@ -3,11 +3,8 @@ set -e echo "====================BASE PACKAGES3 START====================" -apt-get install -y --no-install-recommends \ - nodejs npm +# Node and bundled npm are copied from the official Node image by Dockerfile. +node --version +npm --version -echo "====================BASE PACKAGES3 NPM====================" - -# we shall not install npx separately, it's discontinued and some versions are broken -# npm i -g npx echo "====================BASE PACKAGES3 END====================" diff --git a/docker/base/fs/ins/install_base_packages4.sh b/docker/base/fs/ins/install_base_packages4.sh index 45726ddc0..abe941104 100644 --- a/docker/base/fs/ins/install_base_packages4.sh +++ b/docker/base/fs/ins/install_base_packages4.sh @@ -3,7 +3,11 @@ set -e echo "====================BASE PACKAGES4 START====================" +# sandboxing +apt-get update apt-get install -y --no-install-recommends \ - tesseract-ocr tesseract-ocr-script-latn poppler-utils + ca-certificates util-linux procps iproute2 skopeo umoci -echo "====================BASE PACKAGES4 END====================" \ No newline at end of file +rm -rf /var/lib/apt/lists/* # for docker layers size + +echo "====================BASE PACKAGES4 END====================" diff --git a/docker/base/fs/ins/install_python.sh b/docker/base/fs/ins/install_python.sh index 71c9513ef..e3a527491 100644 --- a/docker/base/fs/ins/install_python.sh +++ b/docker/base/fs/ins/install_python.sh @@ -3,71 +3,25 @@ set -e echo "====================PYTHON START====================" -echo "====================PYTHON 3.13====================" +apt-get update +apt-get -y upgrade +rm -rf /var/lib/apt/lists/* -apt clean && apt-get update && apt-get -y upgrade +# The official Python image provides the global interpreter and pip. +python -m pip install --no-cache-dir --upgrade \ + pip pipx ipython uv depfix -# install python 3.13 globally -apt-get install -y --no-install-recommends \ - python3.13 python3.13-venv - #python3.13-dev - - -echo "====================PYTHON 3.13 VENV====================" - -# create and activate default venv -python3.13 -m venv /opt/venv -source /opt/venv/bin/activate - -# upgrade pip and install static packages -pip install --no-cache-dir --upgrade pip pipx ipython requests - -echo "====================PYTHON PYVENV====================" - -# Install pyenv build dependencies. -apt-get install -y --no-install-recommends \ - make build-essential libssl-dev zlib1g-dev libbz2-dev \ - libreadline-dev libsqlite3-dev wget curl llvm \ - libncursesw5-dev xz-utils tk-dev libxml2-dev \ - libxmlsec1-dev libffi-dev liblzma-dev - -# Install pyenv globally -git clone https://github.com/pyenv/pyenv.git /opt/pyenv - -# Setup environment variables for pyenv to be available system-wide -cat > /etc/profile.d/pyenv.sh <<'EOF' -export PYENV_ROOT="/opt/pyenv" -export PATH="$PYENV_ROOT/bin:$PATH" -eval "$(pyenv init --path)" -EOF - -# fix permissions -chmod +x /etc/profile.d/pyenv.sh - -# Source pyenv environment to make it available in this script -source /etc/profile.d/pyenv.sh - -# Install Python 3.12.4 -echo "====================PYENV 3.12 VENV====================" -pyenv install 3.12.4 - -/opt/pyenv/versions/3.12.4/bin/python -m venv /opt/venv-a0 -source /opt/venv-a0/bin/activate - -# upgrade pip and install static packages -pip install --no-cache-dir --upgrade pip pipx - -# Install some packages in specific variants -pip install --no-cache-dir \ - torch==2.4.0 \ - torchvision==0.19.0 \ +# Install CPU-only variants before the application requirements are resolved. +depfix pip install torch torchvision \ --index-url https://download.pytorch.org/whl/cpu -echo "====================PYTHON UV ====================" - -curl -Ls https://astral.sh/uv/install.sh | UV_INSTALL_DIR=/usr/local/bin sh +# PyTorch wheels include development-only test suites, C++ headers, and helper binaries. +rm -rf \ + /usr/local/lib/python3.12/site-packages/torch/test \ + /usr/local/lib/python3.12/site-packages/torch/include \ + /usr/local/lib/python3.12/site-packages/torch/bin # clean up pip cache -pip cache purge +python -m pip cache purge echo "====================PYTHON END====================" diff --git a/docker/base/fs/ins/install_searxng.sh b/docker/base/fs/ins/install_searxng.sh deleted file mode 100644 index 65d0719a5..000000000 --- a/docker/base/fs/ins/install_searxng.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/bash -set -e - -echo "====================SEARXNG1 START====================" - -# Install necessary packages -apt-get install -y \ - git build-essential libxslt-dev zlib1g-dev libffi-dev libssl-dev -# python3.12-babel uwsgi uwsgi-plugin-python3 - - -# Add the searxng system user -useradd --shell /bin/bash --system \ - --home-dir "/usr/local/searxng" \ - --comment 'Privacy-respecting metasearch engine' \ - searxng - -# Add the searxng user to the sudo group -usermod -aG sudo searxng - -# Create the searxng directory and set ownership -mkdir "/usr/local/searxng" -chown -R "searxng:searxng" "/usr/local/searxng" - -echo "====================SEARXNG1 END====================" - -# Start a new shell as the searxng user and run the installation script -su - searxng -c "bash /ins/install_searxng2.sh" - diff --git a/docker/base/fs/ins/install_searxng2.sh b/docker/base/fs/ins/install_searxng2.sh deleted file mode 100644 index 97e735faf..000000000 --- a/docker/base/fs/ins/install_searxng2.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/bash -set -e - -echo "====================SEARXNG2 START====================" - - -# clone SearXNG repo -git clone "https://github.com/searxng/searxng" \ - "/usr/local/searxng/searxng-src" - -echo "====================SEARXNG2 VENV====================" - -# create virtualenv: -python3.13 -m venv "/usr/local/searxng/searx-pyenv" - -# make it default -echo ". /usr/local/searxng/searx-pyenv/bin/activate" \ - >> "/usr/local/searxng/.profile" - -# activate venv -source "/usr/local/searxng/searx-pyenv/bin/activate" - -echo "====================SEARXNG2 INST====================" - -# update pip's boilerplate -pip install --no-cache-dir -U pip setuptools wheel pyyaml lxml msgspec typing_extensions - -# jump to SearXNG's working tree and install SearXNG into virtualenv -cd "/usr/local/searxng/searxng-src" -# pip install --no-cache-dir --use-pep517 --no-build-isolation -e . -pip install --no-cache-dir --use-pep517 --no-build-isolation . - -# cleanup cache -pip cache purge - -echo "====================SEARXNG2 END====================" \ No newline at end of file diff --git a/docker/run/AGENTS.md b/docker/run/AGENTS.md index 8c98797b7..a5289d73f 100644 --- a/docker/run/AGENTS.md +++ b/docker/run/AGENTS.md @@ -11,28 +11,34 @@ - `docker-compose.yml` owns the local compose service example. - `build.txt` owns maintainer build and push command notes. - `fs/exe/` owns runtime entrypoint, supervisor, self-update, Node eval, and service scripts. -- `fs/ins/` owns preinstall, installation, virtualenv, Playwright, SSH, and postinstall scripts. +- `fs/ins/` owns preinstall, installation, Playwright, SSH, and postinstall scripts. - Files under `fs/` are copied to container root during the runtime build. ## Local Contracts - `BRANCH` is required for branch-based Docker builds. - Preserve exposed ports for SSH, HTTP, and tunneled services unless docs and workflows are updated together. -- Keep the two-runtime Python model aligned with the root contract. +- Run framework services and local agent/user Python execution in the official image's global Python environment; do not create or activate a virtual environment. - Retain the Python 3.13-compatible ATK, LibreOffice/UNO, and Xpra pins in `fs/ins/install_additional.sh`. Resolve them from the signed Debian `forky` archive dated `20260624T000000Z` and Xpra `trixie`, using build-scoped APT options that preserve normal Kali sources. Refresh Xpra through `plugins/_desktop/helpers/refresh_xpra_index.sh` from the cloned repository; its signed compressed index avoids upstream's empty ARM64 `Packages` metadata without clearing the Debian indexes. - Do not bake secrets, local `.env` values, or user data into the image. - Runtime startup must ensure `/a0/usr/uploads` exists before supervised services start. - Runtime startup seeds APT package lists in the background only when no package index is cached (fresh images clear these at build time). Normal restarts skip the refresh; installation scripts and plugin hooks refresh metadata when installing packages. - Runtime startup raises the soft open-file limit toward `A0_NOFILE_LIMIT` (default `65535`) before supervisord starts, bounded by the container hard limit. +- Do not launch or configure SearXNG in the outer runtime container; the placeholder integration is owned by `plugins/_searxng/` and any future service must run through sandboxing. +- The compose example keeps the outer container unprivileged with `no-new-privileges`, uses an init reaper for detached sandboxes, and allows the nested gVisor systrap syscall surface through `seccomp:unconfined`. - Self-update user-data backups skip Time Travel shadow history under `usr/.time_travel/` and transient Desktop agent state. - Self-update backups use ZIP deflate level 1 and clamp archive timestamps to ZIP's supported range without changing source file dates. - Self-update rollback stashes use immutable Git object IDs for creation checks and restoration; resolve the matching reflog selector only when dropping that stash, preserving unrelated entries. Failed restoration retains the stash. - Self-update waits up to 600 seconds for each updated or restored WebUI health check by default; `A0_SELF_UPDATE_HEALTH_TIMEOUT_SECONDS` may override it. Backup and checkout time precede this health window. - Successful or already-current self-updates refresh an installed Codex CLI with npm on a best-effort basis; missing CLIs and registry failures must not block Agent Zero startup. +- Application requirements are materialized into Depfix's shared installed store; launchers use `depfix run` so store fallback is active without moving those packages into global `site-packages`. +- The cache-busted final install reuses the first exact Depfix materialization and is the only pass that installs Chromium and runs preload. +- Playwright's pinned Python distribution comes only from `requirements.txt`; `install_playwright.sh` owns Chromium, its OS libraries, and `/a0/tmp/playwright` through the Depfix-managed module invocation. +- Keep Depfix's installed store. Depfix owns its ephemeral uv resolver cache, so runtime-image and self-update scripts must not purge pip or uv caches. ## Work Guidance -- Keep startup scripts explicit about framework runtime versus execution runtime. +- Keep startup scripts explicit about using the global Python runtime. - Coordinate tag, branch, and publishing changes with GitHub workflow automation. ## Verification diff --git a/docker/run/Dockerfile b/docker/run/Dockerfile index 48664461b..f18594c7a 100644 --- a/docker/run/Dockerfile +++ b/docker/run/Dockerfile @@ -1,7 +1,7 @@ # Use the pre-built base image for A0 -# FROM agent-zero-base:local +FROM agent-zero-base:local # FROM agent0ai/agent-zero-base:testing -FROM agent0ai/agent-zero-base:latest +# FROM agent0ai/agent-zero-base:latest # Check if the argument is provided, else throw an error ARG BRANCH @@ -14,13 +14,14 @@ COPY ./fs/ / # pre installation steps RUN bash /ins/pre_install.sh $BRANCH -# install A0 +# Prime the Depfix store from the currently cached branch snapshot. RUN bash /ins/install_A0.sh $BRANCH # install additional software RUN bash /ins/install_additional.sh $BRANCH -# cleanup repo and install A0 without caching, this speeds up builds +# Refresh the branch through the cache buster, reuse exact Depfix packages, and +# install runtime assets once from the final source snapshot. ARG CACHE_DATE=none RUN echo "cache buster $CACHE_DATE" && bash /ins/install_A02.sh $BRANCH @@ -30,7 +31,7 @@ RUN bash /ins/post_install.sh $BRANCH # Expose ports EXPOSE 22 80 9000-9009 -RUN chmod +x /exe/initialize.sh /exe/run_A0.sh /exe/run_searxng.sh /exe/run_tunnel_api.sh /exe/trigger_self_update.sh +RUN chmod +x /exe/initialize.sh /exe/run_A0.sh /exe/run_tunnel_api.sh /exe/trigger_self_update.sh # initialize runtime and switch to supervisord CMD ["/exe/initialize.sh", "$BRANCH"] diff --git a/docker/run/docker-compose.yml b/docker/run/docker-compose.yml index b80da0272..8b735008d 100644 --- a/docker/run/docker-compose.yml +++ b/docker/run/docker-compose.yml @@ -2,6 +2,11 @@ services: agent-zero: container_name: agent-zero image: agent0ai/agent-zero:latest + init: true + privileged: false + security_opt: + - no-new-privileges:true + - seccomp:unconfined volumes: - ./agent-zero:/a0 ports: diff --git a/docker/run/fs/etc/searxng/limiter.toml b/docker/run/fs/etc/searxng/limiter.toml deleted file mode 100644 index d5cddbc9f..000000000 --- a/docker/run/fs/etc/searxng/limiter.toml +++ /dev/null @@ -1,33 +0,0 @@ -[botdetection] -# Number of values to trust for X-Forwarded-For. -trusted_proxies = ["127.0.0.1"] - -# The prefix defines the number of leading bits in an address that are compared -# to determine whether or not an address is part of a (client) network. -ipv4_prefix = 32 -ipv6_prefix = 48 - -[botdetection.ip_limit] -# To get unlimited access in a local network, by default link-local addresses -# (networks) are not monitored by the ip_limit -filter_link_local = false - -# Activate link_token method in the ip_limit method -link_token = false - -[botdetection.ip_lists] -# In the limiter, the ip_lists method has priority over all other methods. -# If an IP is in the pass_ip list, it has unrestricted access and is not -# checked if, for example, the "user agent" suggests a bot (e.g., curl). -block_ip = [ - # '93.184.216.34', # Example IPv4 address - # '257.1.1.1', # Invalid IP --> will be ignored, logged in ERROR class -] -pass_ip = [ - # '192.168.0.0/16', # IPv4 private network - # 'fe80::/10', # IPv6 link-local; overrides botdetection.ip_limit.filter_link_local -] - -# Activate passlist of (hardcoded) IPs from the SearXNG organization, -# e.g., `check.searx.space`. -pass_searxng_org = true diff --git a/docker/run/fs/etc/searxng/settings.yml b/docker/run/fs/etc/searxng/settings.yml deleted file mode 100644 index e5073d924..000000000 --- a/docker/run/fs/etc/searxng/settings.yml +++ /dev/null @@ -1,98 +0,0 @@ -# SearXNG settings - -use_default_settings: - engines: - remove: - - radio browser - - wikidata -# TODO enable radio_browser when it works again -# currently it crashes on x86 on gethostbyaddr - -general: - debug: false - instance_name: "SearXNG" - -search: - safe_search: 0 - # autocomplete: 'duckduckgo' - formats: - - json - # - html - -server: - # Is overwritten by ${SEARXNG_SECRET} - secret_key: "dummy" - port: 55510 - limiter: false - image_proxy: false - # public URL of the instance, to ensure correct inbound links. Is overwritten - # by ${SEARXNG_URL}. - # base_url: http://example.com/location - -# redis: -# # URL to connect redis database. Is overwritten by ${SEARXNG_REDIS_URL}. -# url: unix:///usr/local/searxng-redis/run/redis.sock?db=0 - -ui: - static_use_hash: true - -# preferences: -# lock: -# - autocomplete -# - method - -enabled_plugins: - - 'Hash plugin' - - 'Self Informations' - - 'Tracker URL remover' - # - 'Ahmia blacklist' - # - 'Hostnames plugin' # see 'hostnames' configuration below - # - 'Open Access DOI rewrite' - -# plugins: -# - only_show_green_results - -# hostnames: -# replace: -# '(.*\.)?youtube\.com$': 'invidious.example.com' -# '(.*\.)?youtu\.be$': 'invidious.example.com' -# remove: -# - '(.*\.)?facebook.com$' -# low_priority: -# - '(.*\.)?google\.com$' -# high_priority: -# - '(.*\.)?wikipedia.org$' - -engines: - - name: radio browser - engine: radio_browser - disabled: true - inactive: true - - - name: ahmia - disabled: true - inactive: true - - - name: torch - disabled: true - inactive: true -# TODO enable radio_browser when it works again -# currently it crashes on x86 on gethostbyaddr - -# - name: fdroid -# disabled: false -# -# - name: apk mirror -# disabled: false -# -# - name: mediathekviewweb -# categories: TV -# disabled: false -# -# - name: invidious -# disabled: false -# base_url: -# - https://invidious.snopyta.org -# - https://invidious.tiekoetter.com -# - https://invidio.xamh.de -# - https://inv.riverside.rocks diff --git a/docker/run/fs/etc/supervisor/conf.d/supervisord.conf b/docker/run/fs/etc/supervisor/conf.d/supervisord.conf index 63553ddbc..c09a1924e 100644 --- a/docker/run/fs/etc/supervisor/conf.d/supervisord.conf +++ b/docker/run/fs/etc/supervisor/conf.d/supervisord.conf @@ -43,21 +43,6 @@ startretries=3 stopasgroup=true killasgroup=true -[program:run_searxng] -command=/exe/run_searxng.sh -environment=SEARXNG_SETTINGS_PATH=/etc/searxng/settings.yml -user=searxng -directory=/usr/local/searxng/searxng-src -stopwaitsecs=1 -stdout_logfile=/dev/stdout -stdout_logfile_maxbytes=0 -stderr_logfile=/dev/stderr -stderr_logfile_maxbytes=0 -autorestart=true -startretries=3 -stopasgroup=true -killasgroup=true - [program:run_ui] command=/exe/run_A0.sh environment= @@ -87,7 +72,7 @@ stopasgroup=true killasgroup=true [eventlistener:the_listener] -command=python3 /exe/supervisor_event_listener.py +command=/usr/local/bin/python /exe/supervisor_event_listener.py events=PROCESS_STATE_FATAL stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 diff --git a/docker/run/fs/exe/run_A0.sh b/docker/run/fs/exe/run_A0.sh index 350020d7b..6598de12b 100644 --- a/docker/run/fs/exe/run_A0.sh +++ b/docker/run/fs/exe/run_A0.sh @@ -1,7 +1,7 @@ #!/bin/bash -. "/ins/setup_venv.sh" "$@" . "/ins/copy_A0.sh" "$@" echo "Starting A0 bootstrap manager..." -exec python /exe/self_update_manager.py docker-run-ui +cd /a0 +exec depfix run /exe/self_update_manager.py docker-run-ui diff --git a/docker/run/fs/exe/run_searxng.sh b/docker/run/fs/exe/run_searxng.sh deleted file mode 100644 index bb544186c..000000000 --- a/docker/run/fs/exe/run_searxng.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -# start webapp -cd /usr/local/searxng/searxng-src -export SEARXNG_SETTINGS_PATH="/etc/searxng/settings.yml" - -# activate venv -source "/usr/local/searxng/searx-pyenv/bin/activate" - -exec python /usr/local/searxng/searxng-src/searx/webapp.py diff --git a/docker/run/fs/exe/run_tunnel_api.sh b/docker/run/fs/exe/run_tunnel_api.sh index 88c4ac4e5..29581d22c 100644 --- a/docker/run/fs/exe/run_tunnel_api.sh +++ b/docker/run/fs/exe/run_tunnel_api.sh @@ -9,9 +9,8 @@ while [ ! -f /a0/run_tunnel.py ]; do sleep 1 done -. "/ins/setup_venv.sh" "$@" - -exec python /a0/run_tunnel.py \ +cd /a0 +exec depfix run /a0/run_tunnel.py \ --dockerized=true \ --port=80 \ --tunnel_api_port=55520 \ diff --git a/docker/run/fs/exe/self_update_manager.py b/docker/run/fs/exe/self_update_manager.py index 6d189aca4..a29fe3c4f 100644 --- a/docker/run/fs/exe/self_update_manager.py +++ b/docker/run/fs/exe/self_update_manager.py @@ -618,24 +618,6 @@ def run_command( return completed -def clean_uv_cache(logger: AttemptLogger) -> None: - uv_path = shutil.which("uv") - if not uv_path: - logger.log("uv executable not found, skipping uv cache clean.") - return - - logger.log("Cleaning uv cache before continuing self-update startup.") - try: - run_command( - [uv_path, "cache", "clean"], - cwd=None, - logger=logger, - error_message="Failed to clean uv cache during self-update.", - ) - except Exception as exc: - logger.log(f"uv cache clean skipped after error: {exc}") - - def refresh_codex_cli(logger: AttemptLogger) -> None: codex_path = shutil.which("codex") if not codex_path: @@ -1438,7 +1420,6 @@ def docker_run_ui() -> int: logger.reset() logger.log(f"Consumed update file at {TRIGGER_FILE}") logger.log_block("Trigger file content", raw_text) - clean_uv_cache(logger) try: clean_transient_desktop_agent_state(REPO_DIR, logger) except Exception as exc: diff --git a/docker/run/fs/exe/trigger_self_update.sh b/docker/run/fs/exe/trigger_self_update.sh index de0d1fce0..0faed84e2 100755 --- a/docker/run/fs/exe/trigger_self_update.sh +++ b/docker/run/fs/exe/trigger_self_update.sh @@ -3,4 +3,5 @@ set -eu SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) -exec python3 "$SCRIPT_DIR/self_update_manager.py" trigger-update "$@" +cd /a0 +exec depfix run "$SCRIPT_DIR/self_update_manager.py" trigger-update "$@" diff --git a/docker/run/fs/ins/install_A0.sh b/docker/run/fs/ins/install_A0.sh index 7b5d0d807..83554c4ed 100644 --- a/docker/run/fs/ins/install_A0.sh +++ b/docker/run/fs/ins/install_A0.sh @@ -26,19 +26,5 @@ else } fi -. "/ins/setup_venv.sh" "$@" - -# moved to base image -# # Ensure the virtual environment and pip setup -# pip install --upgrade pip ipython requests -# # Install some packages in specific variants -# pip install torch --index-url https://download.pytorch.org/whl/cpu - -# Install remaining A0 python packages -uv pip install -r /git/agent-zero/requirements.txt - -# install playwright -bash /ins/install_playwright.sh "$@" - -# Preload A0 -python /git/agent-zero/preload.py --dockerized=true +# Materialize the complete application dependency graph in Depfix's shared store. +depfix pip install -r /git/agent-zero/requirements.txt diff --git a/docker/run/fs/ins/install_A02.sh b/docker/run/fs/ins/install_A02.sh index d40132aa0..100acd4b6 100644 --- a/docker/run/fs/ins/install_A02.sh +++ b/docker/run/fs/ins/install_A02.sh @@ -8,10 +8,8 @@ if [ "$1" != "local" ]; then rm -rf /git/agent-zero fi -# run the original install script again +# Refresh the branch and re-resolve once against the already populated Depfix +# store. Runtime assets are deliberately installed only on this final pass. bash /ins/install_A0.sh "$@" - -# remove python packages cache -. "/ins/setup_venv.sh" "$@" -pip cache purge -uv cache prune \ No newline at end of file +bash /ins/install_playwright.sh "$@" +depfix run /git/agent-zero/preload.py --dockerized=true diff --git a/docker/run/fs/ins/install_additional.sh b/docker/run/fs/ins/install_additional.sh index caa3d3e6c..9ab9ecd66 100644 --- a/docker/run/fs/ins/install_additional.sh +++ b/docker/run/fs/ins/install_additional.sh @@ -1,12 +1,6 @@ #!/bin/bash set -e -# install playwright - moved to install A0 -# bash /ins/install_playwright.sh "$@" - -# searxng - moved to base image -# bash /ins/install_searxng.sh "$@" - if ! command -v apt-get >/dev/null 2>&1; then echo "apt-get unavailable; skipping LibreOffice install" exit 0 diff --git a/docker/run/fs/ins/install_playwright.sh b/docker/run/fs/ins/install_playwright.sh index d5fc31e42..ace37342d 100644 --- a/docker/run/fs/ins/install_playwright.sh +++ b/docker/run/fs/ins/install_playwright.sh @@ -1,13 +1,15 @@ #!/bin/bash set -e -# activate venv -. "/ins/setup_venv.sh" "$@" - -# set PW installation path to temporary Browser runtime storage +# The pinned Python package is already materialized by the main requirements +# install. Keep only Chromium and its operating-system runtime dependencies here. export PLAYWRIGHT_BROWSERS_PATH=/a0/tmp/playwright mkdir -p "$PLAYWRIGHT_BROWSERS_PATH" -# preinstall Chromium for fresh images; the Browser hook also reconciles self-updated installs -apt-get install -y fonts-unifont libnss3 libnspr4 libatk1.0-0 libatspi2.0-0 libxcomposite1 libxdamage1 libatk-bridge2.0-0 libcups2 -patchright install chromium --no-shell +# install chromium with dependencies +apt-get update +apt-get install -y --no-install-recommends \ + fonts-unifont libnss3 libnspr4 libatk1.0-0 libatspi2.0-0 \ + libxcomposite1 libxdamage1 libatk-bridge2.0-0 libcups2 +rm -rf /var/lib/apt/lists/* +depfix run -m patchright install chromium --no-shell diff --git a/docker/run/fs/ins/pre_install.sh b/docker/run/fs/ins/pre_install.sh index 8d8b8b521..0b0c43195 100644 --- a/docker/run/fs/ins/pre_install.sh +++ b/docker/run/fs/ins/pre_install.sh @@ -1,9 +1,6 @@ #!/bin/bash set -e -# update apt -apt-get update - # fix permissions for cron files if any if [ -f /etc/cron.d/* ]; then chmod 0644 /etc/cron.d/* diff --git a/docker/run/fs/ins/setup_venv.sh b/docker/run/fs/ins/setup_venv.sh deleted file mode 100644 index 4f43a70fc..000000000 --- a/docker/run/fs/ins/setup_venv.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -set -e - -# this has to be ready from base image -# if [ ! -d /opt/venv ]; then -# # Create and activate Python virtual environment -# python3.12 -m venv /opt/venv -# source /opt/venv/bin/activate -# else - # source /opt/venv/bin/activate -# fi -source /opt/venv-a0/bin/activate \ No newline at end of file diff --git a/docker/run/fs/per/root/.bashrc b/docker/run/fs/per/root/.bashrc index 88a273c5f..98ff87a65 100644 --- a/docker/run/fs/per/root/.bashrc +++ b/docker/run/fs/per/root/.bashrc @@ -4,6 +4,3 @@ if [ -f /etc/bashrc ]; then . /etc/bashrc fi - -# Activate the virtual environment -source /opt/venv/bin/activate diff --git a/docker/run/fs/per/root/.profile b/docker/run/fs/per/root/.profile index 88a273c5f..9ab53c456 100644 --- a/docker/run/fs/per/root/.profile +++ b/docker/run/fs/per/root/.profile @@ -1,9 +1,6 @@ -# .bashrc +# .profile # Source global definitions if [ -f /etc/bashrc ]; then . /etc/bashrc fi - -# Activate the virtual environment -source /opt/venv/bin/activate diff --git a/docs/setup/dev-setup.md b/docs/setup/dev-setup.md index d1390d0de..b8e8c940f 100644 --- a/docs/setup/dev-setup.md +++ b/docs/setup/dev-setup.md @@ -60,7 +60,7 @@ Now when you select one of the python files in the project, you should see prope ![VS Code Python environments](../res/dev/devinst-3.png) ![VS Code Python environments](../res/dev/devinst-4.png) -- Your new environment should be automatically activated. If not, select it in the lower right corner. You might need to open a new terminal in VS Code to reflect the changes with `Terminal > New Terminal` or clicking the `+` button in the terminal tab. Your terminal prompt should now start with your environment name/path, in my case `(/Users/frdel/Desktop/agent-zero/.conda)` This shows the environment is active in the terminal. +- Your new environment should be automatically activated. If not, select it in the lower right corner. You might need to open a new terminal in VS Code to reflect the changes with `Terminal > New Terminal` or clicking the `+` button in the terminal tab. Your terminal prompt should now start with your environment name/path, in my case `(/home/user/agent-zero/.conda)` This shows the environment is active in the terminal. ![VS Code env terminal](../res/dev/devinst-5.png) @@ -75,7 +75,10 @@ The first command installs Python dependencies. The second command installs full Patchright Chromium into `./tmp/playwright`, relative to the project root. Docker images use the absolute path -`/a0/tmp/playwright` and ship Chromium preinstalled. +`/a0/tmp/playwright` and ship Chromium preinstalled. The Docker build differs +from this local-development setup: it materializes `requirements.txt` once in +Depfix's shared store, then invokes the pinned Playwright module through Depfix +to install Chromium without installing the Python package a second time. If you skip the second command, local development can still download Chromium on first Browser use through `ensure_playwright_binary()` in @@ -125,7 +128,7 @@ Some tools like code execution will not work yet because they need to be connect 1. Pull the docker image `agent0ai/agent-zero` from Docker Hub and run it with a web port (`80`) mapped and SSH port (`22`) mapped. If you want, you can also map the `/a0` folder to our local project folder as well, this way we can update our local instance and the docker instance at the same time. -This is how it looks in my example: port `80` is mapped to `8880` on the host and `22` to `8822`, `/a0` folder mapped to `/Users/frdel/Desktop/agent-zero`: +This is how it looks in my example: port `80` is mapped to `8880` on the host and `22` to `8822`, `/a0` folder mapped to `/home/user/agent-zero`: ![docker run](../res/dev/devinst-11.png) ![docker run](../res/dev/devinst-12.png) @@ -139,7 +142,7 @@ This is how it looks in my example: port `80` is mapped to `8880` on the host an 2. Set the `RFC Password` field to a new password and save. 3. Open the "Settings" page in the Web UI of your local instance and go in the "Development" section. 4. Here set the `RFC Password` field to the same password you used in the dockerized instance. Also set the SSH port and HTTP port the same numbers you used when creating the container - in my case `8822` for SSH and `8880` for HTTP. The `RFC Destination URL` will most probably stay `localhost` as both instances are running on the host machine. -5. Click save and test by asking your agent to do something in the terminal, like "Get current OS version". It should be able to communicate with the dockerized instance via RFC and SSH and execute the command there, responding with something like "Kali GNU/Linux Rolling". +5. Click save and test by asking your agent to do something in the terminal, like "Get current OS version". It should be able to communicate with the dockerized instance via RFC and SSH and execute the command there, responding with Debian GNU/Linux 13 (Trixie). My Dockerized instance: ![Dockerized instance](../res/dev/devinst-14.png) diff --git a/docs/setup/installation.md b/docs/setup/installation.md index 2204aec03..d5657b95d 100644 --- a/docs/setup/installation.md +++ b/docs/setup/installation.md @@ -561,7 +561,7 @@ Use `claude-sonnet-4-5` for Anthropic, but use `anthropic/claude-sonnet-4-5` for ### Built-in Voice Plugins - Agent Zero ships Whisper STT as the built-in `_whisper_stt` plugin and Kokoro TTS as the built-in `_kokoro_tts` plugin. -- Docker/bootstrap remains responsible for installing the required speech dependencies such as `ffmpeg`, Kokoro, Whisper, and `soundfile`. +- Docker/bootstrap installs the Whisper, Kokoro, and `soundfile` Python dependencies. Whisper microphone audio is browser-normalized PCM, so the container does not require FFmpeg. - Both plugins can be enabled or disabled independently from the Agent Plugins section in the Web UI. - Whisper model size, language, message handling, and silence behavior are configured from the plugin settings screen. - If `_kokoro_tts` is disabled, spoken output falls back to the browser's native speech synthesis instead of the container runtime. diff --git a/extensions/python/startup_migration/AGENTS.md b/extensions/python/startup_migration/AGENTS.md index de8fc4a93..fe1162b49 100644 --- a/extensions/python/startup_migration/AGENTS.md +++ b/extensions/python/startup_migration/AGENTS.md @@ -19,7 +19,7 @@ - Required updater capabilities include immutable rollback-stash identity (`get_top_stash_oid`), so runtimes using moving stash selectors are upgraded on startup. - Runtime markers also require fast, timestamp-tolerant ZIP backups so existing `/exe` managers receive the backup fixes. - Runtime synchronization also upgrades updaters with the older health timeout to the 600-second default, retaining the environment override. -- After synchronizing a stale self-update manager, `_10_self_update_manager.py` starts that manager's best-effort Codex CLI refresh in the background so the update that introduces the hook does not need a second restart. +- After synchronizing a stale self-update manager, `_10_self_update_manager.py` starts that manager's best-effort Codex CLI refresh through `depfix run` in the background so the fresh process can import application dependencies without needing a second restart. ## Work Guidance diff --git a/extensions/python/startup_migration/_10_self_update_manager.py b/extensions/python/startup_migration/_10_self_update_manager.py index 58f719ac3..accde74f9 100644 --- a/extensions/python/startup_migration/_10_self_update_manager.py +++ b/extensions/python/startup_migration/_10_self_update_manager.py @@ -4,7 +4,6 @@ import os import shutil import stat import subprocess -import sys from pathlib import Path from typing import Any @@ -98,7 +97,7 @@ def ensure_self_update_manager_runtime_current( def start_codex_cli_refresh(manager_path: Path | str) -> str: try: subprocess.Popen( - [sys.executable, str(manager_path), "refresh-codex"], + ["depfix", "run", str(manager_path), "refresh-codex"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, diff --git a/helpers/docker.py b/helpers/docker.py index a95aaee37..d3f6b34ee 100644 --- a/helpers/docker.py +++ b/helpers/docker.py @@ -1,99 +1,101 @@ -import time -import docker -import atexit -from typing import Optional -from helpers.files import get_abs_path -from helpers.errors import format_error -from helpers.print_style import PrintStyle -from helpers.log import Log +# not used anymore -class DockerContainerManager: - def __init__(self, image: str, name: str, ports: Optional[dict[str, int]] = None, volumes: Optional[dict[str, dict[str, str]]] = None,logger: Log|None=None): - self.logger = logger - self.image = image - self.name = name - self.ports = ports - self.volumes = volumes - self.init_docker() +# import time +# import docker +# import atexit +# from typing import Optional +# from helpers.files import get_abs_path +# from helpers.errors import format_error +# from helpers.print_style import PrintStyle +# from helpers.log import Log + +# class DockerContainerManager: +# def __init__(self, image: str, name: str, ports: Optional[dict[str, int]] = None, volumes: Optional[dict[str, dict[str, str]]] = None,logger: Log|None=None): +# self.logger = logger +# self.image = image +# self.name = name +# self.ports = ports +# self.volumes = volumes +# self.init_docker() - def init_docker(self): - self.client = None - while not self.client: - try: - self.client = docker.from_env() - self.container = None - except Exception as e: - err = format_error(e) - if ("ConnectionRefusedError(61," in err or "Error while fetching server API version" in err): - PrintStyle.hint("Connection to Docker failed. Is docker or Docker Desktop running?") # hint for user - if self.logger:self.logger.log(type="hint", content="Connection to Docker failed. Is docker or Docker Desktop running?") - PrintStyle.error(err) - if self.logger:self.logger.log(type="error", content=err) - time.sleep(5) # try again in 5 seconds - else: raise - return self.client +# def init_docker(self): +# self.client = None +# while not self.client: +# try: +# self.client = docker.from_env() +# self.container = None +# except Exception as e: +# err = format_error(e) +# if ("ConnectionRefusedError(61," in err or "Error while fetching server API version" in err): +# PrintStyle.hint("Connection to Docker failed. Is docker or Docker Desktop running?") # hint for user +# if self.logger:self.logger.log(type="hint", content="Connection to Docker failed. Is docker or Docker Desktop running?") +# PrintStyle.error(err) +# if self.logger:self.logger.log(type="error", content=err) +# time.sleep(5) # try again in 5 seconds +# else: raise +# return self.client - def cleanup_container(self) -> None: - if self.container: - try: - self.container.stop() - self.container.remove() - PrintStyle.standard(f"Stopped and removed the container: {self.container.id}") - if self.logger: self.logger.log(type="info", content=f"Stopped and removed the container: {self.container.id}") - except Exception as e: - PrintStyle.error(f"Failed to stop and remove the container: {e}") - if self.logger: self.logger.log(type="error", content=f"Failed to stop and remove the container: {e}") +# def cleanup_container(self) -> None: +# if self.container: +# try: +# self.container.stop() +# self.container.remove() +# PrintStyle.standard(f"Stopped and removed the container: {self.container.id}") +# if self.logger: self.logger.log(type="info", content=f"Stopped and removed the container: {self.container.id}") +# except Exception as e: +# PrintStyle.error(f"Failed to stop and remove the container: {e}") +# if self.logger: self.logger.log(type="error", content=f"Failed to stop and remove the container: {e}") - def get_image_containers(self): - if not self.client: self.client = self.init_docker() - containers = self.client.containers.list(all=True, filters={"ancestor": self.image}) - infos = [] - for container in containers: - infos.append({ - "id": container.id, - "name": container.name, - "status": container.status, - "image": container.image, - "ports": container.ports, - "web_port": (container.ports.get("80/tcp") or [{}])[0].get("HostPort"), - "ssh_port": (container.ports.get("22/tcp") or [{}])[0].get("HostPort"), - # "volumes": container.volumes, - # "data_folder": container.volumes["/a0"], - }) - return infos +# def get_image_containers(self): +# if not self.client: self.client = self.init_docker() +# containers = self.client.containers.list(all=True, filters={"ancestor": self.image}) +# infos = [] +# for container in containers: +# infos.append({ +# "id": container.id, +# "name": container.name, +# "status": container.status, +# "image": container.image, +# "ports": container.ports, +# "web_port": (container.ports.get("80/tcp") or [{}])[0].get("HostPort"), +# "ssh_port": (container.ports.get("22/tcp") or [{}])[0].get("HostPort"), +# # "volumes": container.volumes, +# # "data_folder": container.volumes["/a0"], +# }) +# return infos - def start_container(self) -> None: - if not self.client: self.client = self.init_docker() - existing_container = None - for container in self.client.containers.list(all=True): - if container.name == self.name: - existing_container = container - break +# def start_container(self) -> None: +# if not self.client: self.client = self.init_docker() +# existing_container = None +# for container in self.client.containers.list(all=True): +# if container.name == self.name: +# existing_container = container +# break - if existing_container: - if existing_container.status != 'running': - PrintStyle.standard(f"Starting existing container: {self.name} for safe code execution...") - if self.logger: self.logger.log(type="info", content=f"Starting existing container: {self.name} for safe code execution...") +# if existing_container: +# if existing_container.status != 'running': +# PrintStyle.standard(f"Starting existing container: {self.name} for safe code execution...") +# if self.logger: self.logger.log(type="info", content=f"Starting existing container: {self.name} for safe code execution...") - existing_container.start() - self.container = existing_container - time.sleep(2) # this helps to get SSH ready +# existing_container.start() +# self.container = existing_container +# time.sleep(2) # this helps to get SSH ready - else: - self.container = existing_container - # PrintStyle.standard(f"Container with name '{self.name}' is already running with ID: {existing_container.id}") - else: - PrintStyle.standard(f"Initializing docker container {self.name} for safe code execution...") - if self.logger: self.logger.log(type="info", content=f"Initializing docker container {self.name} for safe code execution...") +# else: +# self.container = existing_container +# # PrintStyle.standard(f"Container with name '{self.name}' is already running with ID: {existing_container.id}") +# else: +# PrintStyle.standard(f"Initializing docker container {self.name} for safe code execution...") +# if self.logger: self.logger.log(type="info", content=f"Initializing docker container {self.name} for safe code execution...") - self.container = self.client.containers.run( - self.image, - detach=True, - ports=self.ports, # type: ignore - name=self.name, - volumes=self.volumes, # type: ignore - ) - # atexit.register(self.cleanup_container) - PrintStyle.standard(f"Started container with ID: {self.container.id}") - if self.logger: self.logger.log(type="info", content=f"Started container with ID: {self.container.id}") - time.sleep(5) # this helps to get SSH ready +# self.container = self.client.containers.run( +# self.image, +# detach=True, +# ports=self.ports, # type: ignore +# name=self.name, +# volumes=self.volumes, # type: ignore +# ) +# # atexit.register(self.cleanup_container) +# PrintStyle.standard(f"Started container with ID: {self.container.id}") +# if self.logger: self.logger.log(type="info", content=f"Started container with ID: {self.container.id}") +# time.sleep(5) # this helps to get SSH ready diff --git a/helpers/duckduckgo_search.py b/helpers/duckduckgo_search.py index b97497c27..855550c3a 100644 --- a/helpers/duckduckgo_search.py +++ b/helpers/duckduckgo_search.py @@ -1,30 +1,18 @@ -# from langchain_community.utilities import DuckDuckGoSearchAPIWrapper +# not used anymore -# def search(query: str, results = 5, region = "wt-wt", time="y") -> str: -# # Create an instance with custom parameters -# api = DuckDuckGoSearchAPIWrapper( -# region=region, # Set the region for search results -# safesearch="off", # Set safesearch level (options: strict, moderate, off) -# time=time, # Set time range (options: d, w, m, y) -# max_results=results # Set maximum number of results to return +# from duckduckgo_search import DDGS + +# def search(query: str, results = 5, region = "wt-wt", time="y") -> list[str]: + +# ddgs = DDGS() +# src = ddgs.text( +# query, +# region=region, # Specify region +# safesearch="off", # SafeSearch setting +# timelimit=time, # Time limit (y = past year) +# max_results=results # Number of results to return # ) -# # Perform a search -# result = api.run(query) -# return result - -from duckduckgo_search import DDGS - -def search(query: str, results = 5, region = "wt-wt", time="y") -> list[str]: - - ddgs = DDGS() - src = ddgs.text( - query, - region=region, # Specify region - safesearch="off", # SafeSearch setting - timelimit=time, # Time limit (y = past year) - max_results=results # Number of results to return - ) - results = [] - for s in src: - results.append(str(s)) - return results \ No newline at end of file +# results = [] +# for s in src: +# results.append(str(s)) +# return results \ No newline at end of file diff --git a/helpers/searxng.py b/helpers/searxng.py deleted file mode 100644 index b325ee76c..000000000 --- a/helpers/searxng.py +++ /dev/null @@ -1,12 +0,0 @@ -import aiohttp -from helpers import runtime - -URL = "http://localhost:55510/search" - -async def search(query:str): - return await runtime.call_development_function(_search, query=query) - -async def _search(query:str): - async with aiohttp.ClientSession() as session: - async with session.post(URL, data={"q": query, "format": "json"}) as response: - return await response.json() diff --git a/helpers/searxng.py.dox.md b/helpers/searxng.py.dox.md deleted file mode 100644 index 889e62df1..000000000 --- a/helpers/searxng.py.dox.md +++ /dev/null @@ -1,43 +0,0 @@ -# searxng.py DOX - -## Purpose - -- Own the `searxng.py` helper module. -- This module queries SearXNG search. -- Keep this file-level DOX profile synchronized with `searxng.py` because this directory is intentionally flat. - -## Ownership - -- `searxng.py` owns the runtime implementation. -- `searxng.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation. -- Top-level functions: -- `async search(query: str)` -- `async _search(query: str)` -- Notable constants/configuration names: `URL`. - -## Runtime Contracts - -- Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together. -- Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change. -- Observed side-effect areas: network calls, settings/state persistence. -- Imported dependency areas include: `aiohttp`, `helpers`. - -## Key Concepts - -- Important called helpers/classes observed in the source: `runtime.call_development_function`, `aiohttp.ClientSession`, `session.post`, `response.json`. -- Keep request/response, tool, or helper semantics documented here at the same time as source changes. - -## Work Guidance - -- Preserve public helper APIs used by core code and plugins unless every caller is updated. -- Keep path, auth, secret, persistence, network, and subprocess behavior explicit and bounded. -- Prefer adding cohesive helper functions here only when behavior is reused across modules. - -## Verification - -- Run targeted tests for changed helper behavior; run security regressions for auth, filesystem, WebSocket, tunnel, upload, or secret-handling helpers. -- No direct test reference was found by name search; choose the nearest behavioral test or perform a focused smoke check. - -## Child DOX Index - -No child DOX files. diff --git a/plugins/AGENTS.md b/plugins/AGENTS.md index acbac1230..f43df4fa3 100644 --- a/plugins/AGENTS.md +++ b/plugins/AGENTS.md @@ -28,7 +28,7 @@ - `webui/config.html` settings UIs must bind plugin values to `config.*` and modal state/actions to `context.*` through `$store.pluginSettingsPrototype`. - Plugin model provider overrides belong in plugin `conf/model_providers.yaml` and merge after base `conf/model_providers.yaml`. - Global and scoped activation are independent and use `.toggle-1` and `.toggle-0`; `always_enabled: true` forces ON and disables UI toggles. -- `hooks.py` runs in the framework runtime. Explicitly target another runtime if a plugin must prepare the agent execution environment. +- `hooks.py` runs in the global Docker Python environment. Explicitly target an isolated sandbox or the operating system when a plugin must prepare those environments. - `execute.py` is manual user-triggered setup, maintenance, repair, migration, or refresh work; automatic framework behavior belongs in hooks or lifecycle extensions. - Plugin routes are `GET /plugins//`, `POST /api/plugins//`, and `POST /api/plugins` for management actions. - `_a0_connector` WebSocket history replay must stay bounded: emit large chat history as paged `connector_context_snapshot` payloads, keep `last_sequence` as the Agent Zero log-output cursor, and avoid sending an entire long transcript in one frame. @@ -106,6 +106,8 @@ Direct child DOX files: | [_scheduler/AGENTS.md](_scheduler/AGENTS.md) | Scheduler agent tool, Scheduled Tasks WebUI, CRUD API endpoints, and sidebar task list. | | [_search_engine/AGENTS.md](_search_engine/AGENTS.md) | Live web search tool via local SearXNG. | | [_sidebar_folders/AGENTS.md](_sidebar_folders/AGENTS.md) | Project folder presentation, filters, sorting, drag ordering, and chat project moves. | +| [_sandboxing/AGENTS.md](_sandboxing/AGENTS.md) | Direct gVisor sandbox lifecycle, runtime OCI image cache, execution destinations, and management UI. | +| [_searxng/AGENTS.md](_searxng/AGENTS.md) | Disabled SearXNG search placeholder and historical sandbox-reimplementation notes. | | [_skills/AGENTS.md](_skills/AGENTS.md) | Active and hidden skill configuration and prompt injection. | | [_telegram_integration/AGENTS.md](_telegram_integration/AGENTS.md) | Telegram bot integration and per-user chat sessions. | | [_text_editor/AGENTS.md](_text_editor/AGENTS.md) | Native text read, write, and patch tool. | diff --git a/plugins/README.md b/plugins/README.md index e490f54db..ff967d942 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -66,9 +66,9 @@ Plugins can also include an optional `hooks.py` at the plugin root. The framewor - `hooks.py` runs inside the **Agent Zero framework runtime and Python environment**. - Use it for framework-internal work such as install hooks, cache preparation, registration, or filesystem setup. - If it runs `sys.executable -m pip install ...`, packages are installed into the same Python environment that runs Agent Zero. -- If you need to install into the separate agent runtime or into the system environment, explicitly target that environment from a subprocess by selecting the correct interpreter, virtualenv, or package manager. +- If you need to install into an isolated task sandbox or into the system environment, explicitly target that destination from a subprocess by selecting its interpreter or package manager. -In Docker, `hooks.py` normally affects `/opt/venv-a0`; the agent execution runtime is `/opt/venv`. +In Docker, `hooks.py` and local Python execution share the official image's global Python environment; sandbox destinations retain their own environments. ### Configuration Hook Context diff --git a/plugins/_browser/AGENTS.md b/plugins/_browser/AGENTS.md index f2c79c67b..9793bb36e 100644 --- a/plugins/_browser/AGENTS.md +++ b/plugins/_browser/AGENTS.md @@ -77,6 +77,7 @@ - `hooks.install()` also installs HTTPX's SOCKS extra in the framework runtime when `socksio` is missing; this supports shared HTTP clients using proxy environment variables independently of Chromium's proxy settings. - Browser startup must install the shared virtual-desktop route hook itself; do not make Browser depend on the Desktop plugin being enabled. - Use shared `surface-workspace`, toolbar/control, and separator styles from `webui/css/surfaces.css`; match the lighter Files/Browser panel palette and preserve disabled, active, and keyboard focus states. +- When Chromium is absent, the runtime fallback invokes Patchright as a module through `depfix run`; do not assume the Patchright console script is on ordinary `PATH`. ## Work Guidance diff --git a/plugins/_browser/helpers/playwright.py b/plugins/_browser/helpers/playwright.py index 4878adca0..ad732f636 100644 --- a/plugins/_browser/helpers/playwright.py +++ b/plugins/_browser/helpers/playwright.py @@ -104,7 +104,7 @@ def ensure_playwright_binary() -> Path: env = os.environ.copy() env["PLAYWRIGHT_BROWSERS_PATH"] = cache_dir subprocess.check_call( - [sys.executable, "-m", "patchright", "install", "chromium", "--no-shell"], + ["depfix", "run", "-m", "patchright", "install", "chromium", "--no-shell"], env=env, ) diff --git a/plugins/_code_execution/AGENTS.md b/plugins/_code_execution/AGENTS.md index 21991ae4e..b71068b1e 100644 --- a/plugins/_code_execution/AGENTS.md +++ b/plugins/_code_execution/AGENTS.md @@ -2,7 +2,7 @@ ## Purpose -- Own terminal, Python, and Node.js code execution through persistent local or SSH-backed sessions. +- Own terminal, Python, and Node.js code execution through destination-aware persistent sessions. ## Ownership @@ -29,7 +29,10 @@ - Explicitly target local versus SSH execution runtimes. - The `input` tool logs a prefix-free `icon://keyboard Using tool 'input'` heading and forwards keyboard input through the code execution tool and its log. - The tool's `allow_running` flag is framework-set (for example by the `input` tool's terminal dispatch); it is not a model-facing arg and stays undocumented in prompts. +- Keep `destination=default` isolated through registered destination extensions; `local` means the Agent Zero operating system, and connected-host routing reuses the authenticated connector transport. +- Key persistent sessions by destination and session id so output, input, and reset cannot cross execution boundaries. - Do not hardcode secrets, SSH credentials, or local user paths. +- Local Python snippets run IPython through `depfix run` so imports can use packages materialized in the shared Depfix store; sandbox Python remains owned by the sandbox image. ## Work Guidance diff --git a/plugins/_code_execution/helpers/destinations.py b/plugins/_code_execution/helpers/destinations.py new file mode 100644 index 000000000..967a28cd0 --- /dev/null +++ b/plugins/_code_execution/helpers/destinations.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Literal + +from helpers.extension import call_extensions_async + + +DestinationKind = Literal["local", "sandbox", "host"] + + +@dataclass(frozen=True, slots=True) +class ExecutionDestination: + id: str + kind: DestinationKind + label: str + description: str + target: str = "" + status: str = "available" + + +async def get_code_execution_destinations(agent: Any) -> list[ExecutionDestination]: + destinations = [ + ExecutionDestination( + id="local", + kind="local", + label="Agent Zero system", + description="The operating system running Agent Zero; use only for Agent Zero itself or its core files.", + ) + ] + await call_extensions_async( + "code_execution_destinations", + agent=agent, + destinations=destinations, + ) + unique: dict[str, ExecutionDestination] = {} + for destination in destinations: + if destination.id and destination.id not in unique: + unique[destination.id] = destination + return list(unique.values()) + + +async def resolve_code_execution_destination( + agent: Any, requested: str +) -> ExecutionDestination: + requested = str(requested or "default").strip() or "default" + destinations = await get_code_execution_destinations(agent) + for destination in destinations: + if destination.id == requested: + return destination + + if requested in {"local", "host", "default"}: + raise ValueError(f"Code execution destination is not currently available: {requested}") + + # Named sandboxes are intentionally lazy: a missing one is created when its + # first shell connects. The sandbox plugin still validates the exact name. + try: + from plugins._sandboxing.helpers.manager import validate_name + + sandbox_name = requested.split(":", 1)[1] if requested.startswith("sandbox:") else requested + validate_name(sandbox_name) + except (ImportError, IndexError, ValueError, RuntimeError) as exc: + raise ValueError(f"Unknown code execution destination: {requested}") from exc + return ExecutionDestination( + id=requested, + kind="sandbox", + target=sandbox_name, + label=f"Sandbox {sandbox_name}", + description="A gVisor sandbox that will be created or woken on first use.", + status="missing", + ) diff --git a/plugins/_code_execution/prompts/agent.system.tool.code_exe.md b/plugins/_code_execution/prompts/agent.system.tool.code_exe.md index 7a851308b..681d107ce 100644 --- a/plugins/_code_execution/prompts/agent.system.tool.code_exe.md +++ b/plugins/_code_execution/prompts/agent.system.tool.code_exe.md @@ -2,11 +2,14 @@ run terminal, python, or nodejs commands args: - `runtime`: `terminal`, `python`, `nodejs`, or `output` +- `destination`: execution target from EXTRAS; default `default` - `code`: command or script code - `session`: terminal session id; default `0` - `reset`: kill a session before running; `true` or `false` rules: - place the command or script in `code` +- use `destination=default` for ordinary isolated work; use `destination=local` only to inspect or modify Agent Zero itself +- keep the same `destination` for a session's commands, output polls, interactive input, and reset - use `runtime=output` to poll running work - use `input` for interactive terminal prompts - if a session is stuck, call again with the same `session` and `reset=true` diff --git a/plugins/_code_execution/prompts/agent.system.tool.input.md b/plugins/_code_execution/prompts/agent.system.tool.input.md index c87f845ed..c98f34eee 100644 --- a/plugins/_code_execution/prompts/agent.system.tool.input.md +++ b/plugins/_code_execution/prompts/agent.system.tool.input.md @@ -2,6 +2,7 @@ send keyboard input to an interactive terminal program use keyboard arg for terminal program input use session arg for terminal session number +use the same destination as the terminal session; default is `default` answer dialogues enter passwords etc not for browser usage: @@ -14,7 +15,8 @@ usage: "tool_name": "input", "tool_args": { "keyboard": "Y", - "session": 0 + "session": 0, + "destination": "default" } } ~~~ diff --git a/plugins/_code_execution/tools/code_execution_tool.py b/plugins/_code_execution/tools/code_execution_tool.py index 9732cd4fc..8a6d110f8 100644 --- a/plugins/_code_execution/tools/code_execution_tool.py +++ b/plugins/_code_execution/tools/code_execution_tool.py @@ -4,6 +4,7 @@ from dataclasses import dataclass import re import shlex import time +from typing import Any from helpers.tool import Tool, Response, coerce_bool from helpers import files, rfc_exchange, projects, runtime, secrets, settings @@ -14,6 +15,10 @@ from helpers import plugins from plugins._code_execution.helpers.shell_local import LocalInteractiveSession from plugins._code_execution.helpers.shell_ssh import SSHInteractiveSession +from plugins._code_execution.helpers.destinations import ( + ExecutionDestination, + resolve_code_execution_destination, +) def _is_closed_pty_error(exc: BaseException) -> bool: @@ -40,14 +45,14 @@ def _group_multiline_command(command: str, powershell: bool = False) -> str: @dataclass class ShellWrap: id: int - session: LocalInteractiveSession | SSHInteractiveSession + session: Any running: bool @dataclass class State: ssh_enabled: bool - shells: dict[int, ShellWrap] + shells: dict[int | str, ShellWrap] class CodeExecution(Tool): @@ -67,11 +72,37 @@ class CodeExecution(Tool): async def _execute(self, job) -> Response: await self.agent.handle_intervention() # wait for intervention and handle it, if paused - runtime_arg = self.args.get("runtime", "").lower().strip() + runtime_arg = str(self.args.get("runtime", "")).lower().strip() session = int(self.args.get("session", 0)) self.allow_running = coerce_bool(self.args.get("allow_running", False), False) reset = coerce_bool(self.args.get("reset", False), False) or runtime_arg == "reset" + requested_destination = str(self.args.get("destination", "default") or "default") + try: + self.destination = await resolve_code_execution_destination( + self.agent, requested_destination + ) + except ValueError as exc: + return Response(message=str(exc), break_loop=False) + + if self.destination.kind == "host": + from plugins._a0_connector.tools.code_execution_remote import ( + CodeExecutionRemote, + ) + + remote_args = dict(self.args) + remote_args.pop("destination", None) + remote = CodeExecutionRemote( + self.agent, + "code_execution_remote", + "", + remote_args, + self.message, + self.loop_data, + ) + remote.log = self.log + return await remote.execute(**remote_args) + cfg = _get_config(self.agent) if runtime_arg == "python": @@ -98,7 +129,7 @@ class CodeExecution(Tool): ) if job and runtime_arg in {"terminal", "python", "nodejs"}: - while self.state.shells[session].running: + while self._shell_wrap(session).running: job.result = response response = await self.get_terminal_output( cfg, session=session, reset_full_output=False, @@ -125,7 +156,8 @@ class CodeExecution(Tool): if not text: text = f"{self.name} - {self.args['runtime'] if 'runtime' in self.args else 'unknown'}" session = self.args.get("session", None) - session_text = f"[{session}] " if session or session == 0 else "" + destination = str(self.args.get("destination", "default") or "default") + session_text = f"[{destination}/{session}] " if session or session == 0 else "" return f"icon://terminal {session_text}{truncate_text_string(text, 200)}" async def after_execution(self, response, **kwargs): @@ -134,27 +166,40 @@ class CodeExecution(Tool): async def prepare_state(self, cfg: dict, reset=False, session: int | None = None): self.state: State | None = self.agent.get_data("_cet_state") ssh_enabled = cfg["ssh_enabled"] + destination = self._destination() # always reset state when ssh_enabled changes if not self.state or self.state.ssh_enabled != ssh_enabled: - shells: dict[int, ShellWrap] = {} + if self.state: + for wrapper in self.state.shells.values(): + await wrapper.session.close() + shells: dict[int | str, ShellWrap] = {} else: shells = self.state.shells.copy() + key = self._session_key(session) if session is not None else None + # Only reset the specified session if provided - if reset and session is not None and session in shells: - await shells[session].session.close() - del shells[session] - elif reset and not session: + if reset and key is not None and key in shells: + await shells[key].session.close() + del shells[key] + elif reset and session is None: # Close all sessions if full reset requested for s in list(shells.keys()): await shells[s].session.close() shells = {} # initialize local or remote interactive shell interface for session if needed - if session is not None and session not in shells: - cwd = await self.ensure_cwd() - if ssh_enabled: + if session is not None and key not in shells: + if destination.kind == "sandbox": + from plugins._sandboxing.helpers.shell import SandboxInteractiveSession + + shell = SandboxInteractiveSession( + destination.target, + agent=self.agent, + ) + elif destination.kind == "local" and ssh_enabled: + cwd = await self.ensure_cwd() ssh_pass = await _resolve_ssh_pass(cfg["ssh_pass"]) shell = SSHInteractiveSession( self.agent.context.log, @@ -165,9 +210,10 @@ class CodeExecution(Tool): cwd=cwd, ) else: + cwd = await self.ensure_cwd() shell = LocalInteractiveSession(cwd=cwd) - shells[session] = ShellWrap(id=session, session=shell, running=False) + shells[key] = ShellWrap(id=session, session=shell, running=False) try: await shell.connect() except BaseException: @@ -180,13 +226,22 @@ class CodeExecution(Tool): async def execute_python_code(self, cfg: dict, session: int, code: str, reset: bool = False): escaped_code = shlex.quote(code) - command = f"ipython -c {escaped_code}" + runner = ( + "depfix run -m IPython --" + if self._destination().kind == "local" + else "ipython" + ) + command = f"{runner} -c {escaped_code}" prefix = "python> " + self.format_command_for_output(code) + "\n\n" return await self.terminal_session(cfg, session, command, reset, prefix) async def execute_nodejs_code(self, cfg: dict, session: int, code: str, reset: bool = False): escaped_code = shlex.quote(code) - command = f"node /exe/node_eval.js {escaped_code}" + command = ( + f"node -e {escaped_code}" + if self._destination().kind == "sandbox" + else f"node /exe/node_eval.js {escaped_code}" + ) prefix = "node> " + self.format_command_for_output(code) + "\n\n" return await self.terminal_session(cfg, session, command, reset, prefix) @@ -194,12 +249,23 @@ class CodeExecution(Tool): self, cfg: dict, session: int, command: str, reset: bool = False ): prefix = ( - ("bash>" if not runtime.is_windows() or cfg["ssh_enabled"] else "PS>") + ( + "bash>" + if self._destination().kind == "sandbox" + or not runtime.is_windows() + or cfg["ssh_enabled"] + else "PS>" + ) + self.format_command_for_output(command) + "\n\n" ) command = _group_multiline_command( - command, powershell=runtime.is_windows() and not cfg["ssh_enabled"] + command, + powershell=( + self._destination().kind == "local" + and runtime.is_windows() + and not cfg["ssh_enabled"] + ), ) return await self.terminal_session(cfg, session, command, reset, prefix) @@ -217,24 +283,17 @@ class CodeExecution(Tool): # A strict-mode command can terminate the persistent shell itself. # Recreate such a session lazily before accepting the next command. - if self.state.shells[session].session.is_terminated(): + if self._shell_wrap(session).session.is_terminated(): await self.prepare_state(cfg, reset=True, session=session) # try again on lost connection for i in range(2): try: - self.state.shells[session].running = True - await self.state.shells[session].session.send_command(command) + wrapper = self._shell_wrap(session) + wrapper.running = True + await wrapper.session.send_command(command) - locl = ( - " (local)" - if isinstance(self.state.shells[session].session, LocalInteractiveSession) - else ( - " (remote)" - if isinstance(self.state.shells[session].session, SSHInteractiveSession) - else " (unknown)" - ) - ) + locl = f" ({self._destination().id})" PrintStyle( background_color="white", font_color="#1B4F72", bold=True @@ -299,7 +358,7 @@ class CodeExecution(Tool): while True: await asyncio.sleep(sleep_time) try: - full_output, partial_output = await self.state.shells[session].session.read_output( + full_output, partial_output = await self._shell_wrap(session).session.read_output( timeout=1, reset_full_output=reset_full_output ) except Exception as e: @@ -328,7 +387,7 @@ class CodeExecution(Tool): # ``set -e``, ``exit``, or a lost SSH channel can end the managed # shell without ever producing another prompt. Treat that process # or channel termination as a definitive command end. - shell = self.state.shells[session].session + shell = self._shell_wrap(session).session if shell.is_terminated(): exit_code = shell.get_exit_code() status = f" with exit code {exit_code}" if exit_code is not None else "" @@ -439,16 +498,17 @@ class CodeExecution(Tool): reset_full_output=True, prefix="" ): - if not self.state or session not in self.state.shells: + key = self._session_key(session) + if not self.state or key not in self.state.shells: return None - if not self.state.shells[session].running: + if not self.state.shells[key].running: return None prompt_patterns = cfg["prompt_patterns"] dialog_patterns = cfg["dialog_patterns"] try: - full_output, _ = await self.state.shells[session].session.read_output( + full_output, _ = await self.state.shells[key].session.read_output( timeout=1, reset_full_output=reset_full_output ) except Exception as e: @@ -461,7 +521,7 @@ class CodeExecution(Tool): await self.set_progress(truncated_output) heading = self.get_heading_from_output(truncated_output, 0) - if self.state.shells[session].session.is_terminated(): + if self.state.shells[key].session.is_terminated(): self.mark_session_idle(session) return None @@ -500,8 +560,9 @@ class CodeExecution(Tool): return response def mark_session_idle(self, session: int = 0): - if self.state and session in self.state.shells: - self.state.shells[session].running = False + key = self._session_key(session) + if self.state and key in self.state.shells: + self.state.shells[key].running = False async def reset_terminal(self, cfg: dict, session=0, reason: str | None = None): if reason: @@ -540,6 +601,28 @@ class CodeExecution(Tool): output = truncate_text_agent(agent=self.agent, output=output, threshold=1000000) return output + def _destination(self) -> ExecutionDestination: + destination = getattr(self, "destination", None) + if isinstance(destination, ExecutionDestination): + return destination + return ExecutionDestination( + id="local", + kind="local", + label="Agent Zero system", + description="Local compatibility destination.", + ) + + def _session_key(self, session: int | None) -> int | str: + if session is None: + raise ValueError("session is required") + destination = self._destination() + return session if destination.id == "local" else f"{destination.id}:{session}" + + def _shell_wrap(self, session: int) -> ShellWrap: + if not self.state: + raise RuntimeError("Code execution state is not prepared") + return self.state.shells[self._session_key(session)] + async def ensure_cwd(self) -> str | None: project_name = projects.get_context_project_name(self.agent.context) if project_name: diff --git a/plugins/_code_execution/tools/input.py b/plugins/_code_execution/tools/input.py index fe15868f2..87a3755bf 100644 --- a/plugins/_code_execution/tools/input.py +++ b/plugins/_code_execution/tools/input.py @@ -11,9 +11,25 @@ class Input(Tool): # terminal session number session = int(self.args.get("session", 0)) + destination = str(self.args.get("destination", "default") or "default") # forward keyboard input to code execution tool - args = {"runtime": "terminal", "code": keyboard, "session": session, "allow_running": True} + args = ( + { + "runtime": "input", + "keyboard": keyboard, + "session": session, + "destination": destination, + } + if destination == "host" + else { + "runtime": "terminal", + "code": keyboard, + "session": session, + "allow_running": True, + "destination": destination, + } + ) cet = CodeExecution(self.agent, "code_execution_tool", "", args, self.message, self.loop_data) cet.log = self.log return await cet.execute(**args) @@ -23,4 +39,4 @@ class Input(Tool): return self.agent.context.log.log(type="code_exe", heading=f"icon://keyboard Using tool '{self.name}'", content="", kvps=self.args, id=str(uuid.uuid4())) async def after_execution(self, response, **kwargs): - self.agent.hist_add_tool_result(self.name, response.message, id=self.log.id if self.log else "", **(response.additional or {})) \ No newline at end of file + self.agent.hist_add_tool_result(self.name, response.message, id=self.log.id if self.log else "", **(response.additional or {})) diff --git a/plugins/_document_query/AGENTS.md b/plugins/_document_query/AGENTS.md index 3cccf3c24..5ff5d1294 100644 --- a/plugins/_document_query/AGENTS.md +++ b/plugins/_document_query/AGENTS.md @@ -10,6 +10,7 @@ - The tool logs its message as type `document_query` with an `icon://manage_search Querying: ` headline when queries are supplied and `Reading: ` without them, naming the first file and appending `+ N more` for multiple documents; `extensions/webui/get_message_handler/` owns the `DOC` badge presentation and `extensions/webui/get_process_step_types/` registers the type. - Agent-facing error messages render from `prompts/fw.document_query.*.md`, and the Q&A answer streams into the tool log while the model writes it. - `helpers/` owns fetching, parser routing, indexing, and query orchestration. +- `helpers/ocr_dependencies.py` owns concurrency-safe, just-in-time installation of legacy OCR system packages. - `prompts/` owns document-query tool and optimization prompts. - `hooks.py`, `default_config.yaml`, `plugin.yaml`, `skills/`, `extensions/`, and `webui/` own dependency bootstrap, settings, metadata, skill guidance, hooks, and UI. @@ -17,16 +18,20 @@ - Respect configured size, timeout, retry, parser concurrency, and OCR limits. - Fetch local and remote resources safely and avoid leaking document contents beyond intended prompt/tool use. -- Keep optional dependency installation targeted to the framework runtime. +- Keep optional Python dependency installation targeted to the current global Docker Python interpreter. +- Keep Tesseract, its Latin language data, and Poppler out of the base image. Install Tesseract immediately before a system-backed image OCR call and add Poppler only for a PDF OCR fallback. +- LiteParse uses its bundled OCR implementation and must not trigger installation of the legacy system OCR packages. +- The crash-isolated LiteParse worker starts through `depfix run` so a fresh interpreter can import the Depfix-managed application graph. ## Work Guidance - Coordinate parser changes with timeout handling and fallback behavior. +- Keep on-demand apt work noninteractive, serialized across parser threads, retry-safe around apt locks, and explicit when privilege or package installation fails. - Keep prompt and skill guidance clear that image files, screenshots, scans, charts, photos, and diagrams should go to vision tools first when available; `document_query` image OCR is a text-focused fallback when vision is unavailable or cannot read the needed text. ## Verification -- Smoke-test representative PDF, text/HTML, image/OCR, and remote-document queries after parser changes. +- Smoke-test representative PDF, text/HTML, image/OCR, and remote-document queries after parser changes, including first-use OCR installation in a clean runtime image. ## Child DOX Index diff --git a/plugins/_document_query/README.md b/plugins/_document_query/README.md index dfa306b73..d70588e75 100644 --- a/plugins/_document_query/README.md +++ b/plugins/_document_query/README.md @@ -36,23 +36,44 @@ See default_config.yaml for all options. Key settings: | liteparse_ocr_auto_disable_pages | 30 | Disable OCR for PDFs at or above this effective page count | | thread_offload | true | Offload sync parsers to thread pool | -LiteParse is installed into the Agent Zero framework runtime from hooks.py during +LiteParse is installed into the shared Agent Zero Python runtime from hooks.py during plugin install/startup. If installation fails, the plugin logs the error and continues with the legacy parser fallbacks. LiteParse always runs in a child process so native parser and OCR failures stay isolated from the Web UI process. +## On-demand system OCR dependencies + +The outer Agent Zero base image does not include Tesseract or Poppler. LiteParse +2.0.3 has its own bundled Tesseract backend, so its normal parsing path does not +need the operating-system packages. + +The legacy fallbacks install only what they are about to use: + +- Embedded-image OCR in `PdfParser` and image OCR through Unstructured install + `tesseract-ocr` and `tesseract-ocr-script-latn` immediately before the first + system Tesseract call. +- Full-page PDF OCR installs those packages plus `poppler-utils` immediately + before `pdf2image` renders pages for Tesseract. + +Installation uses noninteractive apt, is serialized across parser threads, and +waits out transient apt/dpkg locks. Already-installed commands and packages are +reused. A first fallback OCR request can therefore take longer; later requests +reuse the installed runtime packages. On systems without apt or without root or +non-interactive sudo access, only the fallback request fails with an actionable +error. Normal parsing remains unaffected. + ## Parsers | Parser | MIME Types | Backend | |--------|-----------|---------| | LiteParseParser | PDF, Office/OpenDocument, images | LiteParse | -| PdfParser | application/pdf | PyMuPDF + Tesseract OCR fallback | +| PdfParser | application/pdf | PyMuPDF + on-demand Tesseract/Poppler OCR fallback | | HtmlParser | text/html | Markdownify transformer | | TextParser | text/*, application/json, YAML, XML, TOML, JS, TS, shell | Direct read | -| ImageParser | image/* | UnstructuredLoader | -| UnstructuredParser | * (catch-all) | UnstructuredLoader hi-res | +| ImageParser | image/* | Unstructured local partitioner + on-demand Tesseract | +| UnstructuredParser | * (catch-all) | Unstructured local partitioner, hi-res strategy; OCR system packages on demand | ## Adding a new parser diff --git a/plugins/_document_query/helpers/ocr_dependencies.py b/plugins/_document_query/helpers/ocr_dependencies.py new file mode 100644 index 000000000..114903ac6 --- /dev/null +++ b/plugins/_document_query/helpers/ocr_dependencies.py @@ -0,0 +1,169 @@ +"""Just-in-time system dependencies for legacy OCR fallbacks.""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import threading + +from helpers import system_packages +from helpers.print_style import PrintStyle + + +TESSERACT_APT_PACKAGES = ( + "tesseract-ocr", + "tesseract-ocr-script-latn", +) +POPPLER_APT_PACKAGES = ("poppler-utils",) + +_INSTALL_LOCK = threading.RLock() +_READY_PROFILES: set[str] = set() + + +def ensure_tesseract_dependencies() -> None: + """Ensure the system Tesseract executable and Latin language data exist.""" + _ensure_dependencies( + profile="tesseract", + packages=TESSERACT_APT_PACKAGES, + commands=("tesseract",), + ) + + +def ensure_pdf_ocr_dependencies() -> None: + """Ensure Tesseract plus the Poppler commands used by pdf2image exist.""" + _ensure_dependencies( + profile="pdf_ocr", + packages=(*TESSERACT_APT_PACKAGES, *POPPLER_APT_PACKAGES), + commands=("tesseract", "pdfinfo", "pdftoppm"), + ) + + +def _ensure_dependencies( + *, + profile: str, + packages: tuple[str, ...], + commands: tuple[str, ...], +) -> None: + if profile in _READY_PROFILES: + return + + with _INSTALL_LOCK: + if profile in _READY_PROFILES: + return + if _dependencies_present(packages, commands): + _mark_profile_ready(profile) + return + + apt_prefix = _apt_command_prefix() + if not apt_prefix: + package_list = " ".join(packages) + raise RuntimeError( + "Document Query OCR fallback requires system packages " + f"'{package_list}'. Automatic installation requires apt-get " + "with root access or non-interactive sudo." + ) + + missing_packages = _missing_apt_packages(packages) + packages_to_install = missing_packages or list(packages) + PrintStyle.info( + "Document Query: installing on-demand OCR dependencies: " + + " ".join(packages_to_install) + ) + + update = _run_apt_command([*apt_prefix, "update"], timeout=300) + _require_success(update, "refresh apt package metadata") + + install = _run_apt_command( + [ + *apt_prefix, + "install", + "-y", + "--no-install-recommends", + *packages_to_install, + ], + timeout=900, + ) + _require_success(install, "install OCR dependencies") + + if not _dependencies_present(packages, commands): + missing_commands = [ + command for command in commands if shutil.which(command) is None + ] + detail = ", ".join(missing_commands) or "required Debian packages" + raise RuntimeError( + "Document Query installed OCR dependencies, but they are still " + f"unavailable: {detail}" + ) + + _mark_profile_ready(profile) + + +def _mark_profile_ready(profile: str) -> None: + _READY_PROFILES.add(profile) + if profile == "pdf_ocr": + _READY_PROFILES.add("tesseract") + + +def _dependencies_present( + packages: tuple[str, ...], commands: tuple[str, ...] +) -> bool: + return not _missing_apt_packages(packages) and all( + shutil.which(command) is not None for command in commands + ) + + +def _missing_apt_packages(packages: tuple[str, ...]) -> list[str]: + if not shutil.which("dpkg-query"): + return [] + + missing = [] + for package in packages: + result = subprocess.run( + ["dpkg-query", "-W", "-f=${Status}", package], + check=False, + text=True, + capture_output=True, + timeout=8, + ) + if result.returncode != 0 or "install ok installed" not in result.stdout: + missing.append(package) + return missing + + +def _apt_command_prefix() -> list[str]: + apt_get = shutil.which("apt-get") + if not apt_get: + return [] + + get_effective_uid = getattr(os, "geteuid", None) + if get_effective_uid and get_effective_uid() == 0: + return [apt_get] + + sudo = shutil.which("sudo") + if not sudo: + return [] + env = shutil.which("env") or "env" + return [sudo, "-n", env, "DEBIAN_FRONTEND=noninteractive", apt_get] + + +def _run_apt_command( + command: list[str], *, timeout: int +) -> subprocess.CompletedProcess[str]: + return system_packages.run_apt_with_retries( + lambda: subprocess.run( + command, + check=False, + text=True, + capture_output=True, + timeout=timeout, + env={**os.environ, "DEBIAN_FRONTEND": "noninteractive"}, + ) + ) + + +def _require_success(result: subprocess.CompletedProcess[str], action: str) -> None: + if result.returncode == 0: + return + output = (result.stderr or result.stdout or "apt-get failed").strip() + raise RuntimeError(f"Document Query could not {action}: {output[-2000:]}") diff --git a/plugins/_document_query/helpers/parsers/image.py b/plugins/_document_query/helpers/parsers/image.py index 95c69c86a..0be43fa38 100644 --- a/plugins/_document_query/helpers/parsers/image.py +++ b/plugins/_document_query/helpers/parsers/image.py @@ -1,4 +1,4 @@ -"""Image parser — delegates to UnstructuredLoader.""" +"""Image parser — delegates to Unstructured's local partitioner.""" from plugins._document_query.helpers.fetch import FetchedDocument from .base import BaseParser from .unstructured import UnstructuredParser diff --git a/plugins/_document_query/helpers/parsers/liteparse.py b/plugins/_document_query/helpers/parsers/liteparse.py index 0ff327571..0d6a8b907 100644 --- a/plugins/_document_query/helpers/parsers/liteparse.py +++ b/plugins/_document_query/helpers/parsers/liteparse.py @@ -5,7 +5,6 @@ from __future__ import annotations import json import os import subprocess -import sys from dataclasses import dataclass from pathlib import Path @@ -82,7 +81,8 @@ class LiteParseParser(BaseParser): timeout = float(config.get("per_document_timeout", 60)) result = subprocess.run( [ - sys.executable, + "depfix", + "run", "-m", "plugins._document_query.helpers.parsers.liteparse_worker", ], diff --git a/plugins/_document_query/helpers/parsers/pdf.py b/plugins/_document_query/helpers/parsers/pdf.py index 7a8d2a8cc..3b6f425c2 100644 --- a/plugins/_document_query/helpers/parsers/pdf.py +++ b/plugins/_document_query/helpers/parsers/pdf.py @@ -4,6 +4,10 @@ import os from helpers.print_style import PrintStyle from plugins._document_query.helpers.fetch import FetchedDocument +from plugins._document_query.helpers.ocr_dependencies import ( + ensure_pdf_ocr_dependencies, + ensure_tesseract_dependencies, +) from .base import BaseParser @@ -18,19 +22,24 @@ class PdfParser(BaseParser): contents = self._parse_with_pymupdf(file_path) if not contents: if not config.get("pdf_ocr_fallback", True): - raise ValueError("PyMuPDF returned no content and OCR fallback is disabled") + raise ValueError( + "PyMuPDF returned no content and OCR fallback is disabled" + ) contents = self._parse_with_ocr(file_path) return contents def _parse_with_pymupdf(self, file_path: str) -> str: from langchain_community.document_loaders.pdf import PyMuPDFLoader - from langchain_community.document_loaders.parsers.images import TesseractBlobParser try: loader = PyMuPDFLoader( - file_path, mode="single", extract_tables="markdown", - extract_images=True, images_inner_format="text", - images_parser=TesseractBlobParser(), pages_delimiter="\n", + file_path, + mode="single", + extract_tables="markdown", + extract_images=True, + images_inner_format="text", + images_parser=_on_demand_tesseract_blob_parser(), + pages_delimiter="\n", ) return "\n".join(e.page_content for e in loader.load()) except Exception as e: @@ -39,6 +48,19 @@ class PdfParser(BaseParser): def _parse_with_ocr(self, file_path: str) -> str: import pdf2image, pytesseract + + ensure_pdf_ocr_dependencies() PrintStyle.debug(f"FALLBACK: OCR for {file_path}") pages = pdf2image.convert_from_path(file_path) return "\n\n".join(pytesseract.image_to_string(p) for p in pages) + + +def _on_demand_tesseract_blob_parser(): + from langchain_community.document_loaders.parsers.images import TesseractBlobParser + + class OnDemandTesseractBlobParser(TesseractBlobParser): + def _analyze_image(self, img) -> str: + ensure_tesseract_dependencies() + return super()._analyze_image(img) + + return OnDemandTesseractBlobParser() diff --git a/plugins/_document_query/helpers/parsers/unstructured.py b/plugins/_document_query/helpers/parsers/unstructured.py index 783abedfd..ecda19003 100644 --- a/plugins/_document_query/helpers/parsers/unstructured.py +++ b/plugins/_document_query/helpers/parsers/unstructured.py @@ -1,25 +1,47 @@ -"""Catch-all parser using UnstructuredLoader.""" +"""Catch-all parser using Unstructured's local partitioner.""" import os +from pathlib import Path from plugins._document_query.helpers.fetch import FetchedDocument +from plugins._document_query.helpers.ocr_dependencies import ( + ensure_pdf_ocr_dependencies, + ensure_tesseract_dependencies, +) from .base import BaseParser os.environ.setdefault("USER_AGENT", "@mixedbread-ai/unstructured") +def _partition_file(file_path: str): + from unstructured.partition.auto import partition + + return partition(filename=file_path, strategy="hi_res") + + class UnstructuredParser(BaseParser): mimetypes = ["*"] def _parse_sync(self, document: FetchedDocument, config: dict) -> str: - from langchain_unstructured import UnstructuredLoader - with document.local_file() as file_path: - loader = UnstructuredLoader( - file_path=file_path, - mode="single", - partition_via_api=False, - strategy="hi_res", - ) - elements = loader.load() - return "\n".join(e.page_content for e in elements) + _ensure_ocr_dependencies(document.mimetype, str(file_path)) + elements = _partition_file(str(file_path)) + return "\n".join(str(element) for element in elements) + + +def _ensure_ocr_dependencies(mimetype: str, file_path: str) -> None: + suffix = Path(file_path).suffix.lower() + if mimetype == "application/pdf" or suffix == ".pdf": + ensure_pdf_ocr_dependencies() + elif mimetype.startswith("image/") or suffix in { + ".bmp", + ".gif", + ".heic", + ".jpeg", + ".jpg", + ".png", + ".tif", + ".tiff", + ".webp", + }: + ensure_tesseract_dependencies() diff --git a/plugins/_orchestrator/AGENTS.md b/plugins/_orchestrator/AGENTS.md index fd93db8ac..02e7dcd6f 100644 --- a/plugins/_orchestrator/AGENTS.md +++ b/plugins/_orchestrator/AGENTS.md @@ -34,7 +34,7 @@ - Framework-runtime adapter self-check: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python plugins/_orchestrator/tests/test_status_adapters.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python plugins/_orchestrator/tests/test_status_adapters.py' ``` - Frontend syntax check when editing WebUI JavaScript: ```bash diff --git a/plugins/_orchestrator/README.md b/plugins/_orchestrator/README.md index 601d8a21c..cd7e68aec 100644 --- a/plugins/_orchestrator/README.md +++ b/plugins/_orchestrator/README.md @@ -137,7 +137,7 @@ credentials too. ```yaml a0: - binary: a0 # falls back to /opt/venv/bin/a0 in Agent Zero Docker + binary: a0 # falls back to /usr/local/bin/a0 in Agent Zero Docker host: "" # empty = AGENT_ZERO_HOST env, else local instance codex: binary: codex diff --git a/plugins/_orchestrator/api/AGENTS.md b/plugins/_orchestrator/api/AGENTS.md index 286103533..5cfbfcf2d 100644 --- a/plugins/_orchestrator/api/AGENTS.md +++ b/plugins/_orchestrator/api/AGENTS.md @@ -30,11 +30,11 @@ - Run the plugin self-check after API changes: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python plugins/_orchestrator/tests/test_status_adapters.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python plugins/_orchestrator/tests/test_status_adapters.py' ``` - For import-only API changes, use the Agent Zero framework runtime: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python -m py_compile plugins/_orchestrator/api/*.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python -m py_compile plugins/_orchestrator/api/*.py' ``` ## Child DOX Index diff --git a/plugins/_orchestrator/default_config.yaml b/plugins/_orchestrator/default_config.yaml index 97e254c2f..a3859328e 100644 --- a/plugins/_orchestrator/default_config.yaml +++ b/plugins/_orchestrator/default_config.yaml @@ -1,5 +1,5 @@ a0: - binary: a0 # falls back to /opt/venv/bin/a0 in Agent Zero Docker + binary: a0 # falls back to /usr/local/bin/a0 in Agent Zero Docker host: "" # empty = AGENT_ZERO_HOST env, else local instance (http://localhost:80) codex: binary: codex diff --git a/plugins/_orchestrator/helpers/AGENTS.md b/plugins/_orchestrator/helpers/AGENTS.md index c5cc9d8e1..858b14083 100644 --- a/plugins/_orchestrator/helpers/AGENTS.md +++ b/plugins/_orchestrator/helpers/AGENTS.md @@ -27,7 +27,7 @@ - Run the adapter contract checks: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python plugins/_orchestrator/tests/test_status_adapters.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python plugins/_orchestrator/tests/test_status_adapters.py' ``` ## Child DOX Index diff --git a/plugins/_orchestrator/helpers/adapters/AGENTS.md b/plugins/_orchestrator/helpers/adapters/AGENTS.md index 5b1c16d0a..a4086d64b 100644 --- a/plugins/_orchestrator/helpers/adapters/AGENTS.md +++ b/plugins/_orchestrator/helpers/adapters/AGENTS.md @@ -24,7 +24,7 @@ - A0 Headless: - Host resolution is config `a0.host`, then `AGENT_ZERO_HOST`, then `http://localhost:80` inside the Agent Zero container. - - The Docker fallback binary is `/opt/venv/bin/a0` when plain `a0` is unavailable. + - The Docker fallback binary is `/usr/local/bin/a0` when plain `a0` is unavailable. - Status means the host socket is reachable; login/target choice is handled by the skill. - Codex CLI: - Detect plugin-owned `data/codex/auth.json` before external `CODEX_HOME` or `~/.codex/auth.json`. @@ -53,11 +53,11 @@ - Run adapter tests: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python plugins/_orchestrator/tests/test_status_adapters.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python plugins/_orchestrator/tests/test_status_adapters.py' ``` - For syntax-only adapter edits: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python -m py_compile plugins/_orchestrator/helpers/adapters/*.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python -m py_compile plugins/_orchestrator/helpers/adapters/*.py' ``` ## Child DOX Index diff --git a/plugins/_orchestrator/helpers/adapters/a0.py b/plugins/_orchestrator/helpers/adapters/a0.py index b1a46f8ae..48567adba 100644 --- a/plugins/_orchestrator/helpers/adapters/a0.py +++ b/plugins/_orchestrator/helpers/adapters/a0.py @@ -12,7 +12,7 @@ from plugins._orchestrator.helpers.adapters.base import TerminalAgentAdapter # Inside the Agent Zero container, the local WebUI listens on port 80, # so the default target is the instance running this very plugin. DEFAULT_HOST = "http://localhost:80" -DEFAULT_DOCKER_A0_BINARY = "/opt/venv/bin/a0" +DEFAULT_DOCKER_A0_BINARY = "/usr/local/bin/a0" class AgentZeroAdapter(TerminalAgentAdapter): diff --git a/plugins/_orchestrator/skills/AGENTS.md b/plugins/_orchestrator/skills/AGENTS.md index 69fc91e3b..c567b4c46 100644 --- a/plugins/_orchestrator/skills/AGENTS.md +++ b/plugins/_orchestrator/skills/AGENTS.md @@ -32,7 +32,7 @@ - Run the skill text contract test: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python plugins/_orchestrator/tests/test_status_adapters.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python plugins/_orchestrator/tests/test_status_adapters.py' ``` ## Child DOX Index diff --git a/plugins/_orchestrator/skills/orchestrator/AGENTS.md b/plugins/_orchestrator/skills/orchestrator/AGENTS.md index 545567551..a3d4e2bcf 100644 --- a/plugins/_orchestrator/skills/orchestrator/AGENTS.md +++ b/plugins/_orchestrator/skills/orchestrator/AGENTS.md @@ -39,7 +39,7 @@ - Run: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python plugins/_orchestrator/tests/test_status_adapters.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python plugins/_orchestrator/tests/test_status_adapters.py' ``` ## Child DOX Index diff --git a/plugins/_orchestrator/skills/orchestrator/references/AGENTS.md b/plugins/_orchestrator/skills/orchestrator/references/AGENTS.md index 2cf2fd019..31c74a81e 100644 --- a/plugins/_orchestrator/skills/orchestrator/references/AGENTS.md +++ b/plugins/_orchestrator/skills/orchestrator/references/AGENTS.md @@ -26,7 +26,7 @@ - Run: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python plugins/_orchestrator/tests/test_status_adapters.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python plugins/_orchestrator/tests/test_status_adapters.py' ``` ## Child DOX Index diff --git a/plugins/_orchestrator/skills/orchestrator/references/a0.md b/plugins/_orchestrator/skills/orchestrator/references/a0.md index 89b080ad6..fb7cbaefe 100644 --- a/plugins/_orchestrator/skills/orchestrator/references/a0.md +++ b/plugins/_orchestrator/skills/orchestrator/references/a0.md @@ -9,8 +9,8 @@ Avoid recursive loops. Tell the target Agent Zero instance to answer directly an ## Install And Probe ```bash -command -v a0 >/dev/null || test -x /opt/venv/bin/a0 -a0 --help >/dev/null || /opt/venv/bin/a0 --help >/dev/null +command -v a0 >/dev/null || test -x /usr/local/bin/a0 +a0 --help >/dev/null || /usr/local/bin/a0 --help >/dev/null ``` ## New Chat diff --git a/plugins/_orchestrator/tests/AGENTS.md b/plugins/_orchestrator/tests/AGENTS.md index 578db4659..5feddf3ee 100644 --- a/plugins/_orchestrator/tests/AGENTS.md +++ b/plugins/_orchestrator/tests/AGENTS.md @@ -12,7 +12,7 @@ ## Local Contracts -- Tests must run with the Agent Zero framework runtime, not the agent execution runtime. +- Tests must run with Agent Zero's global Docker Python runtime, not an isolated sandbox image. - Keep tests self-contained and deterministic. They may inspect files and adapter metadata but should not call network login endpoints or run real terminal agents. - When adding an adapter, assert registry order and status-only behavior as needed. - When changing setup/login guidance, add or update assertions for the phrases that protect the workflow. @@ -26,7 +26,7 @@ - Main check: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python plugins/_orchestrator/tests/test_status_adapters.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python plugins/_orchestrator/tests/test_status_adapters.py' ``` ## Child DOX Index diff --git a/plugins/_orchestrator/webui/AGENTS.md b/plugins/_orchestrator/webui/AGENTS.md index 511b836fe..08d7ce0d6 100644 --- a/plugins/_orchestrator/webui/AGENTS.md +++ b/plugins/_orchestrator/webui/AGENTS.md @@ -36,7 +36,7 @@ ``` - Status API smoke after WebUI/API coupling changes: ```bash - docker exec 8dc967046cda bash -lc 'cd /a0 && /opt/venv-a0/bin/python plugins/_orchestrator/tests/test_status_adapters.py' + docker exec 8dc967046cda bash -lc 'cd /a0 && python plugins/_orchestrator/tests/test_status_adapters.py' ``` ## Child DOX Index diff --git a/plugins/_plugin_validator/webui/plugin-validator-guidance.md b/plugins/_plugin_validator/webui/plugin-validator-guidance.md index 64070051d..39b5900a3 100644 --- a/plugins/_plugin_validator/webui/plugin-validator-guidance.md +++ b/plugins/_plugin_validator/webui/plugin-validator-guidance.md @@ -5,7 +5,7 @@ - API handlers: subclass `ApiHandler` and return a dict or `Response`. - Tools: subclass `Tool` from `helpers.tool`. - AgentContext imports: use `from agent import AgentContext, AgentContextType`, never `helpers.context`. -- Hooks runtime targeting: use `sys.executable` only for framework runtime work and `/opt/venv/bin/python` for agent-runtime installs. +- Hooks runtime targeting: `sys.executable` addresses Agent Zero's global Docker Python environment; target isolated sandboxes or OS packages explicitly. - execute.py pattern: expose `main()` and end with `if __name__ == "__main__": sys.exit(main())`. - Community contribution: plugin name must match `^[a-z0-9_]+$`, match the directory name, and stay unique in the published index. - LICENSE: a file named `LICENSE` at the plugin root is optional for local-only plugins but required at the repository root before Plugin Index submission; if missing, rate Structure Validation as warning (not pass) and state that clearly in findings. diff --git a/plugins/_sandboxing/AGENTS.md b/plugins/_sandboxing/AGENTS.md new file mode 100644 index 000000000..710fbd3ff --- /dev/null +++ b/plugins/_sandboxing/AGENTS.md @@ -0,0 +1,39 @@ +# Sandboxing Plugin DOX + +## Purpose + +- Own direct gVisor/runsc sandbox lifecycle, execution, destination discovery, and management UI. + +## Ownership + +- `helpers/images.py` owns daemonless Docker/OCI pull, unpacking, digest-pinned image cache metadata, image last-use tracking, and safe cache deletion. +- `helpers/manager.py` owns validation, OCI bundles, runtime state, snapshots, mounts, sandbox/image references, expiry, and safe deletion. +- `helpers/runtime.py` owns resolved plugin configuration and the process-local manager. +- `helpers/shell.py` owns interactive `runsc exec` terminal sessions. +- `tools/`, `api/`, `prompts/`, `extensions/`, and `webui/` expose the manager without duplicating lifecycle logic. + +## Local Contracts + +- Invoke `runsc` directly with argument arrays and `shell=False`; agent-generated shell text is only passed inside the sandbox. +- Never use a Docker socket, nested daemon, SSH server, KVM, or an unvalidated sandbox path. +- Pull images through `skopeo` and unpack them through `umoci` with argument arrays, bounded output, timeouts, and no shell. Registry credentials may only be referenced through a configured auth file. +- Pin every sandbox to an immutable image digest. Tag refreshes affect new sandboxes only; image deletion and cleanup must refuse every digest referenced by sandbox metadata. +- Treat image cache entries as private runtime state. Automatic cleanup removes only unreferenced images whose last-use time exceeds the configured lifetime (30 days by default). +- Keep the shared mount explicit at `/shared`; optional binds must have validated absolute sources and sandbox destinations. +- Temporary sandboxes use the memory-backed root overlay and expire from configurable last-use time. Permanent sandboxes use a private disk-backed overlay and never expire. +- Metadata reserves chat, project, and agent ownership fields without filtering the first-prototype listing. +- Lifecycle mutations must use per-sandbox and image-cache thread/process locks and atomic metadata/snapshot replacement. + +## Work Guidance + +- Keep framework adapters thin and manager behavior independently testable without a real gVisor installation. +- Treat changes to capabilities, namespaces, mounts, networking, paths, or `runsc` flags as security-contract changes. + +## Verification + +- Run `pytest tests/test_sandboxing.py tests/test_code_execution_destinations.py` after manager or destination changes. +- Run the documented Linux lifecycle smoke test in an image with gVisor before claiming runtime compatibility. + +## Child DOX Index + +No child DOX files. diff --git a/plugins/_sandboxing/README.md b/plugins/_sandboxing/README.md new file mode 100644 index 000000000..ccb4b9401 --- /dev/null +++ b/plugins/_sandboxing/README.md @@ -0,0 +1,103 @@ +# Sandboxing + +The bundled `_sandboxing` plugin runs named OCI containers directly with +gVisor's `runsc`. It does not use Docker child containers, a Docker socket, +SSH, a nested daemon, or KVM. + +## Agent behavior + +`code_execution_tool` now accepts `destination`: + +- `default` (the default) creates or wakes the configured default sandbox. +- A listed sandbox name targets that sandbox; `sandbox:` is always an + unambiguous form. +- `local` targets the operating system running Agent Zero and should be used + only when Agent Zero or its core files must be changed. +- `host` appears only while an A0 CLI or Launcher host with remote execution + enabled is connected. It reuses the existing authenticated connector. + +Terminal session ids are isolated per destination. Commands, `input`, output +polls, and resets must use the same destination and session id. + +The `sandbox` tool and the plugin's main screen support list, doctor, create, +inspect, save, stop, start, expiry cleanup, and exact-name delete operations. +They also pull, list, inspect, clean, and delete cached sandbox images. + +## Storage policy + +Temporary sandboxes use `--overlay2=root:memory` for their live upper layer. +They retain atomic recovery snapshots and expire after the configured number +of days since last execution (seven days by default). Permanent sandboxes use +a private `root:dir=...` disk-backed upper layer and never expire. + +Every sandbox receives the configured shared exchange folder at `/shared`. +Creation APIs also accept optional folder binds: + +```json +{ + "source": "/absolute/host/folder", + "destination": "/mnt/data", + "read_only": true +} +``` + +Sources must be existing absolute non-symlink directories. Destinations must +be absolute sandbox paths and cannot overlap `/proc`, `/dev`, `/sys`, `/etc`, +or `/shared`. Ownership metadata reserves `chat_id`, `project_id`, and +`agent_id`; the prototype lists all managed sandboxes without filtering. + +## Runtime images + +Sandbox root filesystems are resolved at runtime from the configured +Docker/OCI image reference. `skopeo` copies the selected platform image +without a Docker daemon, and `umoci` unpacks it into the private image cache. +New sandboxes resolve tags and pin both the reference and immutable digest in +their metadata. Existing sandboxes always restart from that digest, even when +the tag later moves. + +The default reference is `docker.io/library/python:3.13-slim-bookworm` and can +be changed in plugin settings or per sandbox. A usable image must provide +`/bin/sh` and `/bin/bash`; Python, Node.js, Git, and other tools are available +only when the selected image includes them. Image `ENTRYPOINT`, `CMD`, working +directory, and user are intentionally ignored because Agent Zero supplies a +controlled root process, `/workspace`, and runtime environment. + +Cached images show their size, platform, digest, last use, and referencing +sandboxes on the management screen. Manual deletion refuses referenced images. +The hourly cleanup removes only unreferenced images unused for 30 days by +default. An optional containers-auth JSON path supports private registries +without putting credentials in command arguments or plugin metadata. + +## gVisor runtime + +The base build installs the signed gVisor apt package in a throwaway stage and +copies only `runsc` plus its required `gvisor_sentry` sidecar into the final +image. The containerd shim, remote-checkpoint gofer, and optional metric server +are omitted. `skopeo` and `umoci` remain available, and no sandbox rootfs is +baked into the image. The local Compose example keeps the outer container +unprivileged with `no-new-privileges`, uses an init reaper for detached +runtimes, and relaxes its seccomp profile for nested systrap. Native +deployments must provide the equivalent `CAP_SYS_CHROOT` and kernel policy; +the Doctor action reports missing prerequisites and never falls back to an +unsandboxed runtime. + +Persistent state and `/shared` must live on durable storage. Private state is +never mounted into `/shared`, and private snapshots are replaced atomically. + +## Linux smoke test + +After building the base and runnable images, use the UI or Python manager to: + +1. Run Doctor and verify it passes under the final service identity. +2. Pull the configured image and verify its platform and digest in the UI. +3. Create `alpha` and `beta`; check that `/workspace` changes are private. +4. Exchange a probe through `/shared`. +5. Save and stop `alpha`, start it again, and verify its private file survives. +6. Refresh a moved tag and verify existing sandboxes keep their old digest while a new sandbox uses the refreshed digest. +7. Verify a `network=none` sandbox cannot reach an external address. +8. Delete `alpha` and verify `beta` and the shared probe remain. +9. Verify image deletion refuses `beta`'s digest, then delete `beta` and exercise unused-image cleanup with a controlled clock. + +The unit suite mocks the `runsc` boundary; this Linux smoke test is required to +validate the actual kernel, gVisor release, architecture, and outer-container +security policy. diff --git a/plugins/_sandboxing/api/__init__.py b/plugins/_sandboxing/api/__init__.py new file mode 100644 index 000000000..1bb8a337a --- /dev/null +++ b/plugins/_sandboxing/api/__init__.py @@ -0,0 +1 @@ +"""Sandboxing HTTP API.""" diff --git a/plugins/_sandboxing/api/sandboxes.py b/plugins/_sandboxing/api/sandboxes.py new file mode 100644 index 000000000..69acc3ec7 --- /dev/null +++ b/plugins/_sandboxing/api/sandboxes.py @@ -0,0 +1,88 @@ +from __future__ import annotations + +import asyncio +from typing import Any + +from helpers.api import ApiHandler, Request +from plugins._sandboxing.helpers.images import image_info_dict +from plugins._sandboxing.helpers.manager import SandboxError, sandbox_info_dict +from plugins._sandboxing.helpers.runtime import defaults, get_manager + + +class Sandboxes(ApiHandler): + async def process(self, input: dict[str, Any], request: Request) -> dict[str, Any]: + action = str(input.get("action") or "list").strip().lower() + try: + manager = get_manager() + if action == "list": + sandboxes = await asyncio.to_thread(manager.list) + images = await asyncio.to_thread(manager.list_images) + default_name, default_type, default_network = defaults() + return { + "ok": True, + "sandboxes": [sandbox_info_dict(item) for item in sandboxes], + "images": [image_info_dict(item) for item in images], + "defaults": { + "name": default_name, + "sandbox_type": default_type, + "network": default_network, + "image": manager.config.default_image, + }, + "image_cleanup_days": manager.images.config.cleanup_days, + "shared_dir": str(manager.config.shared_dir), + } + if action == "doctor": + diagnostics = await asyncio.to_thread(manager.doctor) + return { + "ok": not any(line.startswith("ERROR:") for line in diagnostics), + "diagnostics": diagnostics, + } + name = str(input.get("name") or "").strip() + if action == "create": + default_name, default_type, default_network = defaults() + item = await asyncio.to_thread( + manager.create, + name or default_name, + sandbox_type=str(input.get("sandbox_type") or default_type), + network=str(input.get("network") or default_network), + image=str(input.get("image") or manager.config.default_image), + mounts=input.get("mounts") or [], + ) + elif action in {"start", "wake"}: + item = await asyncio.to_thread(manager.start, name) + elif action in {"stop", "sleep"}: + item = await asyncio.to_thread(manager.stop, name) + elif action == "save": + item = await asyncio.to_thread(manager.save, name) + elif action == "inspect": + item = await asyncio.to_thread(manager.inspect, name) + elif action == "delete": + if input.get("confirm") is not True: + return {"ok": False, "error": "delete requires confirm=true"} + removed = await asyncio.to_thread(manager.delete, name) + return {"ok": True, "name": name, "deleted": removed} + elif action == "cleanup": + deleted = await asyncio.to_thread(manager.cleanup_expired) + return {"ok": True, "deleted": deleted} + elif action in {"pull_image", "refresh_image"}: + image = str(input.get("image") or manager.config.default_image).strip() + value = await asyncio.to_thread(manager.pull_image, image) + return {"ok": True, "image": image_info_dict(value)} + elif action == "inspect_image": + identifier = str(input.get("image") or input.get("digest") or "").strip() + value = await asyncio.to_thread(manager.inspect_image, identifier) + return {"ok": True, "image": image_info_dict(value)} + elif action == "delete_image": + if input.get("confirm") is not True: + return {"ok": False, "error": "delete_image requires confirm=true"} + identifier = str(input.get("digest") or input.get("image") or "").strip() + removed = await asyncio.to_thread(manager.delete_image, identifier) + return {"ok": True, "image": identifier, "deleted": removed} + elif action == "cleanup_images": + deleted = await asyncio.to_thread(manager.cleanup_images) + return {"ok": True, "deleted_images": deleted} + else: + return {"ok": False, "error": f"Unknown action: {action}"} + return {"ok": True, "sandbox": sandbox_info_dict(item)} + except (SandboxError, ValueError) as exc: + return {"ok": False, "error": str(exc)} diff --git a/plugins/_sandboxing/default_config.yaml b/plugins/_sandboxing/default_config.yaml new file mode 100644 index 000000000..e5f26bd19 --- /dev/null +++ b/plugins/_sandboxing/default_config.yaml @@ -0,0 +1,22 @@ +runsc_path: /usr/bin/runsc +skopeo_path: /usr/bin/skopeo +umoci_path: /usr/bin/umoci +default_image: docker.io/library/python:3.13-slim-bookworm +registry_auth_file: "" +image_cache_dir: usr/plugins/_sandboxing/images +state_dir: usr/plugins/_sandboxing/runtime +runsc_root: /dev/shm/agent-zero-runsc +shared_dir: usr/sandbox-shared +default_sandbox: default +default_type: temporary +default_network: host +temporary_lifetime_days: 7 +image_lifetime_days: 30 +image_pull_timeout: 900 +image_unpack_timeout: 900 +max_image_bytes: 17179869184 +start_timeout: 8 +stop_timeout: 3 +snapshot_timeout: 300 +exec_timeout: 600 +max_output_bytes: 1048576 diff --git a/plugins/_sandboxing/extensions/python/code_execution_destinations/_10_sandboxes.py b/plugins/_sandboxing/extensions/python/code_execution_destinations/_10_sandboxes.py new file mode 100644 index 000000000..056d2670b --- /dev/null +++ b/plugins/_sandboxing/extensions/python/code_execution_destinations/_10_sandboxes.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +import asyncio + +from helpers.extension import Extension +from plugins._code_execution.helpers.destinations import ExecutionDestination +from plugins._sandboxing.helpers.runtime import defaults, get_manager + + +class IncludeSandboxDestinations(Extension): + async def execute( + self, destinations: list[ExecutionDestination], **kwargs + ) -> None: + default_name, _, _ = defaults(agent=self.agent) + destinations.insert( + 0, + ExecutionDestination( + id="default", + kind="sandbox", + target=default_name, + label=f"Default sandbox ({default_name})", + description="Default isolated execution destination; created or woken automatically.", + status="default", + ), + ) + try: + manager = get_manager(agent=self.agent) + sandboxes = await asyncio.to_thread(manager.list) + except Exception: + return + reserved = {"default", "local", "host"} + for sandbox in sandboxes: + destination_id = ( + f"sandbox:{sandbox.name}" if sandbox.name in reserved else sandbox.name + ) + if sandbox.name == default_name: + continue + destinations.append( + ExecutionDestination( + id=destination_id, + kind="sandbox", + target=sandbox.name, + label=f"Sandbox {sandbox.name}", + description=( + f"{sandbox.sandbox_type} gVisor sandbox; network={sandbox.network}." + ), + status=sandbox.status, + ) + ) diff --git a/plugins/_sandboxing/extensions/python/code_execution_destinations/_20_host.py b/plugins/_sandboxing/extensions/python/code_execution_destinations/_20_host.py new file mode 100644 index 000000000..3de9b4ed8 --- /dev/null +++ b/plugins/_sandboxing/extensions/python/code_execution_destinations/_20_host.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from helpers.extension import Extension +from plugins._code_execution.helpers.destinations import ExecutionDestination + + +class IncludeConnectedHostDestination(Extension): + def execute(self, destinations: list[ExecutionDestination], **kwargs) -> None: + if self.agent is None: + return + context_id = str(getattr(getattr(self.agent, "context", None), "id", "") or "") + if not context_id: + return + try: + from plugins._a0_connector.helpers.remote_tool_prompts import ( + remote_tool_prompt_availability, + ) + + available = remote_tool_prompt_availability(context_id) + except ImportError: + return + if available.get("code_execution_remote"): + destinations.append( + ExecutionDestination( + id="host", + kind="host", + label="Connected host", + description="The A0 CLI or Launcher host computer connected to this chat.", + status="connected", + ) + ) diff --git a/plugins/_sandboxing/extensions/python/job_loop/_40_cleanup_expired_sandboxes.py b/plugins/_sandboxing/extensions/python/job_loop/_40_cleanup_expired_sandboxes.py new file mode 100644 index 000000000..41aad7ba9 --- /dev/null +++ b/plugins/_sandboxing/extensions/python/job_loop/_40_cleanup_expired_sandboxes.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +import asyncio +import datetime as dt + +from helpers.extension import Extension +from helpers.print_style import PrintStyle +from plugins._sandboxing.helpers.runtime import get_manager + + +class CleanupExpiredSandboxes(Extension): + _last_check: dt.datetime | None = None + + async def execute(self, **kwargs) -> None: + now = dt.datetime.now(dt.timezone.utc) + last_check = type(self)._last_check + if last_check and now - last_check < dt.timedelta(hours=1): + return + type(self)._last_check = now + try: + manager = get_manager() + deleted = await asyncio.to_thread(manager.cleanup_expired, now=now) + deleted_images = await asyncio.to_thread(manager.cleanup_images, now=now) + if deleted: + PrintStyle.info("Deleted expired temporary sandboxes:", deleted) + if deleted_images: + PrintStyle.info("Deleted old unused sandbox images:", deleted_images) + except Exception as exc: + PrintStyle.warning("Sandbox and image cleanup failed:", exc) diff --git a/plugins/_sandboxing/extensions/python/message_loop_prompts_after/_70_include_code_execution_destinations.py b/plugins/_sandboxing/extensions/python/message_loop_prompts_after/_70_include_code_execution_destinations.py new file mode 100644 index 000000000..310dbc0f9 --- /dev/null +++ b/plugins/_sandboxing/extensions/python/message_loop_prompts_after/_70_include_code_execution_destinations.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +from agent import LoopData +from helpers.extension import Extension +from plugins._code_execution.helpers.destinations import ( + get_code_execution_destinations, +) + + +class IncludeCodeExecutionDestinations(Extension): + async def execute(self, loop_data: LoopData = LoopData(), **kwargs) -> None: + if self.agent is None: + return + destinations = await get_code_execution_destinations(self.agent) + lines = [ + f"- `{item.id}` — {item.label} ({item.status}): {item.description}" + for item in destinations + ] + loop_data.extras_temporary["code_execution_destinations"] = self.agent.read_prompt( + "agent.extras.code_execution_destinations.md", + destinations="\n".join(lines), + ) diff --git a/plugins/_sandboxing/extensions/python/startup_migration/_30_sandboxing_runtime.py b/plugins/_sandboxing/extensions/python/startup_migration/_30_sandboxing_runtime.py new file mode 100644 index 000000000..7fcca958a --- /dev/null +++ b/plugins/_sandboxing/extensions/python/startup_migration/_30_sandboxing_runtime.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import threading + +from helpers.extension import Extension +from helpers.print_style import PrintStyle +from plugins._sandboxing.helpers.runtime import get_manager + + +_thread: threading.Thread | None = None + + +class PrepareSandboxRuntime(Extension): + def execute(self, **kwargs) -> None: + global _thread + if _thread is not None and _thread.is_alive(): + return + _thread = threading.Thread( + target=_prepare, + name="a0-sandbox-runtime-preparation", + daemon=True, + ) + _thread.start() + + +def _prepare() -> None: + try: + manager = get_manager() + diagnostics = manager.doctor() + errors = [line for line in diagnostics if line.startswith("ERROR:")] + warnings = [line for line in diagnostics if line.startswith("WARNING:")] + if errors: + PrintStyle.warning("Sandbox runtime doctor reported errors:", errors) + elif warnings: + PrintStyle.warning("Sandbox runtime doctor reported warnings:", warnings) + deleted = manager.cleanup_expired() + deleted_images = manager.cleanup_images() + if deleted: + PrintStyle.info("Deleted expired temporary sandboxes:", deleted) + if deleted_images: + PrintStyle.info("Deleted old unused sandbox images:", deleted_images) + except Exception as exc: + PrintStyle.warning("Sandbox runtime preparation failed:", exc) diff --git a/plugins/_sandboxing/helpers/__init__.py b/plugins/_sandboxing/helpers/__init__.py new file mode 100644 index 000000000..44d9d1d2c --- /dev/null +++ b/plugins/_sandboxing/helpers/__init__.py @@ -0,0 +1 @@ +"""gVisor sandbox helpers.""" diff --git a/plugins/_sandboxing/helpers/images.py b/plugins/_sandboxing/helpers/images.py new file mode 100644 index 000000000..d69d328e2 --- /dev/null +++ b/plugins/_sandboxing/helpers/images.py @@ -0,0 +1,883 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import datetime as dt +import fcntl +import json +import os +import re +import shutil +import subprocess +import tempfile +import threading +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal + + +ImageStatus = Literal["ready", "broken"] + +IMAGE_SCHEMA_VERSION = 1 +_DIGEST_RE = re.compile(r"^sha256:[0-9a-f]{64}$") +_ENV_KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") + + +class SandboxImageError(RuntimeError): + """A safe, user-facing sandbox image management error.""" + + +@dataclass(frozen=True, slots=True) +class SandboxImageConfig: + skopeo: Path + umoci: Path + cache_dir: Path + default_image: str + auth_file: Path | None = None + cleanup_days: float = 30.0 + pull_timeout: float = 900.0 + unpack_timeout: float = 900.0 + max_output_bytes: int = 1_048_576 + max_image_bytes: int = 17_179_869_184 + + +@dataclass(frozen=True, slots=True) +class SandboxImageInfo: + digest: str + reference: str + references: tuple[str, ...] + status: ImageStatus + created_at: str + last_used_at: str + size_bytes: int + os: str = "" + architecture: str = "" + used_by: tuple[str, ...] = () + runtime_error: str | None = None + rootfs: Path | None = field(default=None, repr=False, compare=False) + environment: tuple[str, ...] = field(default=(), repr=False, compare=False) + + +def validate_digest(value: str) -> str: + digest = str(value or "").strip().lower() + if not _DIGEST_RE.fullmatch(digest): + raise SandboxImageError(f"invalid OCI image digest {value!r}") + return digest + + +def normalize_image_reference(value: str) -> str: + reference = str(value or "").strip() + if reference.startswith("docker://"): + reference = reference[9:] + if ( + not reference + or len(reference) > 512 + or any(char.isspace() or ord(char) < 32 for char in reference) + or "://" in reference + or reference.startswith(("/", ".")) + ): + raise SandboxImageError(f"invalid Docker image reference {value!r}") + return reference + + +def image_info_dict(info: SandboxImageInfo) -> dict[str, Any]: + """Serialize image information without private cache paths or image env.""" + return { + "digest": info.digest, + "reference": info.reference, + "references": list(info.references), + "status": info.status, + "created_at": info.created_at, + "last_used_at": info.last_used_at, + "size_bytes": info.size_bytes, + "os": info.os, + "architecture": info.architecture, + "used_by": list(info.used_by), + "runtime_error": info.runtime_error, + } + + +class SandboxImageManager: + """Pull, unpack, cache, and remove immutable Docker/OCI image roots.""" + + def __init__(self, config: SandboxImageConfig) -> None: + self.config = self._validated_config(config) + self._thread_lock = threading.RLock() + + @staticmethod + def _validated_config(config: SandboxImageConfig) -> SandboxImageConfig: + for label, path in ( + ("skopeo", config.skopeo), + ("umoci", config.umoci), + ("image cache", config.cache_dir), + ): + if not path.is_absolute(): + raise SandboxImageError(f"{label} path must be absolute: {path}") + if config.auth_file is not None and not config.auth_file.is_absolute(): + raise SandboxImageError( + f"registry auth file path must be absolute: {config.auth_file}" + ) + if config.cleanup_days <= 0: + raise SandboxImageError("image cleanup days must be positive") + if config.max_output_bytes < 4096: + raise SandboxImageError("image command output limit must be at least 4096") + if config.max_image_bytes < 1_048_576: + raise SandboxImageError("maximum unpacked image size must be at least 1 MiB") + if config.default_image: + normalize_image_reference(config.default_image) + return config + + def doctor(self) -> list[str]: + diagnostics: list[str] = [] + for label, executable in ( + ("skopeo", self.config.skopeo), + ("umoci", self.config.umoci), + ): + if not executable.is_file() or not os.access(executable, os.X_OK): + diagnostics.append(f"ERROR: {label} is not executable at {executable}") + continue + try: + result = self._run( + [str(executable), "--version"], + timeout=5, + operation=f"check {label} version", + check=False, + ) + detail = " ".join((result[1] or result[2]).split()) + if result[0]: + diagnostics.append( + f"ERROR: {label} --version exited {result[0]}: {detail}" + ) + else: + diagnostics.append(f"OK: {detail or f'{label} available'}") + except SandboxImageError as exc: + diagnostics.append(f"ERROR: {exc}") + try: + self._ensure_layout() + self._atomic_probe(self.config.cache_dir) + diagnostics.append(f"OK: sandbox image cache at {self.config.cache_dir}") + except (OSError, SandboxImageError) as exc: + diagnostics.append(f"ERROR: sandbox image cache is not writable: {exc}") + if not self.config.default_image: + diagnostics.append("ERROR: no default sandbox image is configured") + else: + diagnostics.append(f"OK: default sandbox image {self.config.default_image}") + auth_file = self.config.auth_file + if auth_file is not None: + if auth_file.is_symlink() or not auth_file.is_file(): + diagnostics.append( + f"ERROR: registry auth file is not a regular non-symlink file: {auth_file}" + ) + else: + diagnostics.append(f"OK: registry auth file configured at {auth_file}") + return diagnostics + + def list(self) -> list[SandboxImageInfo]: + self._ensure_layout() + results: list[SandboxImageInfo] = [] + with self._cache_lock(): + for entry in sorted(self.config.cache_dir.iterdir(), key=lambda path: path.name): + digest = self._digest_from_directory(entry.name) + if digest is None or entry.is_symlink() or not entry.is_dir(): + continue + try: + results.append(self._read_info_locked(digest)) + except SandboxImageError as exc: + results.append(self._broken_info(digest, entry, str(exc))) + return results + + def inspect(self, identifier: str) -> SandboxImageInfo: + self._ensure_layout() + with self._cache_lock(): + digest = self._resolve_identifier_locked(identifier) + return self._read_info_locked(digest) + + def ensure( + self, + reference: str = "", + *, + digest: str | None = None, + refresh: bool = False, + ) -> SandboxImageInfo: + requested = normalize_image_reference(reference or self.config.default_image) + expected = validate_digest(digest) if digest else None + self._ensure_layout() + with self._cache_lock(): + if expected is not None and self._image_path(expected).is_dir(): + try: + return self._touch_reference_locked(expected, requested) + except SandboxImageError: + self._delete_path_locked(expected, self._image_path(expected)) + if expected is None and not refresh: + cached = self._find_reference_locked(requested) + if cached is not None: + return self._touch_reference_locked(cached, requested) + pull_reference = ( + self._pinned_reference(requested, expected) if expected else requested + ) + return self._pull_locked( + pull_reference, + expected_digest=expected, + display_reference=requested, + update_alias=expected is None, + ) + + def pull(self, reference: str = "") -> SandboxImageInfo: + return self.ensure(reference, refresh=True) + + def touch(self, digest: str) -> None: + digest = validate_digest(digest) + self._ensure_layout() + with self._cache_lock(): + info = self._read_info_locked(digest) + self._write_info_locked(dataclasses.replace(info, last_used_at=self._now())) + + def delete(self, digest: str, *, missing_ok: bool = False) -> bool: + digest = validate_digest(digest) + self._ensure_layout() + with self._cache_lock(): + path = self._image_path(digest) + if not path.exists() and not path.is_symlink(): + if missing_ok: + return False + raise SandboxImageError(f"sandbox image {digest} is not cached") + self._delete_path_locked(digest, path) + return True + + def cleanup( + self, + *, + used_digests: set[str], + now: dt.datetime | None = None, + ) -> list[str]: + current = now or dt.datetime.now(dt.timezone.utc) + cutoff = current - dt.timedelta(days=self.config.cleanup_days) + removed: list[str] = [] + self._ensure_layout() + with self._cache_lock(): + for entry in sorted(self.config.cache_dir.iterdir(), key=lambda path: path.name): + digest = self._digest_from_directory(entry.name) + if digest is None: + if ( + re.fullmatch(r"\.pull-[A-Za-z0-9_-]+", entry.name) + and not entry.is_symlink() + and entry.is_dir() + ): + with contextlib.suppress(OSError): + modified = dt.datetime.fromtimestamp( + entry.stat().st_mtime, tz=dt.timezone.utc + ) + if modified <= cutoff: + shutil.rmtree(entry) + continue + if digest in used_digests: + continue + try: + info = self._read_info_locked(digest) + last_used = self._parse_timestamp(info.last_used_at, "last_used_at") + except SandboxImageError: + try: + last_used = self._read_cleanup_timestamp_locked(digest) + except SandboxImageError: + continue + if last_used > cutoff: + continue + self._delete_path_locked(digest, entry) + removed.append(digest) + return removed + + def _read_cleanup_timestamp_locked(self, digest: str) -> dt.datetime: + path = self._image_path(digest) + metadata_path = path / "metadata.json" + if ( + path.is_symlink() + or not path.is_dir() + or metadata_path.is_symlink() + or not metadata_path.is_file() + ): + raise SandboxImageError(f"sandbox image {digest} has unsafe cache content") + try: + value = json.loads(metadata_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise SandboxImageError(f"cannot read sandbox image {digest}: {exc}") from exc + if not isinstance(value, dict) or value.get("digest") != digest: + raise SandboxImageError(f"sandbox image {digest} has invalid metadata") + return self._parse_timestamp(value.get("last_used_at"), "last_used_at") + + def _pull_locked( + self, + reference: str, + *, + expected_digest: str | None, + display_reference: str, + update_alias: bool, + ) -> SandboxImageInfo: + self._require_tools() + inspect_argv = [ + *self._skopeo_command("inspect"), + "--no-tags", + f"docker://{reference}", + ] + _, output, _, _ = self._run( + inspect_argv, + timeout=self.config.pull_timeout, + operation=f"inspect sandbox image {reference!r}", + ) + try: + inspected = json.loads(output) + except json.JSONDecodeError as exc: + raise SandboxImageError( + f"registry returned invalid metadata for {reference!r}: {exc}" + ) from exc + if not isinstance(inspected, dict): + raise SandboxImageError(f"registry returned invalid metadata for {reference!r}") + digest = validate_digest(str(inspected.get("Digest") or expected_digest or "")) + if expected_digest is not None and digest != expected_digest: + raise SandboxImageError( + f"image {reference!r} resolved to {digest}, expected {expected_digest}" + ) + layers = inspected.get("LayersData") + if isinstance(layers, list): + compressed_bytes = 0 + for layer in layers: + if not isinstance(layer, dict): + continue + with contextlib.suppress(TypeError, ValueError): + compressed_bytes += max(0, int(layer.get("Size") or 0)) + if compressed_bytes > self.config.max_image_bytes: + raise SandboxImageError( + f"compressed image is {compressed_bytes} bytes, above the configured " + f"{self.config.max_image_bytes}-byte limit" + ) + target = self._image_path(digest) + if target.is_dir(): + try: + info = self._touch_reference_locked(digest, display_reference) + except SandboxImageError: + self._delete_path_locked(digest, target) + else: + if update_alias: + self._set_alias_locked(display_reference, digest) + return info + pinned = self._pinned_reference(reference, digest) + temporary = Path(tempfile.mkdtemp(prefix=".pull-", dir=self.config.cache_dir)) + try: + layout = temporary / "layout" + bundle = temporary / "bundle" + self._run( + [ + *self._skopeo_command("copy"), + f"docker://{pinned}", + f"oci:{layout}:image", + ], + timeout=self.config.pull_timeout, + operation=f"pull sandbox image {reference!r}", + ) + self._run( + [ + str(self.config.umoci), + "unpack", + "--rootless", + "--image", + f"{layout}:image", + str(bundle), + ], + timeout=self.config.unpack_timeout, + operation=f"unpack sandbox image {reference!r}", + ) + rootfs = bundle / "rootfs" + environment = self._validate_unpacked_rootfs(bundle, rootfs) + size_bytes = self._allocated_bytes(rootfs) + if size_bytes > self.config.max_image_bytes: + raise SandboxImageError( + f"unpacked image is {size_bytes} bytes, above the configured " + f"{self.config.max_image_bytes}-byte limit" + ) + record = temporary / "record" + record.mkdir(mode=0o700) + os.replace(rootfs, record / "rootfs") + now = self._now() + info = SandboxImageInfo( + digest=digest, + reference=display_reference, + references=(display_reference,), + status="ready", + created_at=now, + last_used_at=now, + size_bytes=size_bytes, + os=str(inspected.get("Os") or ""), + architecture=str(inspected.get("Architecture") or ""), + rootfs=record / "rootfs", + environment=environment, + ) + self._write_info_path(record / "metadata.json", info) + os.replace(record, target) + self._fsync_directory(self.config.cache_dir) + if update_alias: + self._set_alias_locked(display_reference, digest) + return dataclasses.replace(info, rootfs=target / "rootfs") + except BaseException: + if target.exists() and not target.is_symlink(): + with contextlib.suppress(OSError): + shutil.rmtree(target) + raise + finally: + if temporary.exists() and not temporary.is_symlink(): + shutil.rmtree(temporary, ignore_errors=True) + + def _validate_unpacked_rootfs( + self, bundle: Path, rootfs: Path + ) -> tuple[str, ...]: + if rootfs.is_symlink() or not rootfs.is_dir(): + raise SandboxImageError("unpacked OCI image has no safe root filesystem") + self._validate_required_commands(rootfs) + for relative in ("workspace", "shared"): + path = rootfs / relative + if path.is_symlink(): + raise SandboxImageError(f"sandbox image /{relative} must not be a symlink") + path.mkdir(mode=0o777, parents=True, exist_ok=True) + with contextlib.suppress(PermissionError): + path.chmod(0o777) + etc = rootfs / "etc" + if etc.is_symlink(): + raise SandboxImageError("sandbox image /etc must not be a symlink") + etc.mkdir(mode=0o755, parents=True, exist_ok=True) + for name in ("hosts", "resolv.conf"): + path = etc / name + if path.is_symlink() or (path.exists() and not path.is_file()): + raise SandboxImageError(f"sandbox image /etc/{name} must be a regular file") + path.touch(mode=0o644, exist_ok=True) + config_path = bundle / "config.json" + try: + config = json.loads(config_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise SandboxImageError(f"cannot read unpacked OCI configuration: {exc}") from exc + raw_env = config.get("process", {}).get("env", []) if isinstance(config, dict) else [] + return self._normalize_environment(raw_env) + + @staticmethod + def _validate_required_commands(rootfs: Path) -> None: + for required in ("bin/sh", "bin/bash"): + path = rootfs / required + try: + resolved = path.resolve(strict=True) + resolved.relative_to(rootfs.resolve(strict=True)) + except (OSError, ValueError): + raise SandboxImageError( + f"sandbox image is missing safe required /{required}" + ) + if not resolved.is_file(): + raise SandboxImageError(f"sandbox image /{required} is not a file") + + @staticmethod + def _normalize_environment(raw: Any) -> tuple[str, ...]: + if not isinstance(raw, list): + return () + result: list[str] = [] + for item in raw[:256]: + value = str(item) + if len(value) > 8192 or "\x00" in value or "=" not in value: + continue + key = value.split("=", 1)[0] + if _ENV_KEY_RE.fullmatch(key): + result.append(value) + return tuple(result) + + def _read_info_locked(self, digest: str) -> SandboxImageInfo: + digest = validate_digest(digest) + path = self._image_path(digest) + if path.is_symlink() or not path.is_dir(): + raise SandboxImageError(f"sandbox image {digest} is not cached safely") + metadata_path = path / "metadata.json" + rootfs = path / "rootfs" + if metadata_path.is_symlink() or rootfs.is_symlink() or not rootfs.is_dir(): + raise SandboxImageError(f"sandbox image {digest} has unsafe cache content") + self._validate_required_commands(rootfs) + workspace = rootfs / "workspace" + if workspace.is_symlink() or not workspace.is_dir(): + raise SandboxImageError(f"sandbox image {digest} has no safe /workspace") + try: + value = json.loads(metadata_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + raise SandboxImageError(f"cannot read sandbox image {digest}: {exc}") from exc + if ( + not isinstance(value, dict) + or value.get("schema_version") != IMAGE_SCHEMA_VERSION + or value.get("digest") != digest + ): + raise SandboxImageError(f"sandbox image {digest} has incompatible metadata") + references = value.get("references") + if not isinstance(references, list) or not references: + raise SandboxImageError(f"sandbox image {digest} has invalid references") + normalized_references = tuple(normalize_image_reference(item) for item in references) + reference = normalize_image_reference(str(value.get("reference") or references[0])) + created = self._parse_timestamp(value.get("created_at"), "created_at").isoformat() + last_used = self._parse_timestamp(value.get("last_used_at"), "last_used_at").isoformat() + environment = self._normalize_environment(value.get("environment", [])) + try: + size_bytes = max(0, int(value.get("size_bytes"))) + except (TypeError, ValueError): + size_bytes = self._allocated_bytes(path) + return SandboxImageInfo( + digest=digest, + reference=reference, + references=normalized_references, + status="ready", + created_at=created, + last_used_at=last_used, + size_bytes=size_bytes, + os=str(value.get("os") or ""), + architecture=str(value.get("architecture") or ""), + rootfs=rootfs, + environment=environment, + ) + + def _write_info_locked(self, info: SandboxImageInfo) -> None: + self._write_info_path(self._image_path(info.digest) / "metadata.json", info) + + def _write_info_path(self, path: Path, info: SandboxImageInfo) -> None: + self._atomic_write_json( + path, + { + "schema_version": IMAGE_SCHEMA_VERSION, + "digest": info.digest, + "reference": info.reference, + "references": list(info.references), + "created_at": info.created_at, + "last_used_at": info.last_used_at, + "os": info.os, + "architecture": info.architecture, + "size_bytes": info.size_bytes, + "environment": list(info.environment), + }, + ) + + def _touch_reference_locked( + self, digest: str, reference: str + ) -> SandboxImageInfo: + info = self._read_info_locked(digest) + references = tuple(dict.fromkeys((*info.references, reference))) + updated = dataclasses.replace( + info, + reference=reference, + references=references, + last_used_at=self._now(), + ) + self._write_info_locked(updated) + return updated + + def _find_reference_locked(self, reference: str) -> str | None: + requested_digest = None + if "@" in reference: + with contextlib.suppress(SandboxImageError): + requested_digest = validate_digest(reference.rsplit("@", 1)[1]) + if requested_digest and self._image_path(requested_digest).is_dir(): + return requested_digest + aliases = self._read_aliases_locked() + aliased = aliases.get(reference) + if aliased: + with contextlib.suppress(SandboxImageError): + info = self._read_info_locked(aliased) + if reference in info.references: + return aliased + matches: list[tuple[dt.datetime, str]] = [] + for entry in self.config.cache_dir.iterdir(): + digest = self._digest_from_directory(entry.name) + if digest is None or entry.is_symlink() or not entry.is_dir(): + continue + with contextlib.suppress(SandboxImageError): + info = self._read_info_locked(digest) + if reference in info.references: + matches.append( + (self._parse_timestamp(info.created_at, "created_at"), digest) + ) + if not matches: + return None + digest = max(matches)[1] + self._set_alias_locked(reference, digest) + return digest + + def _read_aliases_locked(self) -> dict[str, str]: + path = self.config.cache_dir / "aliases.json" + if not path.exists(): + return {} + if path.is_symlink() or not path.is_file(): + raise SandboxImageError(f"sandbox image alias index is unsafe: {path}") + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + if not isinstance(value, dict): + return {} + result: dict[str, str] = {} + for raw_reference, raw_digest in value.items(): + try: + reference = normalize_image_reference(str(raw_reference)) + digest = validate_digest(str(raw_digest)) + except SandboxImageError: + continue + result[reference] = digest + return result + + def _set_alias_locked(self, reference: str, digest: str) -> None: + reference = normalize_image_reference(reference) + digest = validate_digest(digest) + aliases = self._read_aliases_locked() + if aliases.get(reference) == digest: + return + aliases[reference] = digest + self._atomic_write_json(self.config.cache_dir / "aliases.json", aliases) + + def _resolve_identifier_locked(self, identifier: str) -> str: + raw = str(identifier or "").strip() + with contextlib.suppress(SandboxImageError): + digest = validate_digest(raw) + if self._image_path(digest).is_dir(): + return digest + reference = normalize_image_reference(raw) + digest = self._find_reference_locked(reference) + if digest is None: + raise SandboxImageError(f"sandbox image {identifier!r} is not cached") + return digest + + def _delete_path_locked(self, digest: str, path: Path) -> None: + expected = self._image_path(digest) + if path != expected or path.is_symlink() or not path.is_dir(): + raise SandboxImageError(f"refusing unsafe sandbox image deletion at {path}") + aliases = { + reference: target + for reference, target in self._read_aliases_locked().items() + if target != digest + } + self._atomic_write_json(self.config.cache_dir / "aliases.json", aliases) + shutil.rmtree(path) + self._fsync_directory(self.config.cache_dir) + + def _broken_info(self, digest: str, path: Path, error: str) -> SandboxImageInfo: + return SandboxImageInfo( + digest=digest, + reference="", + references=(), + status="broken", + created_at="", + last_used_at="", + size_bytes=self._allocated_bytes(path), + runtime_error=error, + ) + + def _skopeo_command(self, command: str) -> list[str]: + if command not in {"inspect", "copy"}: + raise SandboxImageError(f"unsupported skopeo command {command!r}") + result = [str(self.config.skopeo), command] + if self.config.auth_file is not None: + auth_file = self.config.auth_file + if auth_file.is_symlink() or not auth_file.is_file(): + raise SandboxImageError( + f"registry auth file is not a regular non-symlink file: {auth_file}" + ) + option = "--src-authfile" if command == "copy" else "--authfile" + result.extend([option, str(auth_file)]) + return result + + def _require_tools(self) -> None: + for label, executable in ( + ("skopeo", self.config.skopeo), + ("umoci", self.config.umoci), + ): + if not executable.is_file() or not os.access(executable, os.X_OK): + raise SandboxImageError( + f"{label} not found at {executable}; run sandbox doctor" + ) + + def _run( + self, + argv: Sequence[str], + *, + timeout: float, + operation: str, + check: bool = True, + ) -> tuple[int, str, str, bool]: + try: + process = subprocess.Popen( + list(argv), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + ) + except OSError as exc: + raise SandboxImageError(f"could not {operation}: {exc}") from exc + buffers = [bytearray(), bytearray()] + truncated = [False, False] + + def drain(stream: Any, index: int) -> None: + while True: + chunk = stream.read(65536) + if not chunk: + return + remaining = self.config.max_output_bytes - len(buffers[index]) + if remaining > 0: + buffers[index].extend(chunk[:remaining]) + if len(chunk) > max(remaining, 0): + truncated[index] = True + + threads = [ + threading.Thread(target=drain, args=(process.stdout, 0), daemon=True), + threading.Thread(target=drain, args=(process.stderr, 1), daemon=True), + ] + for thread in threads: + thread.start() + try: + returncode = process.wait(timeout=timeout) + except subprocess.TimeoutExpired as exc: + process.kill() + with contextlib.suppress(subprocess.TimeoutExpired): + process.wait(timeout=2) + raise SandboxImageError(f"timed out after {timeout:g}s while trying to {operation}") from exc + finally: + for thread in threads: + thread.join(timeout=2) + stdout = bytes(buffers[0]).decode("utf-8", "replace") + stderr = bytes(buffers[1]).decode("utf-8", "replace") + if check and returncode: + detail = (stderr or stdout).strip() + if truncated[0] or truncated[1]: + detail += " [output truncated]" + raise SandboxImageError( + f"could not {operation}: {detail or f'exited {returncode}'}" + ) + return returncode, stdout, stderr, any(truncated) + + @staticmethod + def _pinned_reference(reference: str, digest: str) -> str: + digest = validate_digest(digest) + base = reference.rsplit("@", 1)[0] + slash = base.rfind("/") + colon = base.rfind(":") + if colon > slash: + base = base[:colon] + return f"{base}@{digest}" + + def _image_path(self, digest: str) -> Path: + digest = validate_digest(digest) + path = self.config.cache_dir / digest.replace(":", "-") + if path.parent != self.config.cache_dir: + raise SandboxImageError("sandbox image path escaped the cache directory") + return path + + @staticmethod + def _digest_from_directory(name: str) -> str | None: + if not re.fullmatch(r"sha256-[0-9a-f]{64}", name): + return None + return name.replace("-", ":", 1) + + def _ensure_layout(self) -> None: + self.config.cache_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + if self.config.cache_dir.is_symlink() or not self.config.cache_dir.is_dir(): + raise SandboxImageError( + f"sandbox image cache is not a safe directory: {self.config.cache_dir}" + ) + with contextlib.suppress(PermissionError): + self.config.cache_dir.chmod(0o700) + + @contextlib.contextmanager + def _cache_lock(self) -> Iterator[None]: + self._ensure_layout() + with self._thread_lock: + lock_path = self.config.cache_dir / ".lock" + if lock_path.is_symlink(): + raise SandboxImageError(f"refusing symlink image lock file {lock_path}") + with lock_path.open("a+", encoding="utf-8") as handle: + with contextlib.suppress(PermissionError): + os.fchmod(handle.fileno(), 0o600) + fcntl.flock(handle.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(handle.fileno(), fcntl.LOCK_UN) + + @staticmethod + def _parse_timestamp(value: Any, label: str) -> dt.datetime: + if not isinstance(value, str): + raise SandboxImageError(f"image metadata {label} must be an ISO timestamp") + try: + parsed = dt.datetime.fromisoformat(value) + except ValueError as exc: + raise SandboxImageError(f"image metadata {label} is invalid") from exc + if parsed.tzinfo is None: + raise SandboxImageError(f"image metadata {label} must include a timezone") + return parsed + + @staticmethod + def _now() -> str: + return dt.datetime.now(dt.timezone.utc).isoformat() + + @staticmethod + def _allocated_bytes(path: Path) -> int: + total = 0 + seen: set[tuple[int, int]] = set() + pending = [path] + while pending: + current = pending.pop() + try: + stat = current.lstat() + except OSError: + continue + identity = (stat.st_dev, stat.st_ino) + if identity in seen: + continue + seen.add(identity) + total += getattr(stat, "st_blocks", (stat.st_size + 511) // 512) * 512 + if current.is_dir() and not current.is_symlink(): + with contextlib.suppress(OSError): + pending.extend(current.iterdir()) + return total + + @staticmethod + def _atomic_write_json(path: Path, value: Mapping[str, Any]) -> None: + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{path.name}.", dir=path.parent + ) + temporary = Path(temporary_name) + try: + os.fchmod(descriptor, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + json.dump(value, handle, indent=2, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + SandboxImageManager._fsync_directory(path.parent) + except BaseException: + with contextlib.suppress(OSError): + os.close(descriptor) + temporary.unlink(missing_ok=True) + raise + + @staticmethod + def _fsync_directory(path: Path) -> None: + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + @staticmethod + def _atomic_probe(path: Path) -> None: + descriptor, name = tempfile.mkstemp(prefix=".sandbox-image-doctor.", dir=path) + temporary = Path(name) + replacement = path / f"{temporary.name}.ok" + try: + os.write(descriptor, b"ok") + os.fsync(descriptor) + os.close(descriptor) + descriptor = -1 + os.replace(temporary, replacement) + SandboxImageManager._fsync_directory(path) + finally: + if descriptor >= 0: + os.close(descriptor) + temporary.unlink(missing_ok=True) + replacement.unlink(missing_ok=True) diff --git a/plugins/_sandboxing/helpers/manager.py b/plugins/_sandboxing/helpers/manager.py new file mode 100644 index 000000000..9ed61bf9d --- /dev/null +++ b/plugins/_sandboxing/helpers/manager.py @@ -0,0 +1,1648 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import datetime as dt +import fcntl +import json +import os +import platform +import re +import shutil +import subprocess +import tempfile +import threading +import time +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path, PurePosixPath +from typing import Any, Literal + +from plugins._sandboxing.helpers.images import ( + SandboxImageError, + SandboxImageInfo, + SandboxImageManager, + validate_digest, +) + + +NetworkMode = Literal["host", "none"] +SandboxType = Literal["temporary", "permanent"] +SandboxStatus = Literal[ + "creating", + "running", + "stopped", + "recoverable", + "stale", + "broken", +] + +NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$") +ROOTFS_SNAPSHOT = "rootfs-upper.tar" +SCHEMA_VERSION = 2 +CAPABILITIES = ( + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FOWNER", + "CAP_FSETID", + "CAP_KILL", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_MKNOD", + "CAP_AUDIT_WRITE", + "CAP_SETFCAP", +) +_ABSENT_MARKERS = ( + "file does not exist", + "no such file", + "not found", + "container does not exist", +) +_PROTECTED_MOUNT_ROOTS = ("/proc", "/dev", "/sys", "/etc", "/shared") +_OWNERSHIP_KEYS = ("chat_id", "project_id", "agent_id") + + +class SandboxError(RuntimeError): + """A safe, user-facing sandbox management error.""" + + +@dataclass(frozen=True, slots=True) +class SandboxMount: + source: Path + destination: str + read_only: bool = True + + +@dataclass(frozen=True, slots=True) +class SandboxConfig: + runsc: Path + instances_dir: Path + runsc_root: Path + shared_dir: Path + default_image: str + temporary_lifetime_days: float = 7.0 + start_timeout: float = 8.0 + stop_timeout: float = 3.0 + snapshot_timeout: float = 300.0 + exec_timeout: float = 600.0 + state_timeout: float = 3.0 + delete_timeout: float = 5.0 + max_output_bytes: int = 1_048_576 + + +@dataclass(frozen=True, slots=True) +class SandboxInfo: + name: str + status: SandboxStatus + sandbox_type: SandboxType + network: NetworkMode + created_at: str + last_used_at: str + snapshot_at: str | None + expires_at: str | None + image_ref: str = "" + image_digest: str = "" + size_bytes: int = 0 + mounts: tuple[SandboxMount, ...] = () + ownership: Mapping[str, str | None] = field(default_factory=dict) + runtime_error: str | None = None + + +@dataclass(frozen=True, slots=True) +class ExecResult: + argv: tuple[str, ...] + exit_code: int + stdout: str + stderr: str + output_truncated: bool = False + + +def validate_name(name: str) -> str: + name = str(name or "") + if not NAME_RE.fullmatch(name): + raise SandboxError( + f"invalid sandbox name {name!r}; expected {NAME_RE.pattern}" + ) + return name + + +def runtime_is_absent(error: str | None) -> bool: + if not error: + return False + lowered = error.lower() + return any(marker in lowered for marker in _ABSENT_MARKERS) + + +def allocated_bytes(path: Path) -> int: + total = 0 + seen: set[tuple[int, int]] = set() + pending = [path] + while pending: + current = pending.pop() + try: + stat = current.lstat() + except OSError: + continue + identity = (stat.st_dev, stat.st_ino) + if identity in seen: + continue + seen.add(identity) + total += getattr(stat, "st_blocks", (stat.st_size + 511) // 512) * 512 + if current.is_dir() and not current.is_symlink(): + with contextlib.suppress(OSError): + pending.extend(current.iterdir()) + return total + + +class SandboxManager: + """Manage Agent Zero-owned OCI sandboxes directly through gVisor runsc.""" + + def __init__(self, config: SandboxConfig, images: SandboxImageManager) -> None: + self.config = self._validated_config(config) + self.images = images + image_cache = self.images.config.cache_dir.resolve(strict=False) + instances = self.config.instances_dir.resolve(strict=False) + shared = self.config.shared_dir.resolve(strict=False) + if ( + image_cache == instances + or image_cache in instances.parents + or instances in image_cache.parents + ): + raise SandboxError("sandbox instances and image cache must be separate") + if ( + image_cache == shared + or image_cache in shared.parents + or shared in image_cache.parents + ): + raise SandboxError("shared exchange and image cache must be separate") + self._locks_guard = threading.Lock() + self._locks: dict[str, threading.RLock] = {} + + @staticmethod + def _validated_config(config: SandboxConfig) -> SandboxConfig: + paths = { + "runsc": config.runsc, + "instances_dir": config.instances_dir, + "runsc_root": config.runsc_root, + "shared_dir": config.shared_dir, + } + for label, value in paths.items(): + if not value.is_absolute(): + raise SandboxError(f"{label} must be an absolute path: {value}") + instances = config.instances_dir.resolve(strict=False) + shared = config.shared_dir.resolve(strict=False) + if instances == shared or instances in shared.parents or shared in instances.parents: + raise SandboxError("private sandbox state and shared exchange must be separate") + if config.temporary_lifetime_days <= 0: + raise SandboxError("temporary_lifetime_days must be positive") + if config.max_output_bytes < 4096: + raise SandboxError("max_output_bytes must be at least 4096") + return config + + def doctor(self) -> list[str]: + diagnostics: list[str] = [] + if platform.system() != "Linux": + diagnostics.append("ERROR: gVisor sandboxes require Linux") + else: + diagnostics.append(f"OK: Linux {platform.machine()}") + + if not self.config.runsc.is_file() or not os.access(self.config.runsc, os.X_OK): + diagnostics.append(f"ERROR: runsc is not executable at {self.config.runsc}") + else: + try: + result = subprocess.run( + [str(self.config.runsc), "--version"], + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + check=False, + shell=False, + timeout=5, + ) + version = " ".join(result.stdout.split()) + if result.returncode: + diagnostics.append( + f"ERROR: runsc --version exited {result.returncode}: {version}" + ) + else: + diagnostics.append(f"OK: {version or 'runsc available'}") + except (OSError, subprocess.TimeoutExpired) as exc: + diagnostics.append(f"ERROR: runsc version check failed: {exc}") + + diagnostics.extend(self.images.doctor()) + + try: + self._ensure_layout() + self._atomic_probe(self.config.instances_dir.parent) + diagnostics.append(f"OK: sandbox state at {self.config.instances_dir}") + except OSError as exc: + diagnostics.append(f"ERROR: sandbox state is not writable: {exc}") + try: + self._ensure_shared_directory() + self._atomic_probe(self.config.shared_dir) + diagnostics.append(f"OK: shared exchange at {self.config.shared_dir}") + except OSError as exc: + diagnostics.append(f"ERROR: shared exchange is not writable: {exc}") + + instances = self.config.instances_dir.resolve(strict=False) + shared = self.config.shared_dir.resolve(strict=False) + if instances == shared or instances in shared.parents or shared in instances.parents: + diagnostics.append("ERROR: private sandbox state and shared exchange must be separate") + + status = self._proc_status() + try: + caps = int(status.get("CapEff", "0"), 16) + except ValueError: + caps = 0 + if platform.system() == "Linux" and not caps & (1 << 18): + diagnostics.append( + "ERROR: CAP_SYS_CHROOT is unavailable; use the documented native or Docker launch policy" + ) + if status.get("Seccomp") == "2": + diagnostics.append( + "WARNING: an outer seccomp filter is active; nested systrap requires the documented profile" + ) + return diagnostics + + def list(self) -> list[SandboxInfo]: + self._ensure_layout() + results: list[SandboxInfo] = [] + with self._index_lock(exclusive=False): + for entry in sorted(self.config.instances_dir.iterdir(), key=lambda p: p.name): + if entry.is_symlink() or not entry.is_dir() or not NAME_RE.fullmatch(entry.name): + continue + try: + results.append(self.inspect(entry.name)) + except SandboxError as exc: + results.append(self._broken_info(entry.name, str(exc))) + return results + + def inspect(self, name: str) -> SandboxInfo: + name = validate_name(name) + path = self._instance_path(name) + if not path.exists() or path.is_symlink() or not path.is_dir(): + raise SandboxError(f"sandbox {name!r} does not exist") + try: + metadata = self._read_metadata(name) + except SandboxError as exc: + return self._broken_info(name, str(exc)) + state, error = self._runtime_state(name, metadata) + snapshot = self._valid_snapshot(name, metadata) + if state is not None: + observed = str(state.get("status") or "") + if observed == "running": + status: SandboxStatus = "running" + elif observed == "stopped": + status = "stopped" + elif observed in {"created", "creating"}: + status = "creating" + else: + status = "broken" + error = f"unexpected runsc status {observed!r}" + elif runtime_is_absent(error): + if snapshot is None: + status = "stale" + elif metadata.get("last_known_status") == "stopped": + status = "stopped" + else: + status = "recoverable" + else: + status = "broken" + image_error: str | None = None + if status != "running": + try: + self.images.inspect(str(metadata.get("image_digest") or "")) + except SandboxImageError as exc: + image_error = f"base image will be restored on start: {exc}" + if status not in {"stopped", "recoverable"}: + status = "broken" + return self._info( + name, + metadata, + status, + image_error or (error if status == "broken" else None), + ) + + def create( + self, + name: str, + *, + network: NetworkMode = "host", + sandbox_type: SandboxType = "temporary", + image: str = "", + mounts: Sequence[SandboxMount | Mapping[str, Any]] = (), + ownership: Mapping[str, str | None] | None = None, + ) -> SandboxInfo: + name = validate_name(name) + network = self._validate_network(network) + sandbox_type = self._validate_type(sandbox_type) + normalized_mounts = self._normalize_mounts(mounts) + normalized_owner = self._normalize_ownership(ownership) + self._ensure_layout() + with self._index_lock(exclusive=False): + path = self._instance_path(name) + if path.exists() or path.is_symlink(): + raise SandboxError(f"sandbox {name!r} already exists") + self._require_runtime_artifacts() + try: + image_info = self.images.ensure(image or self.config.default_image) + except SandboxImageError as exc: + raise SandboxError(str(exc)) from exc + self._ensure_shared_directory() + + with self._name_thread_lock(name), self._index_lock(exclusive=True): + try: + image_info = self.images.ensure( + image_info.reference, digest=image_info.digest + ) + except SandboxImageError as exc: + raise SandboxError(str(exc)) from exc + path = self._instance_path(name) + if path.exists() or path.is_symlink(): + raise SandboxError(f"sandbox {name!r} already exists") + bundle = path / "bundle" + overlay = path / "overlay" + logs = path / "logs" + for directory in (path, bundle, overlay, logs): + directory.mkdir(mode=0o700) + (path / ".lock").touch(mode=0o600, exist_ok=True) + now = self._now() + metadata: dict[str, Any] = { + "schema_version": SCHEMA_VERSION, + "name": name, + "sandbox_type": sandbox_type, + "network": network, + "created_at": now, + "last_used_at": now, + "snapshot_at": None, + "rootfs_snapshot": None, + "image_ref": image_info.reference, + "image_digest": image_info.digest, + "launch_mode": "starting", + "launcher_pid": None, + "last_known_status": "creating", + "mounts": [self._mount_json(mount) for mount in normalized_mounts], + "ownership": normalized_owner, + } + try: + self._refresh_bundle(name, metadata) + self._atomic_write_json(path / "metadata.json", metadata) + self._launch(name, metadata) + self._save_locked(name, metadata) + return self.inspect(name) + except BaseException: + cleaned = self._force_runtime_delete(name, metadata) + if cleaned and path.exists() and not path.is_symlink(): + shutil.rmtree(path) + elif not cleaned: + self._append_log( + path / "logs" / "launcher.log", + "runtime cleanup was not confirmed; preserving state for diagnosis", + ) + raise + + def ensure_running( + self, + name: str, + *, + network: NetworkMode = "host", + sandbox_type: SandboxType = "temporary", + image: str = "", + ) -> SandboxInfo: + name = validate_name(name) + path = self._instance_path(name) + if not path.exists() and not path.is_symlink(): + return self.create( + name, + network=network, + sandbox_type=sandbox_type, + image=image, + ) + info = self.inspect(name) + if info.status == "running": + self.touch(name) + return self.inspect(name) + if info.status in {"stopped", "recoverable"}: + return self.start(name) + raise SandboxError( + f"sandbox {name!r} cannot be started automatically from status {info.status!r}" + ) + + def exec( + self, + name: str, + argv: Sequence[str], + *, + cwd: str = "/workspace", + timeout: float | None = None, + ) -> ExecResult: + name = validate_name(name) + args = tuple(str(item) for item in argv) + if not args or not args[0]: + raise SandboxError("exec requires a non-empty argv") + cwd = self._validate_guest_path(cwd, label="cwd") + with self._operation_lock(name): + metadata = self._read_metadata(name) + self._require_running(name, metadata) + command = self._runsc_command( + name, + metadata, + "exec", + f"--cwd={cwd}", + "--user=0:0", + name, + *args, + ) + result = self._run_captured( + command, + timeout=self.config.exec_timeout if timeout is None else timeout, + operation=f"execute in sandbox {name!r}", + ) + self._touch_locked(name, metadata) + return ExecResult( + argv=args, + exit_code=result[0], + stdout=result[1], + stderr=result[2], + output_truncated=result[3], + ) + + def bash( + self, + name: str, + script: str, + *, + cwd: str = "/workspace", + timeout: float | None = None, + ) -> ExecResult: + return self.exec( + name, + ["/bin/bash", "-lc", str(script)], + cwd=cwd, + timeout=timeout, + ) + + def interactive_command(self, name: str, *, cwd: str = "/workspace") -> list[str]: + name = validate_name(name) + cwd = self._validate_guest_path(cwd, label="cwd") + with self._operation_lock(name): + metadata = self._read_metadata(name) + self._require_running(name, metadata) + self._touch_locked(name, metadata) + return self._runsc_command( + name, + metadata, + "exec", + f"--cwd={cwd}", + "--user=0:0", + name, + "/bin/bash", + "--login", + ) + + def save(self, name: str) -> SandboxInfo: + name = validate_name(name) + with self._operation_lock(name): + metadata = self._read_metadata(name) + self._require_running(name, metadata) + self._save_locked(name, metadata) + self._touch_locked(name, metadata) + return self.inspect(name) + + def stop(self, name: str) -> SandboxInfo: + name = validate_name(name) + with self._operation_lock(name): + metadata = self._read_metadata(name) + state, error = self._runtime_state(name, metadata) + snapshot = self._valid_snapshot(name, metadata) + if state is None: + if runtime_is_absent(error) and snapshot is not None: + metadata["last_known_status"] = "stopped" + self._atomic_write_json( + self._instance_path(name) / "metadata.json", metadata + ) + return self.inspect(name) + raise SandboxError( + f"cannot stop sandbox {name!r}: {error or 'runtime state is unknown'}" + ) + status = state.get("status") + if status == "running": + self._save_locked(name, metadata) + self._stop_runtime(name, metadata) + elif status != "stopped": + raise SandboxError(f"cannot stop sandbox {name!r} from status {status!r}") + elif snapshot is None: + raise SandboxError( + f"sandbox {name!r} is stopped but has no restartable snapshot" + ) + if not self._force_runtime_delete(name, metadata): + raise SandboxError( + f"sandbox {name!r} stopped but runtime cleanup was not confirmed" + ) + metadata["last_used_at"] = self._now() + metadata["last_known_status"] = "stopped" + self._atomic_write_json(self._instance_path(name) / "metadata.json", metadata) + return self.inspect(name) + + def start(self, name: str) -> SandboxInfo: + name = validate_name(name) + self._require_runtime_artifacts() + self._ensure_shared_directory() + with self._operation_lock(name): + metadata = self._read_metadata(name) + try: + self.images.ensure( + str(metadata.get("image_ref") or ""), + digest=str(metadata.get("image_digest") or ""), + ) + except SandboxImageError as exc: + raise SandboxError( + f"cannot restore pinned base image for {name!r}: {exc}" + ) from exc + state, error = self._runtime_state(name, metadata) + if state is not None and state.get("status") == "running": + self._touch_locked(name, metadata) + return self.inspect(name) + if state is not None: + if not self._force_runtime_delete(name, metadata): + raise SandboxError(f"could not clear stopped runtime for {name!r}") + elif error and not runtime_is_absent(error): + raise SandboxError(f"cannot determine runtime state for {name!r}: {error}") + snapshot = self._valid_snapshot(name, metadata) + if snapshot is None: + raise SandboxError(f"sandbox {name!r} has no valid restart snapshot") + self._refresh_bundle(name, metadata, snapshot=snapshot) + self._launch(name, metadata) + self._touch_locked(name, metadata) + return self.inspect(name) + + def delete(self, name: str, *, missing_ok: bool = False) -> bool: + name = validate_name(name) + self._ensure_layout() + with self._name_thread_lock(name), self._index_lock(exclusive=True): + path = self._instance_path(name) + if not path.exists() and not path.is_symlink(): + if missing_ok: + return False + raise SandboxError(f"sandbox {name!r} does not exist") + if path.is_symlink() or not path.is_dir(): + raise SandboxError(f"refusing to delete unsafe sandbox entry {path}") + with self._file_lock(path / ".lock"): + metadata = self._read_metadata(name) + self._delete_locked(name, path, metadata) + return True + + def touch(self, name: str) -> None: + name = validate_name(name) + with self._operation_lock(name): + metadata = self._read_metadata(name) + self._touch_locked(name, metadata) + + def cleanup_expired(self, *, now: dt.datetime | None = None) -> list[str]: + current = now or dt.datetime.now(dt.timezone.utc) + deleted: list[str] = [] + for info in self.list(): + if info.sandbox_type != "temporary" or not info.expires_at: + continue + try: + expires = dt.datetime.fromisoformat(info.expires_at) + except ValueError: + continue + if expires <= current and self._delete_if_expired(info.name, current): + deleted.append(info.name) + return deleted + + def list_images(self) -> list[SandboxImageInfo]: + usage = self._image_usage() + try: + images = self.images.list() + except SandboxImageError as exc: + raise SandboxError(str(exc)) from exc + return [ + dataclasses.replace(info, used_by=tuple(sorted(usage.get(info.digest, ())))) + for info in images + ] + + def inspect_image(self, identifier: str) -> SandboxImageInfo: + try: + info = self.images.inspect(identifier) + except SandboxImageError as exc: + raise SandboxError(str(exc)) from exc + usage = self._image_usage() + return dataclasses.replace( + info, used_by=tuple(sorted(usage.get(info.digest, ()))) + ) + + def pull_image(self, reference: str = "") -> SandboxImageInfo: + try: + info = self.images.pull(reference or self.config.default_image) + except SandboxImageError as exc: + raise SandboxError(str(exc)) from exc + return dataclasses.replace( + info, used_by=tuple(sorted(self._image_usage().get(info.digest, ()))) + ) + + def delete_image(self, identifier: str, *, missing_ok: bool = False) -> bool: + try: + digest = validate_digest(identifier) + except SandboxImageError: + try: + digest = self.images.inspect(identifier).digest + except SandboxImageError as inspect_exc: + if missing_ok: + return False + raise SandboxError(str(inspect_exc)) from inspect_exc + with self._index_lock(exclusive=True): + usage = self._image_usage_locked(strict=True) + referenced = sorted(usage.get(digest, ())) + if referenced: + raise SandboxError( + f"image {digest} is still used by sandboxes: {', '.join(referenced)}" + ) + try: + return self.images.delete(digest, missing_ok=missing_ok) + except SandboxImageError as exc: + raise SandboxError(str(exc)) from exc + + def cleanup_images(self, *, now: dt.datetime | None = None) -> list[str]: + with self._index_lock(exclusive=True): + used = set(self._image_usage_locked(strict=True)) + try: + return self.images.cleanup(used_digests=used, now=now) + except SandboxImageError as exc: + raise SandboxError(str(exc)) from exc + + def _image_usage(self) -> dict[str, set[str]]: + with self._index_lock(exclusive=False): + return self._image_usage_locked() + + def _image_usage_locked(self, *, strict: bool = False) -> dict[str, set[str]]: + usage: dict[str, set[str]] = {} + if not self.config.instances_dir.exists(): + return usage + for entry in self.config.instances_dir.iterdir(): + if entry.is_symlink() or not entry.is_dir() or not NAME_RE.fullmatch(entry.name): + continue + metadata_path = entry / "metadata.json" + if metadata_path.is_symlink() or not metadata_path.is_file(): + if strict: + raise SandboxError( + f"cannot safely determine image use for sandbox {entry.name!r}" + ) + continue + try: + metadata = json.loads(metadata_path.read_text(encoding="utf-8")) + if not isinstance(metadata, dict): + raise ValueError("metadata is not an object") + digest = validate_digest(str(metadata.get("image_digest") or "")) + except (OSError, json.JSONDecodeError, SandboxImageError, ValueError) as exc: + if strict: + raise SandboxError( + f"cannot safely determine image use for sandbox {entry.name!r}: {exc}" + ) from exc + continue + usage.setdefault(digest, set()).add(entry.name) + return usage + + def _delete_if_expired(self, name: str, now: dt.datetime) -> bool: + """Recheck expiry while holding the same locks as execution and deletion.""" + name = validate_name(name) + self._ensure_layout() + with self._name_thread_lock(name), self._index_lock(exclusive=True): + path = self._instance_path(name) + if not path.exists() and not path.is_symlink(): + return False + if path.is_symlink() or not path.is_dir(): + raise SandboxError(f"refusing to delete unsafe sandbox entry {path}") + with self._file_lock(path / ".lock"): + metadata = self._read_metadata(name) + if self._validate_type(metadata.get("sandbox_type")) != "temporary": + return False + expires_at = self._expiry(str(metadata.get("last_used_at") or "")) + if not expires_at: + return False + try: + expires = dt.datetime.fromisoformat(expires_at) + except ValueError: + return False + if expires > now: + return False + self._delete_locked(name, path, metadata) + return True + + def _delete_locked( + self, name: str, path: Path, metadata: Mapping[str, Any] + ) -> None: + state, error = self._runtime_state(name, metadata) + if state is not None: + self._stop_runtime(name, metadata) + elif error and not runtime_is_absent(error): + raise SandboxError( + f"cannot safely determine runtime state for {name!r}: {error}" + ) + if not self._force_runtime_delete(name, metadata): + raise SandboxError(f"runsc could not delete sandbox {name!r}") + shutil.rmtree(path) + self._fsync_directory(self.config.instances_dir) + + def runsc_command_for_test( + self, + name: str, + network: NetworkMode, + sandbox_type: SandboxType, + *arguments: str, + ) -> list[str]: + metadata = {"network": network, "sandbox_type": sandbox_type} + return self._runsc_command(validate_name(name), metadata, *arguments) + + def oci_config_for_test( + self, + name: str, + network: NetworkMode, + sandbox_type: SandboxType, + mounts: Sequence[SandboxMount | Mapping[str, Any]] = (), + snapshot: Path | None = None, + ) -> dict[str, Any]: + try: + image = self.images.ensure(self.config.default_image) + except SandboxImageError as exc: + raise SandboxError(str(exc)) from exc + metadata = { + "network": self._validate_network(network), + "sandbox_type": self._validate_type(sandbox_type), + "image_ref": image.reference, + "image_digest": image.digest, + "mounts": [self._mount_json(m) for m in self._normalize_mounts(mounts)], + } + bundle = self._instance_path(validate_name(name)) / "bundle" + return self._oci_config(name, metadata, bundle, snapshot=snapshot) + + def _validated_metadata(self, name: str, value: Any) -> dict[str, Any]: + if not isinstance(value, dict): + raise SandboxError(f"sandbox {name!r} metadata is not an object") + if value.get("schema_version") != SCHEMA_VERSION or value.get("name") != name: + raise SandboxError(f"sandbox {name!r} has incompatible metadata") + self._validate_network(value.get("network")) + self._validate_type(value.get("sandbox_type")) + for key in ("created_at", "last_used_at"): + self._parse_timestamp(value.get(key), key) + image_ref = str(value.get("image_ref") or "").strip() + if not image_ref: + raise SandboxError(f"sandbox {name!r} has no base image reference") + try: + value["image_digest"] = validate_digest( + str(value.get("image_digest") or "") + ) + except SandboxImageError as exc: + raise SandboxError(f"sandbox {name!r} has invalid image metadata: {exc}") from exc + mounts = value.get("mounts", []) + if not isinstance(mounts, list): + raise SandboxError(f"sandbox {name!r} has invalid mount metadata") + self._normalize_mounts(mounts) + value["ownership"] = self._normalize_ownership(value.get("ownership")) + return value + + def _read_metadata(self, name: str) -> dict[str, Any]: + path = self._instance_path(name) + if path.is_symlink() or not path.is_dir(): + raise SandboxError(f"sandbox {name!r} has an unsafe instance path") + metadata_path = path / "metadata.json" + if metadata_path.is_symlink(): + raise SandboxError(f"sandbox {name!r} metadata must not be a symlink") + try: + with metadata_path.open(encoding="utf-8") as handle: + value = json.load(handle) + except FileNotFoundError as exc: + raise SandboxError(f"sandbox {name!r} does not exist") from exc + except (OSError, json.JSONDecodeError) as exc: + raise SandboxError(f"cannot read metadata for {name!r}: {exc}") from exc + return self._validated_metadata(name, value) + + def _info( + self, + name: str, + metadata: Mapping[str, Any], + status: SandboxStatus, + runtime_error: str | None, + ) -> SandboxInfo: + mounts = tuple(self._normalize_mounts(metadata.get("mounts", []))) + last_used = str(metadata.get("last_used_at") or metadata.get("created_at") or "") + sandbox_type = self._validate_type(metadata.get("sandbox_type")) + expires = self._expiry(last_used) if sandbox_type == "temporary" else None + return SandboxInfo( + name=name, + status=status, + sandbox_type=sandbox_type, + network=self._validate_network(metadata.get("network")), + created_at=str(metadata.get("created_at") or ""), + last_used_at=last_used, + snapshot_at=str(metadata.get("snapshot_at")) if metadata.get("snapshot_at") else None, + expires_at=expires, + image_ref=str(metadata.get("image_ref") or ""), + image_digest=str(metadata.get("image_digest") or ""), + size_bytes=allocated_bytes(self._instance_path(name)), + mounts=mounts, + ownership=dict(self._normalize_ownership(metadata.get("ownership"))), + runtime_error=runtime_error, + ) + + def _broken_info(self, name: str, error: str) -> SandboxInfo: + return SandboxInfo( + name=name, + status="broken", + sandbox_type="temporary", + network="host", + created_at="", + last_used_at="", + snapshot_at=None, + expires_at=None, + image_ref="", + image_digest="", + size_bytes=allocated_bytes(self._instance_path(name)), + ownership={key: None for key in _OWNERSHIP_KEYS}, + runtime_error=error, + ) + + def _runtime_state( + self, name: str, metadata: Mapping[str, Any] + ) -> tuple[dict[str, Any] | None, str | None]: + try: + result = subprocess.run( + self._runsc_command(name, metadata, "state", name), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + check=False, + shell=False, + timeout=self.config.state_timeout, + ) + except subprocess.TimeoutExpired: + return None, "runsc state timed out" + except OSError as exc: + return None, str(exc) + if result.returncode: + detail = (result.stderr or result.stdout).strip() + return None, detail or f"runsc state exited {result.returncode}" + try: + state = json.loads(result.stdout) + except json.JSONDecodeError as exc: + return None, f"invalid JSON from runsc state: {exc}" + if not isinstance(state, dict) or not isinstance(state.get("status"), str): + return None, "runsc state returned an invalid object" + return state, None + + def _runsc_command( + self, name: str, metadata: Mapping[str, Any], *arguments: str + ) -> list[str]: + network = self._validate_network(metadata.get("network")) + sandbox_type = self._validate_type(metadata.get("sandbox_type")) + path = self._instance_path(name) + command_name = arguments[0] if arguments else "unknown" + overlay = ( + "--overlay2=root:memory" + if sandbox_type == "temporary" + else f"--overlay2=root:dir={path / 'overlay'}" + ) + return [ + str(self.config.runsc), + "--allow-rootfs-tar-annotation", + f"--root={self.config.runsc_root}", + "--rootless=true", + "--platform=systrap", + "--directfs=false", + "--file-access=exclusive", + "--file-access-mounts=shared", + f"--network={network}", + overlay, + f"--log={path / 'logs' / f'runsc-{command_name}.log'}", + *arguments, + ] + + def _oci_config( + self, + name: str, + metadata: Mapping[str, Any], + bundle: Path, + *, + snapshot: Path | None = None, + ) -> dict[str, Any]: + network = self._validate_network(metadata.get("network")) + try: + image = self.images.inspect(str(metadata.get("image_digest") or "")) + except SandboxImageError as exc: + raise SandboxError(f"base image is unavailable: {exc}") from exc + if image.rootfs is None: + raise SandboxError(f"base image {image.digest} has no usable root filesystem") + environment: dict[str, str] = {} + for item in image.environment: + key, separator, value = item.partition("=") + if separator: + environment[key] = value + environment.setdefault( + "PATH", + "/root/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + ) + environment.update( + { + "HOME": "/root", + "LANG": environment.get("LANG", "C.UTF-8"), + "TERM": "xterm-256color", + "PAGER": "cat", + "GIT_PAGER": "cat", + "PIP_DISABLE_PIP_VERSION_CHECK": "1", + "PIP_NO_CACHE_DIR": "1", + "PIP_ROOT_USER_ACTION": "ignore", + "PIPX_HOME": "/root/.local/share/pipx", + "PIPX_BIN_DIR": "/root/.local/bin", + "UV_TOOL_BIN_DIR": "/root/.local/bin", + } + ) + namespaces = [ + {"type": "pid"}, + {"type": "ipc"}, + {"type": "uts"}, + {"type": "mount"}, + ] + if network == "none": + namespaces.append({"type": "network"}) + mounts: list[dict[str, Any]] = [ + {"destination": "/proc", "type": "proc", "source": "proc", "options": ["nosuid", "noexec", "nodev"]}, + {"destination": "/dev", "type": "tmpfs", "source": "tmpfs", "options": ["nosuid", "strictatime", "mode=755", "size=65536k"]}, + {"destination": "/dev/pts", "type": "devpts", "source": "devpts", "options": ["nosuid", "noexec", "newinstance", "ptmxmode=0666", "mode=0620", "gid=5"]}, + {"destination": "/dev/shm", "type": "tmpfs", "source": "shm", "options": ["nosuid", "noexec", "nodev", "mode=1777", "size=65536k"]}, + {"destination": "/dev/mqueue", "type": "mqueue", "source": "mqueue", "options": ["nosuid", "noexec", "nodev"]}, + {"destination": "/sys", "type": "sysfs", "source": "sysfs", "options": ["nosuid", "noexec", "nodev", "ro"]}, + {"destination": "/tmp", "type": "tmpfs", "source": "tmpfs", "options": ["nosuid", "nodev", "mode=1777"]}, + {"destination": "/run", "type": "tmpfs", "source": "tmpfs", "options": ["nosuid", "nodev", "mode=755"]}, + {"destination": "/etc/resolv.conf", "type": "bind", "source": str(bundle / "resolv.conf"), "options": ["bind", "ro", "nosuid", "nodev", "noexec"]}, + {"destination": "/etc/hosts", "type": "bind", "source": str(bundle / "hosts"), "options": ["bind", "ro", "nosuid", "nodev", "noexec"]}, + {"destination": "/shared", "type": "bind", "source": str(self.config.shared_dir), "options": ["rbind", "rw", "nosuid", "nodev"]}, + ] + for item in self._normalize_mounts(metadata.get("mounts", [])): + options = ["rbind", "ro" if item.read_only else "rw", "nosuid", "nodev"] + mounts.append( + { + "destination": item.destination, + "type": "bind", + "source": str(item.source), + "options": options, + } + ) + config: dict[str, Any] = { + "ociVersion": "1.0.2", + "process": { + "terminal": False, + "user": {"uid": 0, "gid": 0}, + "args": ["/bin/sh", "-c", "trap 'exit 0' TERM INT; while :; do sleep 3600; done"], + "env": [f"{key}={value}" for key, value in environment.items()], + "cwd": "/workspace", + "capabilities": { + "bounding": list(CAPABILITIES), + "effective": list(CAPABILITIES), + "inheritable": [], + "permitted": list(CAPABILITIES), + "ambient": [], + }, + "noNewPrivileges": False, + "rlimits": [{"type": "RLIMIT_NOFILE", "hard": 65535, "soft": 65535}], + }, + "root": {"path": str(image.rootfs), "readonly": False}, + "hostname": name, + "mounts": mounts, + "linux": { + "namespaces": namespaces, + "maskedPaths": [ + "/proc/acpi", "/proc/kcore", "/proc/keys", "/proc/latency_stats", + "/proc/timer_list", "/proc/timer_stats", "/proc/sched_debug", "/sys/firmware", + ], + "readonlyPaths": [ + "/proc/asound", "/proc/bus", "/proc/fs", "/proc/irq", + "/proc/sys", "/proc/sysrq-trigger", + ], + }, + } + if snapshot is not None: + config["annotations"] = {"dev.gvisor.tar.rootfs.upper": str(snapshot)} + return config + + def _refresh_bundle( + self, + name: str, + metadata: Mapping[str, Any], + *, + snapshot: Path | None = None, + ) -> None: + bundle = self._instance_path(name) / "bundle" + for source, target_name in ( + (Path("/etc/resolv.conf"), "resolv.conf"), + (Path("/etc/hosts"), "hosts"), + ): + try: + content = source.read_text(encoding="utf-8") + except OSError as exc: + raise SandboxError(f"cannot read outer {source}: {exc}") from exc + self._atomic_write_text(bundle / target_name, content, mode=0o644) + self._atomic_write_json( + bundle / "config.json", + self._oci_config(name, metadata, bundle, snapshot=snapshot), + ) + + def _launch(self, name: str, metadata: dict[str, Any]) -> None: + path = self._instance_path(name) + bundle = path / "bundle" + logs = path / "logs" + launcher_log = logs / "launcher.log" + detached = self._runsc_command( + name, + metadata, + "run", + "--detach", + f"--bundle={bundle}", + f"--user-log={logs / 'user.log'}", + name, + ) + detached_result: subprocess.CompletedProcess[bytes] | None = None + with launcher_log.open("ab", buffering=0) as output: + output.write(b"== detached launch ==\n") + try: + detached_result = subprocess.run( + detached, + stdin=subprocess.DEVNULL, + stdout=output, + stderr=subprocess.STDOUT, + check=False, + shell=False, + timeout=self.config.start_timeout, + ) + except subprocess.TimeoutExpired: + output.write(b"detached run command timed out\n") + state = None + error = "detached run command timed out" + if detached_result is not None and detached_result.returncode == 0: + state, error = self._wait_for_status(name, metadata, {"running"}, self.config.start_timeout) + elif detached_result is not None: + error = f"detached run exited {detached_result.returncode}" + if state is None or state.get("status") != "running": + self._append_log( + launcher_log, + f"detached launch unavailable ({error}); trying attached fallback", + ) + if not self._force_runtime_delete(name, metadata): + raise SandboxError( + f"could not clean failed launch for {name!r}; state retained at {path}" + ) + with launcher_log.open("ab", buffering=0) as output: + output.write(b"== attached fallback launch ==\n") + launcher = subprocess.Popen( + self._runsc_command( + name, + metadata, + "run", + f"--bundle={bundle}", + f"--user-log={logs / 'user.log'}", + name, + ), + stdin=subprocess.DEVNULL, + stdout=output, + stderr=subprocess.STDOUT, + start_new_session=True, + shell=False, + ) + metadata["launch_mode"] = "attached-fallback" + metadata["launcher_pid"] = launcher.pid + self._atomic_write_json(path / "metadata.json", metadata) + state, error = self._wait_for_status( + name, + metadata, + {"running"}, + self.config.start_timeout, + launcher=launcher, + ) + if state is None or state.get("status") != "running": + with contextlib.suppress(ProcessLookupError): + launcher.terminate() + with contextlib.suppress(subprocess.TimeoutExpired): + launcher.wait(timeout=1) + if launcher.poll() is None: + with contextlib.suppress(ProcessLookupError): + launcher.kill() + raise SandboxError( + f"sandbox {name!r} did not reach running state: {error}; " + f"launcher log: {self._log_tail(launcher_log)}" + ) + else: + metadata["launch_mode"] = "detached" + metadata["launcher_pid"] = None + metadata["last_known_status"] = "running" + self._atomic_write_json(path / "metadata.json", metadata) + + def _save_locked(self, name: str, metadata: dict[str, Any]) -> None: + path = self._instance_path(name) + snapshot = path / ROOTFS_SNAPSHOT + descriptor, temp_name = tempfile.mkstemp(prefix=f".{ROOTFS_SNAPSHOT}.", dir=path) + os.close(descriptor) + temporary = Path(temp_name) + temporary.unlink() + try: + result = subprocess.run( + self._runsc_command( + name, + metadata, + "tar", + "rootfs-upper", + f"--file={temporary}", + name, + ), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + check=False, + shell=False, + timeout=self.config.snapshot_timeout, + ) + except subprocess.TimeoutExpired as exc: + temporary.unlink(missing_ok=True) + raise SandboxError( + f"filesystem snapshot timed out for {name!r}; sandbox remains running" + ) from exc + except OSError as exc: + temporary.unlink(missing_ok=True) + raise SandboxError(f"could not snapshot filesystem for {name!r}: {exc}") from exc + if result.stdout: + self._append_log(path / "logs" / "snapshot.log", result.stdout) + if result.returncode or not temporary.is_file() or temporary.is_symlink(): + temporary.unlink(missing_ok=True) + detail = result.stdout.strip() or f"runsc tar exited {result.returncode}" + raise SandboxError( + f"could not snapshot filesystem for {name!r}: {detail}; sandbox remains running" + ) + temporary.chmod(0o600) + with temporary.open("rb") as handle: + os.fsync(handle.fileno()) + os.replace(temporary, snapshot) + self._fsync_directory(path) + metadata["rootfs_snapshot"] = ROOTFS_SNAPSHOT + metadata["snapshot_at"] = self._now() + self._atomic_write_json(path / "metadata.json", metadata) + + def _stop_runtime(self, name: str, metadata: Mapping[str, Any]) -> None: + state, error = self._runtime_state(name, metadata) + if state is None and runtime_is_absent(error): + return + if state is not None and state.get("status") == "stopped": + return + self._run_quiet( + self._runsc_command(name, metadata, "kill", "--all", name, "TERM"), + timeout=3, + ) + state, error = self._wait_for_status( + name, metadata, {"stopped"}, self.config.stop_timeout + ) + if state is not None and state.get("status") == "stopped": + return + if state is None and runtime_is_absent(error): + return + self._run_quiet( + self._runsc_command(name, metadata, "kill", "--all", name, "KILL"), + timeout=3, + ) + state, error = self._wait_for_status( + name, metadata, {"stopped"}, self.config.stop_timeout + ) + if state is None and runtime_is_absent(error): + return + if state is not None and state.get("status") == "stopped": + return + # Some runsc versions keep reporting "running" after both kill calls + # while the init process is being reaped. Forced runtime deletion is + # the final bounded stop operation and is confirmed by missing state. + if self._force_runtime_delete(name, metadata): + return + raise SandboxError(f"could not confirm sandbox {name!r} stopped: {error}") + + def _force_runtime_delete(self, name: str, metadata: Mapping[str, Any]) -> bool: + path = self._instance_path(name) + try: + result = subprocess.run( + self._runsc_command(name, metadata, "delete", "--force", name), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + check=False, + shell=False, + timeout=self.config.delete_timeout, + ) + except (OSError, subprocess.TimeoutExpired) as exc: + self._append_log(path / "logs" / "launcher.log", f"runsc delete failed: {exc}") + return False + if result.stdout: + self._append_log(path / "logs" / "launcher.log", result.stdout) + state, error = self._runtime_state(name, metadata) + return state is None and (result.returncode == 0 or runtime_is_absent(error)) + + def _wait_for_status( + self, + name: str, + metadata: Mapping[str, Any], + wanted: set[str], + timeout: float, + *, + launcher: subprocess.Popen[bytes] | None = None, + ) -> tuple[dict[str, Any] | None, str | None]: + deadline = time.monotonic() + timeout + last_state: dict[str, Any] | None = None + last_error: str | None = None + while time.monotonic() < deadline: + last_state, last_error = self._runtime_state(name, metadata) + if last_state is not None and last_state.get("status") in wanted: + return last_state, None + if launcher is not None and launcher.poll() is not None: + return last_state, f"runsc launcher exited {launcher.returncode}" + time.sleep(0.1) + if last_state is not None: + return last_state, f"last status was {last_state.get('status')!r}" + return None, last_error or "runtime state did not appear" + + def _require_running(self, name: str, metadata: Mapping[str, Any]) -> None: + state, error = self._runtime_state(name, metadata) + if state is None or state.get("status") != "running": + detail = error or f"status is {state.get('status') if state else 'unknown'}" + raise SandboxError(f"sandbox {name!r} is not running: {detail}") + + def _run_captured( + self, + argv: Sequence[str], + *, + timeout: float, + operation: str, + ) -> tuple[int, str, str, bool]: + if timeout <= 0: + raise SandboxError("execution timeout must be positive") + try: + process = subprocess.Popen( + list(argv), + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=False, + ) + except OSError as exc: + raise SandboxError(f"could not {operation}: {exc}") from exc + buffers = [bytearray(), bytearray()] + truncated = [False, False] + + def drain(stream: Any, index: int) -> None: + while True: + chunk = stream.read(65536) + if not chunk: + return + remaining = self.config.max_output_bytes - len(buffers[index]) + if remaining > 0: + buffers[index].extend(chunk[:remaining]) + if len(chunk) > remaining: + truncated[index] = True + + threads = [ + threading.Thread(target=drain, args=(process.stdout, 0), daemon=True), + threading.Thread(target=drain, args=(process.stderr, 1), daemon=True), + ] + for thread in threads: + thread.start() + try: + exit_code = process.wait(timeout=timeout) + except subprocess.TimeoutExpired as exc: + process.kill() + with contextlib.suppress(subprocess.TimeoutExpired): + process.wait(timeout=2) + for thread in threads: + thread.join(timeout=1) + raise SandboxError(f"timed out after {timeout:g}s while trying to {operation}") from exc + for thread in threads: + thread.join(timeout=2) + stdout = bytes(buffers[0]).decode("utf-8", "replace") + stderr = bytes(buffers[1]).decode("utf-8", "replace") + if truncated[0]: + stdout += "\n[output truncated by sandbox policy]\n" + if truncated[1]: + stderr += "\n[output truncated by sandbox policy]\n" + return exit_code, stdout, stderr, any(truncated) + + @staticmethod + def _run_quiet(argv: Sequence[str], *, timeout: float) -> None: + with contextlib.suppress(OSError, subprocess.TimeoutExpired): + subprocess.run( + list(argv), + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + shell=False, + timeout=timeout, + ) + + def _valid_snapshot(self, name: str, metadata: Mapping[str, Any]) -> Path | None: + if metadata.get("rootfs_snapshot") != ROOTFS_SNAPSHOT: + return None + snapshot = self._instance_path(name) / ROOTFS_SNAPSHOT + if snapshot.is_symlink() or not snapshot.is_file(): + return None + if snapshot.parent.resolve() != self._instance_path(name).resolve(): + return None + return snapshot + + def _normalize_mounts( + self, mounts: Sequence[SandboxMount | Mapping[str, Any]] + ) -> tuple[SandboxMount, ...]: + if isinstance(mounts, (str, bytes)) or not isinstance(mounts, Sequence): + raise SandboxError("mounts must be a list") + normalized: list[SandboxMount] = [] + destinations: set[str] = set() + for raw in mounts: + if isinstance(raw, SandboxMount): + source = raw.source + destination = raw.destination + read_only = raw.read_only + elif isinstance(raw, Mapping): + source = Path(str(raw.get("source") or "")) + destination = str(raw.get("destination") or "") + read_only = self._as_bool(raw.get("read_only", True)) + else: + raise SandboxError("each mount must be a SandboxMount or object") + if not source.is_absolute(): + raise SandboxError(f"mount source must be absolute: {source}") + if source.is_symlink(): + raise SandboxError(f"mount source must not be a symlink: {source}") + source = source.resolve(strict=False) + if not source.is_dir(): + raise SandboxError(f"mount source must be an existing non-symlink directory: {source}") + destination = self._validate_guest_path(destination, label="mount destination") + if any( + destination == root or destination.startswith(root + "/") + for root in _PROTECTED_MOUNT_ROOTS + ): + raise SandboxError(f"mount destination is reserved: {destination}") + if destination in destinations: + raise SandboxError(f"duplicate mount destination: {destination}") + destinations.add(destination) + normalized.append(SandboxMount(source, destination, read_only)) + return tuple(normalized) + + @staticmethod + def _mount_json(mount: SandboxMount) -> dict[str, Any]: + return { + "source": str(mount.source), + "destination": mount.destination, + "read_only": mount.read_only, + } + + @staticmethod + def _normalize_ownership( + ownership: Mapping[str, str | None] | None, + ) -> dict[str, str | None]: + raw = ownership if isinstance(ownership, Mapping) else {} + result: dict[str, str | None] = {} + for key in _OWNERSHIP_KEYS: + value = raw.get(key) + result[key] = str(value).strip()[:256] if value is not None and str(value).strip() else None + return result + + @staticmethod + def _validate_network(value: Any) -> NetworkMode: + if value not in {"host", "none"}: + raise SandboxError(f"unsupported network mode {value!r}") + return value + + @staticmethod + def _validate_type(value: Any) -> SandboxType: + if value not in {"temporary", "permanent"}: + raise SandboxError(f"unsupported sandbox type {value!r}") + return value + + @staticmethod + def _validate_guest_path(value: str, *, label: str) -> str: + value = str(value or "") + if "\x00" in value: + raise SandboxError(f"{label} must not contain NUL bytes") + path = PurePosixPath(value) + normalized = str(path) + if ( + not value.startswith("/") + or value.startswith("//") + or ".." in path.parts + or value == "/" + or normalized != value + ): + raise SandboxError(f"{label} must be an absolute sandbox path below /: {value!r}") + return normalized + + @staticmethod + def _as_bool(value: Any) -> bool: + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return bool(value) + return str(value).strip().lower() in {"1", "true", "yes", "on"} + + def _require_runtime_artifacts(self) -> None: + if not self.config.runsc.is_file() or not os.access(self.config.runsc, os.X_OK): + raise SandboxError(f"runsc not found at {self.config.runsc}; run sandbox doctor") + + def _touch_locked(self, name: str, metadata: dict[str, Any]) -> None: + metadata["last_used_at"] = self._now() + self._atomic_write_json(self._instance_path(name) / "metadata.json", metadata) + try: + self.images.touch(str(metadata.get("image_digest") or "")) + except SandboxImageError as exc: + raise SandboxError(f"could not update base image usage: {exc}") from exc + + def _expiry(self, last_used_at: str) -> str | None: + try: + used = dt.datetime.fromisoformat(last_used_at) + except ValueError: + return None + return (used + dt.timedelta(days=self.config.temporary_lifetime_days)).isoformat() + + @staticmethod + def _parse_timestamp(value: Any, label: str) -> dt.datetime: + if not isinstance(value, str): + raise SandboxError(f"metadata {label} must be an ISO timestamp") + try: + parsed = dt.datetime.fromisoformat(value) + except ValueError as exc: + raise SandboxError(f"metadata {label} is invalid") from exc + if parsed.tzinfo is None: + raise SandboxError(f"metadata {label} must include a timezone") + return parsed + + @staticmethod + def _now() -> str: + return dt.datetime.now(dt.timezone.utc).isoformat() + + def _instance_path(self, name: str) -> Path: + validate_name(name) + path = self.config.instances_dir / name + if path.parent != self.config.instances_dir: + raise SandboxError("sandbox path escaped the instances directory") + return path + + def _ensure_layout(self) -> None: + for path in ( + self.config.instances_dir.parent, + self.config.instances_dir, + self.config.runsc_root, + ): + path.mkdir(mode=0o700, parents=True, exist_ok=True) + with contextlib.suppress(PermissionError): + path.chmod(0o700) + + def _ensure_shared_directory(self) -> None: + self.config.shared_dir.mkdir(mode=0o770, parents=True, exist_ok=True) + if self.config.shared_dir.is_symlink() or not self.config.shared_dir.is_dir(): + raise SandboxError(f"shared path is not a safe directory: {self.config.shared_dir}") + + @contextlib.contextmanager + def _name_thread_lock(self, name: str) -> Iterator[None]: + with self._locks_guard: + lock = self._locks.setdefault(name, threading.RLock()) + with lock: + yield + + @contextlib.contextmanager + def _operation_lock(self, name: str) -> Iterator[None]: + with self._name_thread_lock(name): + path = self._instance_path(name) + if path.is_symlink() or not path.is_dir(): + raise SandboxError(f"sandbox {name!r} does not exist") + with self._file_lock(path / ".lock"): + yield + + @contextlib.contextmanager + def _index_lock(self, *, exclusive: bool) -> Iterator[None]: + self._ensure_layout() + lock_path = self.config.instances_dir.parent / ".index.lock" + with lock_path.open("a+", encoding="utf-8") as handle: + with contextlib.suppress(PermissionError): + os.fchmod(handle.fileno(), 0o600) + fcntl.flock(handle.fileno(), fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) + try: + yield + finally: + fcntl.flock(handle.fileno(), fcntl.LOCK_UN) + + @staticmethod + @contextlib.contextmanager + def _file_lock(path: Path) -> Iterator[None]: + if path.is_symlink(): + raise SandboxError(f"refusing symlink lock file {path}") + with path.open("a+", encoding="utf-8") as handle: + with contextlib.suppress(PermissionError): + os.fchmod(handle.fileno(), 0o600) + fcntl.flock(handle.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(handle.fileno(), fcntl.LOCK_UN) + + @staticmethod + def _atomic_write_json(path: Path, value: Mapping[str, Any]) -> None: + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + temporary = Path(temporary_name) + try: + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as handle: + json.dump(value, handle, indent=2, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + SandboxManager._fsync_directory(path.parent) + except BaseException: + with contextlib.suppress(OSError): + os.close(fd) + temporary.unlink(missing_ok=True) + raise + + @staticmethod + def _atomic_write_text(path: Path, content: str, *, mode: int) -> None: + fd, temporary_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + temporary = Path(temporary_name) + try: + os.fchmod(fd, mode) + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(content) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + except BaseException: + with contextlib.suppress(OSError): + os.close(fd) + temporary.unlink(missing_ok=True) + raise + + @staticmethod + def _fsync_directory(path: Path) -> None: + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + @staticmethod + def _atomic_probe(path: Path) -> None: + fd, name = tempfile.mkstemp(prefix=".sandbox-doctor.", dir=path) + temporary = Path(name) + replacement = path / f"{temporary.name}.ok" + try: + os.write(fd, b"ok") + os.fsync(fd) + os.close(fd) + fd = -1 + os.replace(temporary, replacement) + SandboxManager._fsync_directory(path) + finally: + if fd >= 0: + os.close(fd) + temporary.unlink(missing_ok=True) + replacement.unlink(missing_ok=True) + + @staticmethod + def _append_log(path: Path, message: str) -> None: + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(message) + if not message.endswith("\n"): + handle.write("\n") + + @staticmethod + def _log_tail(path: Path) -> str: + try: + content = path.read_text(encoding="utf-8", errors="replace") + except OSError: + return "(no log)" + return "\n".join(content[-12000:].splitlines()[-40:]) + + @staticmethod + def _proc_status() -> dict[str, str]: + result: dict[str, str] = {} + with contextlib.suppress(OSError): + for line in Path("/proc/self/status").read_text(encoding="utf-8").splitlines(): + if ":" in line: + key, value = line.split(":", 1) + result[key] = value.strip() + return result + + +def sandbox_info_dict(info: SandboxInfo) -> dict[str, Any]: + """Serialize public sandbox information for tools and HTTP APIs.""" + result = dataclasses.asdict(info) + for mount in result.get("mounts", []): + mount["source"] = str(mount.get("source") or "") + return result diff --git a/plugins/_sandboxing/helpers/runtime.py b/plugins/_sandboxing/helpers/runtime.py new file mode 100644 index 000000000..fefb11827 --- /dev/null +++ b/plugins/_sandboxing/helpers/runtime.py @@ -0,0 +1,175 @@ +from __future__ import annotations + +import threading +from pathlib import Path +from typing import Any + +from helpers import files, plugins + +from plugins._sandboxing.helpers.images import ( + SandboxImageConfig, + SandboxImageError, + SandboxImageManager, +) +from plugins._sandboxing.helpers.manager import ( + SandboxConfig, + SandboxError, + SandboxManager, + validate_name, +) + + +PLUGIN_NAME = "_sandboxing" +_manager_lock = threading.RLock() +_manager: SandboxManager | None = None +_manager_config: tuple[SandboxConfig, SandboxImageConfig] | None = None + + +def normalize_config(value: dict[str, Any] | None) -> dict[str, Any]: + raw = value if isinstance(value, dict) else {} + default_type = str(raw.get("default_type", "temporary")).strip().lower() + default_network = str(raw.get("default_network", "host")).strip().lower() + default_sandbox = str(raw.get("default_sandbox") or "default").strip() + try: + validate_name(default_sandbox) + except SandboxError: + default_sandbox = "default" + return { + "runsc_path": str(raw.get("runsc_path") or "/usr/bin/runsc").strip(), + "skopeo_path": str(raw.get("skopeo_path") or "/usr/bin/skopeo").strip(), + "umoci_path": str(raw.get("umoci_path") or "/usr/bin/umoci").strip(), + "default_image": str( + raw.get("default_image") or "docker.io/library/python:3.13-slim-bookworm" + ).strip(), + "registry_auth_file": str(raw.get("registry_auth_file") or "").strip(), + "image_cache_dir": str( + raw.get("image_cache_dir") or "usr/plugins/_sandboxing/images" + ).strip(), + "state_dir": str( + raw.get("state_dir") or "usr/plugins/_sandboxing/runtime" + ).strip(), + "runsc_root": str( + raw.get("runsc_root") or "/dev/shm/agent-zero-runsc" + ).strip(), + "shared_dir": str(raw.get("shared_dir") or "usr/sandbox-shared").strip(), + "default_sandbox": default_sandbox, + "default_type": default_type + if default_type in {"temporary", "permanent"} + else "temporary", + "default_network": default_network + if default_network in {"host", "none"} + else "host", + "temporary_lifetime_days": _positive_float( + raw.get("temporary_lifetime_days"), 7.0 + ), + "image_lifetime_days": _positive_float(raw.get("image_lifetime_days"), 30.0), + "image_pull_timeout": _positive_float(raw.get("image_pull_timeout"), 900.0), + "image_unpack_timeout": _positive_float( + raw.get("image_unpack_timeout"), 900.0 + ), + "max_image_bytes": max( + 1_048_576, _integer(raw.get("max_image_bytes"), 17_179_869_184) + ), + "start_timeout": _positive_float(raw.get("start_timeout"), 8.0), + "stop_timeout": _positive_float(raw.get("stop_timeout"), 3.0), + "snapshot_timeout": _positive_float(raw.get("snapshot_timeout"), 300.0), + "exec_timeout": _positive_float(raw.get("exec_timeout"), 600.0), + "max_output_bytes": max(4096, _integer(raw.get("max_output_bytes"), 1_048_576)), + } + + +def manager_config( + *, agent: object | None = None +) -> tuple[SandboxConfig, SandboxImageConfig]: + raw = normalize_config(plugins.get_plugin_config(PLUGIN_NAME, agent=agent) or {}) + state_dir = _absolute_path(raw["state_dir"]) + sandbox = SandboxConfig( + runsc=_absolute_path(raw["runsc_path"]), + instances_dir=state_dir / "instances", + runsc_root=_absolute_path(raw["runsc_root"]), + shared_dir=_absolute_path(raw["shared_dir"]), + default_image=str(raw["default_image"]), + temporary_lifetime_days=float(raw["temporary_lifetime_days"]), + start_timeout=float(raw["start_timeout"]), + stop_timeout=float(raw["stop_timeout"]), + snapshot_timeout=float(raw["snapshot_timeout"]), + exec_timeout=float(raw["exec_timeout"]), + max_output_bytes=int(raw["max_output_bytes"]), + ) + auth_file = str(raw["registry_auth_file"] or "") + images = SandboxImageConfig( + skopeo=_absolute_path(raw["skopeo_path"]), + umoci=_absolute_path(raw["umoci_path"]), + cache_dir=_absolute_path(raw["image_cache_dir"]), + default_image=str(raw["default_image"]), + auth_file=_absolute_path(auth_file) if auth_file else None, + cleanup_days=float(raw["image_lifetime_days"]), + pull_timeout=float(raw["image_pull_timeout"]), + unpack_timeout=float(raw["image_unpack_timeout"]), + max_output_bytes=int(raw["max_output_bytes"]), + max_image_bytes=int(raw["max_image_bytes"]), + ) + return sandbox, images + + +def get_manager(*, agent: object | None = None) -> SandboxManager: + global _manager, _manager_config + sandbox_config, image_config = manager_config(agent=agent) + config = (sandbox_config, image_config) + with _manager_lock: + if _manager is None or _manager_config != config: + try: + images = SandboxImageManager(image_config) + except SandboxImageError as exc: + raise SandboxError(str(exc)) from exc + _manager = SandboxManager(sandbox_config, images) + _manager_config = config + return _manager + + +def reset_manager() -> None: + global _manager, _manager_config + with _manager_lock: + _manager = None + _manager_config = None + + +def defaults(*, agent: object | None = None) -> tuple[str, str, str]: + config = normalize_config(plugins.get_plugin_config(PLUGIN_NAME, agent=agent) or {}) + return ( + str(config["default_sandbox"]), + str(config["default_type"]), + str(config["default_network"]), + ) + + +def resolve_sandbox_name(destination: str, *, agent: object | None = None) -> str: + destination = str(destination or "default").strip() + default_name, _, _ = defaults(agent=agent) + if destination == "default": + return default_name + if destination.startswith("sandbox:"): + return destination.split(":", 1)[1] + return destination + + +def _absolute_path(value: str) -> Path: + path = Path(value).expanduser() + if not path.is_absolute(): + path = Path(files.get_abs_path(str(path))) + return path.resolve(strict=False) + + +def _positive_float(value: Any, default: float) -> float: + try: + parsed = float(value) + except (TypeError, ValueError): + return default + return parsed if parsed > 0 else default + + +def _integer(value: Any, default: int) -> int: + try: + return int(value) + except (TypeError, ValueError): + return default diff --git a/plugins/_sandboxing/helpers/shell.py b/plugins/_sandboxing/helpers/shell.py new file mode 100644 index 000000000..e09589c6a --- /dev/null +++ b/plugins/_sandboxing/helpers/shell.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +import asyncio +import contextlib +import errno +import os +import pty +import signal +import termios +from typing import Any + +from plugins._code_execution.helpers.shell_ssh import clean_string +from plugins._sandboxing.helpers.runtime import defaults, get_manager + + +class SandboxInteractiveSession: + """Persistent Bash session transported by a direct `runsc exec` PTY.""" + + def __init__(self, name: str, *, agent: object | None = None) -> None: + self.name = name + self.agent = agent + self.full_output = "" + self._proc: asyncio.subprocess.Process | None = None + self._queue: asyncio.Queue[str] | None = None + self._pump_task: asyncio.Task[None] | None = None + self._master_fd: int | None = None + + async def connect(self) -> None: + manager = get_manager(agent=self.agent) + _, sandbox_type, network = defaults(agent=self.agent) + await asyncio.to_thread( + manager.ensure_running, + self.name, + sandbox_type=sandbox_type, + network=network, + ) + argv = await asyncio.to_thread(manager.interactive_command, self.name) + master, slave = pty.openpty() + attrs = termios.tcgetattr(slave) + attrs[3] &= ~termios.ECHO + termios.tcsetattr(slave, termios.TCSANOW, attrs) + try: + self._proc = await asyncio.create_subprocess_exec( + *argv, + stdin=slave, + stdout=slave, + stderr=slave, + close_fds=True, + start_new_session=True, + ) + except BaseException: + os.close(master) + os.close(slave) + raise + os.close(slave) + self._master_fd = master + self._queue = asyncio.Queue() + self._pump_task = asyncio.create_task(self._pump()) + await self._read_until_idle(0.1, 1.0) + + async def close(self) -> None: + process = self._proc + self._proc = None + if process is not None and process.returncode is None: + try: + os.killpg(process.pid, signal.SIGTERM) + except (ProcessLookupError, PermissionError): + process.terminate() + try: + await asyncio.wait_for(process.wait(), timeout=2) + except asyncio.TimeoutError: + try: + os.killpg(process.pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + process.kill() + with contextlib.suppress(Exception): + await asyncio.wait_for(process.wait(), timeout=2) + if self._pump_task is not None: + self._pump_task.cancel() + with contextlib.suppress(asyncio.CancelledError, Exception): + await self._pump_task + self._pump_task = None + self._release_master() + + async def send_command(self, command: str) -> None: + if self.is_terminated() or self._master_fd is None: + raise RuntimeError("Sandbox shell is not connected") + await asyncio.to_thread(get_manager(agent=self.agent).touch, self.name) + self.full_output = "" + try: + os.write(self._master_fd, (command + "\n").encode("utf-8")) + except OSError as exc: + if exc.errno in {errno.EBADF, errno.EIO, errno.EINVAL}: + self._release_master() + raise RuntimeError("TTYSpawn PTY is closed") from exc + raise + + async def read_output( + self, timeout: float = 0, reset_full_output: bool = False + ) -> tuple[str, str | None]: + if self._queue is None: + raise RuntimeError("Sandbox shell is not connected") + if reset_full_output: + self.full_output = "" + partial = await self._read_until_idle(0.01, timeout) + self.full_output += partial + clean_partial = clean_string(partial) + clean_full = clean_string(self.full_output) + return clean_full, clean_partial or None + + def is_terminated(self) -> bool: + return self._proc is None or self._proc.returncode is not None + + def get_exit_code(self) -> int | None: + return None if self._proc is None else self._proc.returncode + + async def _pump(self) -> None: + assert self._queue is not None + while self._master_fd is not None: + try: + chunk = await asyncio.to_thread(os.read, self._master_fd, 65536) + except OSError as exc: + if exc.errno == errno.EIO: + break + raise + if not chunk: + break + self._queue.put_nowait(chunk.decode("utf-8", "replace")) + + async def _read_until_idle(self, idle_timeout: float, total_timeout: float) -> str: + if self._queue is None or total_timeout <= 0: + return "" + loop = asyncio.get_running_loop() + deadline = loop.time() + total_timeout + chunks: list[str] = [] + while loop.time() < deadline: + wait = min(idle_timeout, max(0.0, deadline - loop.time())) + try: + chunks.append(await asyncio.wait_for(self._queue.get(), timeout=wait)) + except asyncio.TimeoutError: + break + return "".join(chunks) + + def _release_master(self) -> None: + descriptor = self._master_fd + self._master_fd = None + if descriptor is not None: + with contextlib.suppress(OSError): + os.close(descriptor) diff --git a/plugins/_sandboxing/hooks.py b/plugins/_sandboxing/hooks.py new file mode 100644 index 000000000..4d83b17ad --- /dev/null +++ b/plugins/_sandboxing/hooks.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +from plugins._sandboxing.helpers.runtime import normalize_config, reset_manager + + +def get_plugin_config(default=None, **kwargs): + return normalize_config(default or {}) + + +def save_plugin_config(settings=None, default=None, **kwargs): + result = normalize_config(settings or default or {}) + reset_manager() + return result diff --git a/plugins/_sandboxing/plugin.yaml b/plugins/_sandboxing/plugin.yaml new file mode 100644 index 000000000..597a3e113 --- /dev/null +++ b/plugins/_sandboxing/plugin.yaml @@ -0,0 +1,9 @@ +name: _sandboxing +title: Sandboxing +description: Fast isolated gVisor sandboxes for agent code execution. +version: 0.2.0 +always_enabled: true +settings_sections: + - agent +per_project_config: false +per_agent_config: false diff --git a/plugins/_sandboxing/prompts/agent.extras.code_execution_destinations.md b/plugins/_sandboxing/prompts/agent.extras.code_execution_destinations.md new file mode 100644 index 000000000..37cbb51ce --- /dev/null +++ b/plugins/_sandboxing/prompts/agent.extras.code_execution_destinations.md @@ -0,0 +1,8 @@ +## Code execution destinations + +`code_execution_tool` uses `destination=default` when omitted. Keep the same destination for a session's command, input, output polling, and reset calls. + +Available destinations: +{{destinations}} + +Use `default` for ordinary commands so work stays isolated. Use `local` only when the task must inspect or modify Agent Zero itself or its core operating system. A stopped or missing sandbox is woken or created automatically. diff --git a/plugins/_sandboxing/prompts/agent.system.tool.sandbox.md b/plugins/_sandboxing/prompts/agent.system.tool.sandbox.md new file mode 100644 index 000000000..93c016f3d --- /dev/null +++ b/plugins/_sandboxing/prompts/agent.system.tool.sandbox.md @@ -0,0 +1,30 @@ +### sandbox +Manage direct gVisor sandboxes. + +Arguments: +- `action`: sandbox actions `list`, `inspect`, `doctor`, `create`, `start`, `stop`, `save`, `cleanup`, or `delete`; image actions `images`, `pull_image`, `inspect_image`, `cleanup_images`, or `delete_image` +- `name`: sandbox name for named actions +- `sandbox_type`: `temporary` (fast memory-backed overlay, expires) or `permanent` (disk-backed overlay, never expires) +- `network`: `host` or `none`, used at creation +- `image`: Docker/OCI image reference for `create`, `pull_image`, and image lookup actions; existing sandboxes remain pinned to the resolved digest +- `mounts`: optional list of `{source, destination, read_only}` folder binds; host sources and sandbox destinations must be absolute +- `confirm`: must be `true` for destructive sandbox or image deletion + +Use `code_execution_tool` with the destination shown in EXTRAS to run Bash, Python, or Node.js inside a sandbox. Missing or sleeping execution destinations are created or woken automatically. `/shared` is visible to every sandbox; optional mounts are explicit additional host exposure. + +Images must provide `/bin/sh` and `/bin/bash`. Pulling or creating from a new reference may take time. `delete_image` refuses images referenced by any sandbox, and `cleanup_images` only removes old unreferenced images. + +Example: +~~~json +{ + "thoughts": ["I need a durable isolated environment."], + "headline": "Creating a permanent sandbox", + "tool_name": "sandbox", + "tool_args": { + "action": "create", + "name": "research", + "sandbox_type": "permanent", + "network": "host" + } +} +~~~ diff --git a/plugins/_sandboxing/tools/__init__.py b/plugins/_sandboxing/tools/__init__.py new file mode 100644 index 000000000..e1d7ae578 --- /dev/null +++ b/plugins/_sandboxing/tools/__init__.py @@ -0,0 +1 @@ +"""Sandbox management tools.""" diff --git a/plugins/_sandboxing/tools/sandbox.py b/plugins/_sandboxing/tools/sandbox.py new file mode 100644 index 000000000..e9f818f53 --- /dev/null +++ b/plugins/_sandboxing/tools/sandbox.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +import asyncio +import json +from typing import Any + +from helpers import projects +from helpers.tool import Response, Tool +from plugins._sandboxing.helpers.images import image_info_dict +from plugins._sandboxing.helpers.manager import SandboxError, sandbox_info_dict +from plugins._sandboxing.helpers.runtime import defaults, get_manager + + +class Sandbox(Tool): + async def execute( + self, + action: str = "list", + name: str = "", + sandbox_type: str = "", + network: str = "", + image: str = "", + mounts: list[dict[str, Any]] | None = None, + confirm: bool = False, + **kwargs: Any, + ) -> Response: + action = str(action or self.args.get("action") or "list").strip().lower() + name = str(name or self.args.get("name") or "").strip() + image = str(image or self.args.get("image") or "").strip() + try: + manager = get_manager(agent=self.agent) + if action in {"list", "ls"}: + values = await asyncio.to_thread(manager.list) + payload = [sandbox_info_dict(value) for value in values] + return self._json({"sandboxes": payload}) + if action in {"images", "list_images"}: + values = await asyncio.to_thread(manager.list_images) + return self._json( + {"images": [image_info_dict(value) for value in values]} + ) + if action in {"inspect_image", "image_status"}: + value = await asyncio.to_thread( + manager.inspect_image, image or name + ) + return self._json(image_info_dict(value)) + if action in {"pull_image", "refresh_image"}: + value = await asyncio.to_thread(manager.pull_image, image or name) + return self._json(image_info_dict(value)) + if action in {"inspect", "status", "get"}: + return self._json( + sandbox_info_dict(await asyncio.to_thread(manager.inspect, name)) + ) + if action == "doctor": + diagnostics = await asyncio.to_thread(manager.doctor) + return self._json( + { + "ok": not any(line.startswith("ERROR:") for line in diagnostics), + "diagnostics": diagnostics, + } + ) + if action in {"create", "new"}: + configured_name, configured_type, configured_network = defaults( + agent=self.agent + ) + if not name: + name = configured_name + sandbox_type = str(sandbox_type or configured_type) + network = str(network or configured_network) + info = await asyncio.to_thread( + manager.create, + name, + network=network, + sandbox_type=sandbox_type, + image=image, + mounts=self._mounts(mounts), + ownership=self._ownership(), + ) + return self._json(sandbox_info_dict(info)) + if action in {"start", "wake"}: + return self._json( + sandbox_info_dict(await asyncio.to_thread(manager.start, name)) + ) + if action in {"stop", "sleep"}: + return self._json( + sandbox_info_dict(await asyncio.to_thread(manager.stop, name)) + ) + if action in {"save", "snapshot"}: + return self._json( + sandbox_info_dict(await asyncio.to_thread(manager.save, name)) + ) + if action == "cleanup": + deleted = await asyncio.to_thread(manager.cleanup_expired) + return self._json({"deleted": deleted}) + if action == "cleanup_images": + deleted = await asyncio.to_thread(manager.cleanup_images) + return self._json({"deleted_images": deleted}) + if action in {"delete_image", "remove_image"}: + if not confirm: + return Response( + message="Deleting a cached image is destructive. Repeat with confirm=true.", + break_loop=False, + ) + identifier = image or name + removed = await asyncio.to_thread(manager.delete_image, identifier) + return self._json({"image": identifier, "deleted": removed}) + if action in {"delete", "remove"}: + if not confirm: + return Response( + message="Deleting a sandbox is destructive. Repeat with confirm=true.", + break_loop=False, + ) + removed = await asyncio.to_thread(manager.delete, name) + return self._json({"name": name, "deleted": removed}) + except (SandboxError, ValueError) as exc: + return Response(message=f"Sandbox error: {exc}", break_loop=False) + return Response( + message=( + "Unknown action. Use list, inspect, doctor, create, start, stop, " + "save, cleanup, delete, images, pull_image, inspect_image, " + "cleanup_images, or delete_image." + ), + break_loop=False, + ) + + def _ownership(self) -> dict[str, str | None]: + context = getattr(self.agent, "context", None) + return { + "chat_id": str(getattr(context, "id", "") or "") or None, + "project_id": projects.get_context_project_name(context) if context else None, + "agent_id": str(getattr(self.agent, "agent_name", "") or "") or None, + } + + @staticmethod + def _mounts(raw: list[dict[str, Any]] | None) -> list[dict[str, Any]]: + return list(raw or []) + + @staticmethod + def _json(value: Any) -> Response: + return Response( + message=json.dumps(value, indent=2, ensure_ascii=False, default=str), + break_loop=False, + ) diff --git a/plugins/_sandboxing/webui/config.html b/plugins/_sandboxing/webui/config.html new file mode 100644 index 000000000..889947651 --- /dev/null +++ b/plugins/_sandboxing/webui/config.html @@ -0,0 +1,41 @@ + +Sandboxing + +
+ +
+ + diff --git a/plugins/_sandboxing/webui/main.html b/plugins/_sandboxing/webui/main.html new file mode 100644 index 000000000..14faaab2e --- /dev/null +++ b/plugins/_sandboxing/webui/main.html @@ -0,0 +1,246 @@ + + + + + + Sandboxes + + + +
+ +
+ + + + diff --git a/plugins/_sandboxing/webui/sandboxing-store.js b/plugins/_sandboxing/webui/sandboxing-store.js new file mode 100644 index 000000000..97357741b --- /dev/null +++ b/plugins/_sandboxing/webui/sandboxing-store.js @@ -0,0 +1,202 @@ +import { createStore } from "/js/AlpineStore.js"; +import { callJsonApi } from "/js/api.js"; +import { + toastFrontendError, + toastFrontendSuccess, +} from "/components/notifications/notification-store.js"; + +const API_PATH = "/plugins/_sandboxing/sandboxes"; + +const model = { + sandboxes: [], + images: [], + diagnostics: [], + sharedDir: "", + defaults: { name: "default", sandbox_type: "temporary", network: "host", image: "" }, + imageCleanupDays: 30, + loading: false, + busy: false, + busyNames: {}, + busyImages: {}, + pollTimer: null, + formInitialized: false, + form: { name: "", sandbox_type: "temporary", network: "host", image: "" }, + imageForm: { reference: "" }, + + async onOpen() { + await this.refresh(); + this.pollTimer = globalThis.setInterval(() => { + if (!this.busy) this.refresh(true); + }, 5000); + }, + + onClose() { + if (this.pollTimer) globalThis.clearInterval(this.pollTimer); + this.pollTimer = null; + }, + + async refresh(silent = false) { + if (!silent) this.loading = true; + try { + const response = await callJsonApi(API_PATH, { action: "list" }); + if (!response?.ok) throw new Error(response?.error || "Could not list sandboxes."); + this.sandboxes = Array.isArray(response.sandboxes) ? response.sandboxes : []; + this.images = Array.isArray(response.images) ? response.images : []; + this.sharedDir = response.shared_dir || ""; + this.defaults = response.defaults || this.defaults; + this.imageCleanupDays = Number(response.image_cleanup_days || 30); + if (!this.formInitialized) { + this.form.sandbox_type = this.defaults.sandbox_type || "temporary"; + this.form.network = this.defaults.network || "host"; + this.form.image = this.defaults.image || ""; + this.formInitialized = true; + } + if (!this.imageForm.reference) this.imageForm.reference = this.defaults.image || ""; + } catch (error) { + if (!silent) toastFrontendError(error?.message || "Could not list sandboxes."); + } finally { + if (!silent) this.loading = false; + } + }, + + async doctor() { + this.busy = true; + try { + const response = await callJsonApi(API_PATH, { action: "doctor" }); + this.diagnostics = Array.isArray(response?.diagnostics) ? response.diagnostics : []; + if (response?.ok) toastFrontendSuccess("Sandbox runtime checks passed."); + else toastFrontendError("Sandbox runtime needs attention. Review the diagnostics."); + } catch (error) { + toastFrontendError(error?.message || "Sandbox doctor failed."); + } finally { + this.busy = false; + } + }, + + async createSandbox() { + const name = this.form.name.trim(); + if (!name) return; + this.busy = true; + try { + const response = await callJsonApi(API_PATH, { + action: "create", + name, + sandbox_type: this.form.sandbox_type, + network: this.form.network, + image: this.form.image || this.defaults.image, + }); + if (!response?.ok) throw new Error(response?.error || "Could not create sandbox."); + this.form.name = ""; + toastFrontendSuccess(`Sandbox ${name} created.`); + await this.refresh(true); + } catch (error) { + toastFrontendError(error?.message || "Could not create sandbox."); + } finally { + this.busy = false; + } + }, + + async perform(action, sandbox) { + const name = sandbox?.name || ""; + if (!name || this.isBusy(name)) return; + this.busyNames[name] = true; + try { + const response = await callJsonApi(API_PATH, { + action, + name, + confirm: action === "delete", + }); + if (!response?.ok) throw new Error(response?.error || `Could not ${action} sandbox.`); + const completed = { start: "started", stop: "stopped", save: "saved", delete: "deleted" }[action] || action; + toastFrontendSuccess(`Sandbox ${name} ${completed}.`); + await this.refresh(true); + } catch (error) { + toastFrontendError(error?.message || `Could not ${action} sandbox.`); + } finally { + delete this.busyNames[name]; + } + }, + + async pullImage() { + const reference = this.imageForm.reference.trim(); + if (!reference || this.busy) return; + this.busy = true; + try { + const response = await callJsonApi(API_PATH, { + action: "pull_image", + image: reference, + }); + if (!response?.ok) throw new Error(response?.error || "Could not pull image."); + toastFrontendSuccess(`Image ${reference} is ready.`); + await this.refresh(true); + } catch (error) { + toastFrontendError(error?.message || "Could not pull image."); + } finally { + this.busy = false; + } + }, + + async deleteImage(image) { + const digest = image?.digest || ""; + if (!digest || this.busyImages[digest]) return; + this.busyImages[digest] = true; + try { + const response = await callJsonApi(API_PATH, { + action: "delete_image", + digest, + confirm: true, + }); + if (!response?.ok) throw new Error(response?.error || "Could not delete image."); + toastFrontendSuccess(`Image ${this.shortDigest(digest)} deleted.`); + await this.refresh(true); + } catch (error) { + toastFrontendError(error?.message || "Could not delete image."); + } finally { + delete this.busyImages[digest]; + } + }, + + async cleanupImages() { + if (this.busy) return; + this.busy = true; + try { + const response = await callJsonApi(API_PATH, { action: "cleanup_images" }); + if (!response?.ok) throw new Error(response?.error || "Image cleanup failed."); + const count = Array.isArray(response.deleted_images) ? response.deleted_images.length : 0; + toastFrontendSuccess(`Removed ${count} unused image${count === 1 ? "" : "s"}.`); + await this.refresh(true); + } catch (error) { + toastFrontendError(error?.message || "Image cleanup failed."); + } finally { + this.busy = false; + } + }, + + isBusy(name) { + return Boolean(this.busyNames[name]); + }, + + shortDigest(digest) { + const value = String(digest || ""); + return value.length > 22 ? `${value.slice(0, 19)}…` : value; + }, + + formatSize(bytes) { + let value = Number(bytes || 0); + const units = ["B", "KiB", "MiB", "GiB", "TiB"]; + let unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit += 1; + } + return unit === 0 ? `${Math.round(value)} B` : `${value.toFixed(1)} ${units[unit]}`; + }, + + formatDate(value) { + if (!value) return "Not yet"; + const date = new Date(value); + return Number.isNaN(date.getTime()) ? value : date.toLocaleString(); + }, +}; + +export const store = createStore("sandboxingStore", model); diff --git a/plugins/_search_engine/AGENTS.md b/plugins/_search_engine/AGENTS.md index 3ba0e4246..c913e940f 100644 --- a/plugins/_search_engine/AGENTS.md +++ b/plugins/_search_engine/AGENTS.md @@ -15,7 +15,7 @@ ## Local Contracts -- Search runs through `helpers.searxng.search`, which proxies to the SearXNG URL inside the development runtime via `runtime.call_development_function`. +- Search delegates to `plugins._searxng.helpers.searxng.search`, which returns the WIP not-implemented message without network activity. Preserve the upstream search presentation while sandboxed SearXNG is unfinished. - Result cap is `SEARCH_ENGINE_RESULTS = 10`; exceptions flow through `helpers.errors.handle_error` and return a failed-search message instead of raising. - The tool logs its message as type `search_engine` with an `icon://search Searching: ` headline. The WebUI message handler uses `drawMessageToolSimple` with code `SRC`, styled by the web access indigo styles shared with the browser badge that `extensions/webui/page-head/` loads; `extensions/webui/get_process_step_types/` registers the type. `get_tool_message_handler` reuses this renderer for saved `type="tool"` search logs. diff --git a/plugins/_search_engine/README.md b/plugins/_search_engine/README.md index f68a8dad3..ee3969d48 100644 --- a/plugins/_search_engine/README.md +++ b/plugins/_search_engine/README.md @@ -1,3 +1,3 @@ # Search Engine -Provides the `search_engine` tool, which queries the local SearXNG instance through the development runtime and returns the top titles, urls, and content snippets. +Preserves the search tool and WebUI presentation while the sandboxed SearXNG integration is unfinished. Calls return `the searxng plugin is not yet fully implemented` without network activity. See [SearXNG](../_searxng/README.md) for the preserved implementation notes. diff --git a/plugins/_search_engine/plugin.yaml b/plugins/_search_engine/plugin.yaml index f17ca7dae..da94ef51d 100644 --- a/plugins/_search_engine/plugin.yaml +++ b/plugins/_search_engine/plugin.yaml @@ -1,6 +1,6 @@ name: _search_engine title: Search Engine -description: Web search tool returning live titles, urls, and content snippets via the local SearXNG instance. +description: Search tool presentation backed by the unfinished sandboxed SearXNG placeholder. version: 1.0.0 settings_sections: [] per_project_config: false diff --git a/plugins/_search_engine/prompts/agent.system.tool.search_engine.md b/plugins/_search_engine/prompts/agent.system.tool.search_engine.md index f6953f971..e1e4b1793 100644 --- a/plugins/_search_engine/prompts/agent.system.tool.search_engine.md +++ b/plugins/_search_engine/prompts/agent.system.tool.search_engine.md @@ -1,24 +1,6 @@ ### search_engine -find live news, prices, and other real-time web data -arg: `query` (keyword-based text search query) -returns urls, titles, and descriptions +SearXNG web-search placeholder. -query rules: -- use keywords, names, exact phrases, model/version numbers, dates, and domains -- do not write a natural-language question or sentence -- omit filler words like "what", "who", "can you tell me", "find information about" -- use 3-10 high-signal terms; add alternatives only when they improve recall -- bad: "What is the latest LiteLLM release and what changed?" -- good: "LiteLLM latest release notes changelog" +The integration is currently unavailable. Every call returns `the searxng plugin is not yet fully implemented`. -example: -~~~json -{ - "thoughts": ["I need current information rather than relying on memory."], - "headline": "Searching the web", - "tool_name": "search_engine", - "tool_args": { - "query": "LiteLLM latest release notes changelog" - } -} -~~~ +arg: `query` (currently ignored) diff --git a/plugins/_search_engine/tools/search_engine.py b/plugins/_search_engine/tools/search_engine.py index d0046a48f..2ab292c1a 100644 --- a/plugins/_search_engine/tools/search_engine.py +++ b/plugins/_search_engine/tools/search_engine.py @@ -2,7 +2,7 @@ import uuid from helpers.tool import Tool, Response from helpers.errors import handle_error -from helpers.searxng import search as searxng +from plugins._searxng.helpers.searxng import search as searxng from helpers.strings import truncate_text SEARCH_ENGINE_RESULTS = 10 @@ -29,6 +29,8 @@ class SearchEngine(Tool): return self.format_result_searxng(results, "Search Engine") def format_result_searxng(self, result, source): + if isinstance(result, str): + return result if isinstance(result, Exception): handle_error(result) return f"{source} search failed: {str(result)}" diff --git a/plugins/_search_engine/tools/search_engine.py.dox.md b/plugins/_search_engine/tools/search_engine.py.dox.md index 5efc293df..28702666b 100644 --- a/plugins/_search_engine/tools/search_engine.py.dox.md +++ b/plugins/_search_engine/tools/search_engine.py.dox.md @@ -3,7 +3,7 @@ ## Purpose - Own the `search_engine.py` agent tool. -- This module runs web search through the configured search helper. +- This module delegates to the SearXNG placeholder and preserves search-log presentation; it does not contact a live search service. String placeholder results pass through unchanged. - Keep this file-level DOX profile synchronized with `search_engine.py` because this directory is intentionally flat. ## Ownership @@ -25,7 +25,7 @@ - Update this file whenever tool arguments, output shape, `break_loop` behavior, intervention handling, prompt instructions, or side effects change. - `SearchEngine` is a `Tool`. - `SearchEngine` defines `execute(...)`. -- Imported dependency areas include: `helpers.errors`, `helpers.searxng`, `helpers.strings`, `helpers.tool`, `uuid`. +- Imported dependency areas include: `helpers.errors`, `plugins._searxng.helpers.searxng`, `helpers.strings`, `helpers.tool`, `uuid`. ## Key Concepts diff --git a/plugins/_searxng/AGENTS.md b/plugins/_searxng/AGENTS.md new file mode 100644 index 000000000..30104a8f0 --- /dev/null +++ b/plugins/_searxng/AGENTS.md @@ -0,0 +1,34 @@ +# SearXNG Plugin DOX + +## Purpose + +- Own the unavailable SearXNG search placeholder and the migration record needed for a future sandboxed implementation. + +## Ownership + +- `tools/search_engine.py` owns the agent-facing placeholder tool. +- `helpers/searxng.py` owns the shared not-implemented response used by the placeholder. +- `prompts/agent.system.tool.search_engine.md` owns the agent-facing tool contract. +- `README.md` owns the historical installation, runtime, dependency, and configuration record. +- `plugin.yaml` owns bundled-plugin metadata and activation. + +## Local Contracts + +- Every tool call returns exactly `the searxng plugin is not yet fully implemented` with `break_loop=False`. +- The plugin must not make network requests, install packages, start processes, create a virtualenv, or write SearXNG configuration. +- SearXNG must not be installed or launched in the outer Agent Zero image. +- Any future implementation must isolate SearXNG through the sandboxing plugin and update this contract and the README. + +## Work Guidance + +- Treat the README commands and configuration as a historical reconstruction record, not an instruction to restore host-level installation. +- Keep the public tool name `search_engine` stable while the placeholder remains bundled. + +## Verification + +- Run `pytest tests/test_searxng_plugin.py`. +- Confirm Docker contexts contain no SearXNG installer, launcher, supervisor entry, configuration, virtualenv path, service user, or dependency-only install step. + +## Child DOX Index + +No child DOX files. diff --git a/plugins/_searxng/README.md b/plugins/_searxng/README.md new file mode 100644 index 000000000..cd8412d79 --- /dev/null +++ b/plugins/_searxng/README.md @@ -0,0 +1,137 @@ +# SearXNG plugin + +This bundled plugin is a non-working placeholder for Agent Zero's former built-in SearXNG search service. The `search_engine` tool always returns: + +```text +the searxng plugin is not yet fully implemented +``` + +It performs no network request, package installation, service startup, virtualenv creation, or configuration write. A future implementation should recreate SearXNG inside an Agent Zero sandbox rather than adding it back to the base or runtime image. + +## Historical installation record + +The former base image copied `docker/base/fs/` to `/`, installed Python 3.13, and then ran `/ins/install_searxng.sh`. That first stage: + +1. Installed `git`, `build-essential`, `libxslt-dev`, `zlib1g-dev`, `libffi-dev`, and `libssl-dev` with apt. +2. Created a system user named `searxng` with `/bin/bash`, home `/usr/local/searxng`, and comment `Privacy-respecting metasearch engine`. +3. Added that user to the `sudo` group. +4. Created `/usr/local/searxng`, assigned it to `searxng:searxng`, and ran `/ins/install_searxng2.sh` through `su - searxng`. + +The second stage ran as `searxng` and used this effective sequence: + +```bash +git clone https://github.com/searxng/searxng /usr/local/searxng/searxng-src +python3.13 -m venv /usr/local/searxng/searx-pyenv +echo '. /usr/local/searxng/searx-pyenv/bin/activate' >> /usr/local/searxng/.profile +source /usr/local/searxng/searx-pyenv/bin/activate +pip install --no-cache-dir -U pip setuptools wheel pyyaml lxml msgspec typing_extensions +cd /usr/local/searxng/searxng-src +pip install --no-cache-dir --use-pep517 --no-build-isolation . +pip cache purge +``` + +The repository clone and Python packages were unpinned, so the old build was not fully reproducible. The SearXNG virtualenv lived entirely at `/usr/local/searxng/searx-pyenv`; deleting the installer from the image build removes that virtualenv and its pip-only dependencies from newly built images. The apt packages in the first-stage list were installed by that same deleted installer; some may still be present if another image component independently requires them. + +## Historical runtime wiring + +The runnable image overlaid its own `/etc/searxng/settings.yml` and `/etc/searxng/limiter.toml` on the base copy. Supervisor then started the service as the `searxng` user with: + +```ini +[program:run_searxng] +command=/exe/run_searxng.sh +environment=SEARXNG_SETTINGS_PATH=/etc/searxng/settings.yml +user=searxng +directory=/usr/local/searxng/searxng-src +stopwaitsecs=1 +autorestart=true +startretries=3 +stopasgroup=true +killasgroup=true +``` + +`/exe/run_searxng.sh` changed to `/usr/local/searxng/searxng-src`, exported `SEARXNG_SETTINGS_PATH=/etc/searxng/settings.yml`, activated `/usr/local/searxng/searx-pyenv`, and executed `python /usr/local/searxng/searxng-src/searx/webapp.py`. The former Agent Zero helper sent an HTTP `POST` to `http://localhost:55510/search` with form fields `q=` and `format=json`. + +Port `55510` was internal and was not listed in the runnable Dockerfile's `EXPOSE` instruction. The launcher, supervisor program, service user, install scripts, config files, virtualenv, source clone, and Dockerfile references have all been removed from the outer image design. + +## Historical effective settings + +The runnable image's overlay was the effective configuration. Preserve these values when designing the sandboxed replacement: + +```yaml +use_default_settings: + engines: + remove: + - radio browser + - wikidata + +general: + debug: false + instance_name: "SearXNG" + +search: + safe_search: 0 + formats: + - json + +server: + secret_key: "dummy" # overridable by SEARXNG_SECRET + port: 55510 + limiter: false + image_proxy: false + # base_url was unset and could be overridden by SEARXNG_URL. + +# Redis was disabled. The documented optional value, overridable by +# SEARXNG_REDIS_URL, was: +# redis: +# url: unix:///usr/local/searxng-redis/run/redis.sock?db=0 + +ui: + static_use_hash: true + +enabled_plugins: + - "Hash plugin" + - "Self Informations" + - "Tracker URL remover" + +engines: + - name: radio browser + engine: radio_browser + disabled: true + inactive: true + - name: ahmia + disabled: true + inactive: true + - name: torch + disabled: true + inactive: true +``` + +`radio browser` was disabled because it crashed on x86 in `gethostbyaddr`; `wikidata` was disabled because variant payloads broke the SearXNG 2026.04 bootstrap initialization path. The older base-layer copy only removed `wikidata` and omitted the explicit `radio browser` engine block, but the runtime overlay above replaced it. + +The copied limiter configuration was identical in both image contexts: + +```toml +[botdetection] +trusted_proxies = ["127.0.0.1"] +ipv4_prefix = 32 +ipv6_prefix = 48 + +[botdetection.ip_limit] +filter_link_local = false +link_token = false + +[botdetection.ip_lists] +block_ip = [] +pass_ip = [] +pass_searxng_org = true +``` + +Although the limiter file existed, `server.limiter` was `false`. Future work should reevaluate the dummy secret, trusted proxy assumptions, disabled limiter, unpinned source, and `sudo` membership instead of copying them blindly into a sandbox. + +## Future sandboxing checklist + +- Pin a reviewed SearXNG revision and dependency set. +- Provision the source, virtualenv, settings, and writable state inside a sandbox-owned filesystem. +- Bind only the minimum loopback or mediated endpoint needed by the tool; do not expose the service publicly by default. +- Generate a real secret where required and avoid persisting it in source or image layers. +- Add sandbox lifecycle, health, timeout, cleanup, and request/response tests before replacing the placeholder. diff --git a/plugins/_searxng/helpers/__init__.py b/plugins/_searxng/helpers/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/plugins/_searxng/helpers/searxng.py b/plugins/_searxng/helpers/searxng.py new file mode 100644 index 000000000..54c4e32f3 --- /dev/null +++ b/plugins/_searxng/helpers/searxng.py @@ -0,0 +1,7 @@ +NOT_IMPLEMENTED_MESSAGE = "the searxng plugin is not yet fully implemented" + + +async def search(query: str) -> str: + """Return the placeholder result without contacting a search service.""" + del query + return NOT_IMPLEMENTED_MESSAGE diff --git a/plugins/_searxng/plugin.yaml b/plugins/_searxng/plugin.yaml new file mode 100644 index 000000000..ad7828f8c --- /dev/null +++ b/plugins/_searxng/plugin.yaml @@ -0,0 +1,8 @@ +name: _searxng +title: SearXNG +description: Placeholder for a future sandboxed SearXNG search integration. +version: 0.1.0 +settings_sections: [] +per_project_config: false +per_agent_config: false +always_enabled: true diff --git a/plugins/_searxng/prompts/agent.system.tool.search_engine.md b/plugins/_searxng/prompts/agent.system.tool.search_engine.md new file mode 100644 index 000000000..e1e4b1793 --- /dev/null +++ b/plugins/_searxng/prompts/agent.system.tool.search_engine.md @@ -0,0 +1,6 @@ +### search_engine +SearXNG web-search placeholder. + +The integration is currently unavailable. Every call returns `the searxng plugin is not yet fully implemented`. + +arg: `query` (currently ignored) diff --git a/plugins/_searxng/tools/search_engine.py b/plugins/_searxng/tools/search_engine.py new file mode 100644 index 000000000..29c138aaf --- /dev/null +++ b/plugins/_searxng/tools/search_engine.py @@ -0,0 +1,8 @@ +from helpers.tool import Response, Tool +from plugins._searxng.helpers.searxng import search as searxng + + +class SearchEngine(Tool): + async def execute(self, query: str = "", **kwargs) -> Response: + del kwargs + return Response(message=await searxng(query), break_loop=False) diff --git a/plugins/_whisper_stt/AGENTS.md b/plugins/_whisper_stt/AGENTS.md index 56b6244b0..dadaf37ed 100644 --- a/plugins/_whisper_stt/AGENTS.md +++ b/plugins/_whisper_stt/AGENTS.md @@ -19,6 +19,12 @@ - Keep all `data-whisper-microphone` controls synchronized with the same microphone status. - Optional final-transcript handlers must receive the configured draft/send mode without changing the main chat microphone's delivery behavior. - Do not expose raw audio or transcriptions beyond intended UI/API paths. +- Microphone uploads use the bounded PCM v1 contract documented in `README.md`: + 16 kHz mono normalized little-endian float32, at most 120 seconds. Validate + metadata and bytes before model loading, and pass an ndarray to Whisper so no + filename decoder, temporary audio file, FFmpeg process, or raw-audio log is used. +- Browser capture uses `AudioWorklet`; report unsupported browsers explicitly and + keep microphone streams, worklet nodes, timers, and audio contexts disposable. ## Work Guidance @@ -26,7 +32,9 @@ ## Verification -- Smoke-test status, transcription, model/language settings, send/draft modes, and silence handling after changes. +- Smoke-test status, PCM validation/transcription, model/language settings, + send/draft modes, device selection, repeated recording, teardown, permission + failures, unsupported browsers, and silence handling after changes. ## Child DOX Index diff --git a/plugins/_whisper_stt/README.md b/plugins/_whisper_stt/README.md index 410c11950..e8e288151 100644 --- a/plugins/_whisper_stt/README.md +++ b/plugins/_whisper_stt/README.md @@ -7,6 +7,8 @@ Built-in speech-to-text plugin backed by Whisper. - Registers Whisper as the active STT provider when the plugin is enabled. - Owns the microphone runtime, device selector UI, message delivery mode, and plugin APIs. - Keeps dependency installation and model bootstrap on the Docker/bootstrap path. +- Captures mono PCM with `AudioWorklet`, resamples it in the browser, and passes a + validated float32 array directly to Whisper without a media decoder or temporary file. ## Config @@ -21,3 +23,16 @@ Built-in speech-to-text plugin backed by Whisper. - `POST /api/plugins/_whisper_stt/transcribe` - `POST /api/plugins/_whisper_stt/status` + +The transcribe request contains `audio` using PCM wire contract v1: + +- `version`: integer `1` +- `sample_rate`: integer `16000` +- `channels`: integer `1` +- `sample_format`: `f32le` (normalized IEEE-754 float32, little-endian) +- `frame_count`: positive integer, at most 1,920,000 frames (120 seconds) +- `data`: base64 containing exactly `frame_count * 4` bytes + +The backend rejects unsupported metadata, malformed/truncated data, non-finite or +out-of-range samples, and duration/byte-limit violations before loading a model. +Raw PCM is neither written to disk nor logged. diff --git a/plugins/_whisper_stt/api/transcribe.py b/plugins/_whisper_stt/api/transcribe.py index 5c0b4f30e..45c74fe8d 100644 --- a/plugins/_whisper_stt/api/transcribe.py +++ b/plugins/_whisper_stt/api/transcribe.py @@ -7,8 +7,8 @@ class Transcribe(ApiHandler): if not runtime.is_globally_enabled(): return Response(status=409, response="Whisper STT plugin is disabled") - audio = str(input.get("audio") or "").strip() - if not audio: + audio = input.get("audio") + if audio is None: return Response(status=400, response="Missing audio") ctxid = str(input.get("ctxid") or "").strip() @@ -22,5 +22,7 @@ class Transcribe(ApiHandler): "text": str(result.get("text") or "").strip(), "language": str(result.get("language") or "").strip(), } + except runtime.AudioPayloadError as e: + return Response(status=400, response=str(e)) except Exception as e: return {"success": False, "error": str(e), "text": ""} diff --git a/plugins/_whisper_stt/helpers/runtime.py b/plugins/_whisper_stt/helpers/runtime.py index 7ae867424..e29a08262 100644 --- a/plugins/_whisper_stt/helpers/runtime.py +++ b/plugins/_whisper_stt/helpers/runtime.py @@ -2,11 +2,10 @@ from __future__ import annotations import asyncio import base64 -import os -import tempfile import warnings from typing import Any +import numpy as np import whisper from helpers import files, plugins @@ -18,7 +17,6 @@ from helpers.notification import ( from helpers.print_style import PrintStyle from plugins._whisper_stt.helpers import migration - warnings.filterwarnings("ignore", category=FutureWarning) @@ -34,6 +32,16 @@ DEFAULT_CONFIG = { VALID_MODEL_SIZES = {"tiny", "base", "small", "medium", "large", "turbo"} VALID_MESSAGE_MODES = {"send", "draft"} +AUDIO_WIRE_VERSION = 1 +AUDIO_SAMPLE_RATE = 16_000 +AUDIO_CHANNELS = 1 +AUDIO_SAMPLE_FORMAT = "f32le" +AUDIO_MAX_DURATION_SECONDS = 120 +AUDIO_MAX_FRAMES = AUDIO_SAMPLE_RATE * AUDIO_MAX_DURATION_SECONDS +AUDIO_BYTES_PER_SAMPLE = 4 +AUDIO_MAX_BYTES = AUDIO_MAX_FRAMES * AUDIO_BYTES_PER_SAMPLE +AUDIO_MAX_BASE64_CHARS = ((AUDIO_MAX_BYTES + 2) // 3) * 4 + _model = None _model_name = "" is_updating_model = False @@ -78,7 +86,9 @@ def normalize_config(config: dict[str, Any] | None) -> dict[str, Any]: pass try: - waiting_timeout = int(config.get("waiting_timeout", normalized["waiting_timeout"])) + waiting_timeout = int( + config.get("waiting_timeout", normalized["waiting_timeout"]) + ) if waiting_timeout > 0: normalized["waiting_timeout"] = waiting_timeout except (TypeError, ValueError): @@ -151,39 +161,82 @@ async def is_downloaded() -> bool: async def transcribe( - audio_bytes_b64: str, config: dict[str, Any] | None = None + audio_payload: dict[str, Any], config: dict[str, Any] | None = None ) -> dict[str, Any]: cfg = normalize_config(config or get_config()) + audio_samples = decode_audio_payload(audio_payload) return await _transcribe( str(cfg["model_size"]), - audio_bytes_b64, + audio_samples, language=_resolve_language(str(cfg["language"])), ) async def _transcribe( - model_name: str, audio_bytes_b64: str, *, language: str | None = None + model_name: str, audio_samples: np.ndarray, *, language: str | None = None ) -> dict[str, Any]: await _preload(model_name) - audio_bytes = base64.b64decode(audio_bytes_b64) + kwargs: dict[str, Any] = {"fp16": False} + if language: + kwargs["language"] = language - with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as audio_file: - audio_file.write(audio_bytes) - temp_path = audio_file.name + result = _model.transcribe(audio_samples, **kwargs) # type: ignore[union-attr] + return result if isinstance(result, dict) else {} + + +class AudioPayloadError(ValueError): + """Raised when the bounded PCM wire contract is invalid.""" + + +def decode_audio_payload(payload: dict[str, Any]) -> np.ndarray: + """Validate PCM v1 and return Whisper-ready mono float32 samples.""" + + if not isinstance(payload, dict): + raise AudioPayloadError("Audio payload must be an object") + if payload.get("version") != AUDIO_WIRE_VERSION: + raise AudioPayloadError("Unsupported audio payload version") + if payload.get("sample_rate") != AUDIO_SAMPLE_RATE: + raise AudioPayloadError("Unsupported audio sample rate") + if payload.get("channels") != AUDIO_CHANNELS: + raise AudioPayloadError("Unsupported audio channel count") + if payload.get("sample_format") != AUDIO_SAMPLE_FORMAT: + raise AudioPayloadError("Unsupported audio sample format") + + frame_count = payload.get("frame_count") + if isinstance(frame_count, bool) or not isinstance(frame_count, int): + raise AudioPayloadError("Audio frame count must be an integer") + if frame_count <= 0: + raise AudioPayloadError("Audio payload is empty") + if frame_count > AUDIO_MAX_FRAMES: + raise AudioPayloadError("Audio duration exceeds 120 seconds") + + encoded = payload.get("data") + if not isinstance(encoded, str) or not encoded: + raise AudioPayloadError("Audio data must be base64 text") + if len(encoded) > AUDIO_MAX_BASE64_CHARS: + raise AudioPayloadError("Audio payload exceeds the byte limit") try: - kwargs: dict[str, Any] = {"fp16": False} - if language: - kwargs["language"] = language + raw = base64.b64decode(encoded, validate=True) + except (ValueError, base64.binascii.Error) as exc: + raise AudioPayloadError("Audio data is not valid base64") from exc - result = _model.transcribe(temp_path, **kwargs) # type: ignore[union-attr] - return result if isinstance(result, dict) else {} - finally: - try: - os.remove(temp_path) - except Exception: - pass + expected_bytes = frame_count * AUDIO_BYTES_PER_SAMPLE + if len(raw) != expected_bytes: + raise AudioPayloadError("Audio data length does not match frame count") + if len(raw) > AUDIO_MAX_BYTES: + raise AudioPayloadError("Audio payload exceeds the byte limit") + + samples = np.frombuffer(raw, dtype=" 1.0): + raise AudioPayloadError("Audio samples must be normalized") + + # Whisper accepts a 16 kHz mono float32 ndarray and therefore skips load_audio, + # the only path in openai-whisper that launches ffmpeg. + return np.array(samples, dtype=np.float32, copy=True, order="C") def _resolve_language(language: str) -> str | None: diff --git a/plugins/_whisper_stt/webui/audio-pcm.js b/plugins/_whisper_stt/webui/audio-pcm.js new file mode 100644 index 000000000..a0f7c9e61 --- /dev/null +++ b/plugins/_whisper_stt/webui/audio-pcm.js @@ -0,0 +1,98 @@ +export const PCM_WIRE_VERSION = 1; +export const PCM_SAMPLE_RATE = 16000; +export const PCM_CHANNELS = 1; +export const PCM_SAMPLE_FORMAT = "f32le"; +export const PCM_MAX_DURATION_SECONDS = 120; + +export function mixAudioChannels(channels) { + if (!channels?.length) return new Float32Array(); + + const frameCount = Math.min(...channels.map((channel) => channel.length)); + const mono = new Float32Array(frameCount); + for (let frame = 0; frame < frameCount; frame += 1) { + let sum = 0; + for (const channel of channels) sum += channel[frame]; + mono[frame] = sum / channels.length; + } + return mono; +} + +export function resampleMonoPcm(samples, sourceRate, targetRate = PCM_SAMPLE_RATE) { + if (!(samples instanceof Float32Array) || samples.length === 0) { + return new Float32Array(); + } + if (!Number.isFinite(sourceRate) || sourceRate <= 0) { + throw new Error("Invalid source sample rate"); + } + if (sourceRate === targetRate) return samples.slice(); + + const outputLength = Math.max(1, Math.round(samples.length * targetRate / sourceRate)); + const output = new Float32Array(outputLength); + const ratio = sourceRate / targetRate; + + if (ratio > 1) { + for (let outputIndex = 0; outputIndex < outputLength; outputIndex += 1) { + const start = outputIndex * ratio; + const end = Math.min((outputIndex + 1) * ratio, samples.length); + const first = Math.floor(start); + const last = Math.ceil(end); + let weightedSum = 0; + let weight = 0; + for (let inputIndex = first; inputIndex < last; inputIndex += 1) { + const overlap = Math.max(0, Math.min(end, inputIndex + 1) - Math.max(start, inputIndex)); + weightedSum += samples[inputIndex] * overlap; + weight += overlap; + } + output[outputIndex] = weight ? weightedSum / weight : 0; + } + return output; + } + + for (let outputIndex = 0; outputIndex < outputLength; outputIndex += 1) { + const position = outputIndex * ratio; + const left = Math.floor(position); + const right = Math.min(left + 1, samples.length - 1); + const fraction = position - left; + output[outputIndex] = samples[left] * (1 - fraction) + samples[right] * fraction; + } + return output; +} + +export function concatenatePcmChunks(chunks, frameCount) { + const samples = new Float32Array(frameCount); + let offset = 0; + for (const chunk of chunks) { + const remaining = samples.length - offset; + if (remaining <= 0) break; + const view = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk; + samples.set(view, offset); + offset += view.length; + } + return samples; +} + +export function encodePcmPayload(samples) { + const bytes = new Uint8Array(samples.length * 4); + const view = new DataView(bytes.buffer); + for (let index = 0; index < samples.length; index += 1) { + const sample = Number.isFinite(samples[index]) + ? Math.max(-1, Math.min(1, samples[index])) + : 0; + view.setFloat32(index * 4, sample, true); + } + + let binary = ""; + const chunkSize = 0x8000; + for (let offset = 0; offset < bytes.length; offset += chunkSize) { + binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize)); + } + + return { + version: PCM_WIRE_VERSION, + sample_rate: PCM_SAMPLE_RATE, + channels: PCM_CHANNELS, + sample_format: PCM_SAMPLE_FORMAT, + frame_count: samples.length, + data: btoa(binary), + }; +} diff --git a/plugins/_whisper_stt/webui/pcm-capture-processor.js b/plugins/_whisper_stt/webui/pcm-capture-processor.js new file mode 100644 index 000000000..bfa41102a --- /dev/null +++ b/plugins/_whisper_stt/webui/pcm-capture-processor.js @@ -0,0 +1,45 @@ +import { mixAudioChannels } from "./audio-pcm.js"; + +class PcmCaptureProcessor extends AudioWorkletProcessor { + constructor(options) { + super(); + this.capturing = false; + this.recordingId = 0; + this.frameCount = 0; + this.maxFrames = Math.max(1, Number(options.processorOptions?.maxFrames || sampleRate * 120)); + this.port.onmessage = (event) => { + if (event.data?.type === "start") { + this.recordingId = event.data.recordingId; + this.frameCount = 0; + this.capturing = true; + } else if (event.data?.type === "stop") { + this.capturing = false; + this.port.postMessage({ type: "stopped", recordingId: event.data.recordingId }); + } + }; + } + + process(inputs) { + if (!this.capturing) return true; + const channels = inputs[0]; + if (!channels?.length) return true; + + const mono = mixAudioChannels(channels); + const remaining = this.maxFrames - this.frameCount; + const captured = mono.length > remaining ? mono.slice(0, remaining) : mono; + if (captured.length) { + this.frameCount += captured.length; + this.port.postMessage( + { type: "chunk", recordingId: this.recordingId, samples: captured.buffer }, + [captured.buffer], + ); + } + if (this.frameCount >= this.maxFrames) { + this.capturing = false; + this.port.postMessage({ type: "overflow", recordingId: this.recordingId }); + } + return true; + } +} + +registerProcessor("whisper-pcm-capture", PcmCaptureProcessor); diff --git a/plugins/_whisper_stt/webui/whisper-stt-store.js b/plugins/_whisper_stt/webui/whisper-stt-store.js index 72897b624..19f7b848f 100644 --- a/plugins/_whisper_stt/webui/whisper-stt-store.js +++ b/plugins/_whisper_stt/webui/whisper-stt-store.js @@ -4,10 +4,16 @@ import { callJsonApi } from "/js/api.js"; import { sttService } from "/js/stt-service.js"; import { ttsService } from "/js/tts-service.js"; import { sendMessage, updateChatInput } from "/index.js"; +import { + PCM_MAX_DURATION_SECONDS, + concatenatePcmChunks, + encodePcmPayload, + resampleMonoPcm, +} from "./audio-pcm.js"; const PLUGIN_NAME = "_whisper_stt"; -const Status = { +export const Status = { INACTIVE: "inactive", ACTIVATING: "activating", LISTENING: "listening", @@ -46,7 +52,7 @@ function clearMicrophoneTooltip(element) { element.removeAttribute("data-bs-tooltip-initialized"); } -const model = { +export const model = { runtimeInitialized: false, statusLoaded: false, loading: false, @@ -402,17 +408,22 @@ const model = { }, }; -class MicrophoneInput { +export class MicrophoneInput { constructor(owner, updateCallback) { this.owner = owner; this.updateCallback = updateCallback; this.mediaStream = null; - this.mediaRecorder = null; this.audioContext = null; this.mediaStreamSource = null; this.analyserNode = null; - this.audioChunks = []; - this.lastChunk = null; + this.captureNode = null; + this.silentGain = null; + this.pcmChunks = []; + this.pcmFrameCount = 0; + this.recordingId = 0; + this.captureStopResolver = null; + this.captureOverflow = false; + this.disposed = false; this.messageSent = false; this.lastAudioTime = null; this.waitingTimer = null; @@ -437,6 +448,7 @@ class MicrophoneInput { } async initialize() { + this.disposed = false; this.status = Status.ACTIVATING; try { @@ -455,28 +467,14 @@ class MicrophoneInput { this.selectedDeviceId = selectedDevice?.deviceId || ""; this.mediaStream = stream; - this.mediaRecorder = new MediaRecorder(stream); - this.mediaRecorder.ondataavailable = (event) => { - if ( - event.data.size > 0 && - (this.status === Status.RECORDING || this.status === Status.WAITING) - ) { - if (this.lastChunk) { - this.audioChunks.push(this.lastChunk); - this.lastChunk = null; - } - this.audioChunks.push(event.data); - } else if (this.status === Status.LISTENING) { - this.lastChunk = event.data; - } - }; - - this.setupAudioAnalysis(stream); + await this.setupAudioPipeline(stream); return true; } catch (error) { console.error("[Whisper STT] Microphone initialization failed", error); globalThis.toast?.( - "Failed to access the microphone. Please check browser permissions.", + error?.name === "NotSupportedError" + ? "This browser does not support the AudioWorklet microphone pipeline required for local transcription." + : "Failed to access the microphone. Please check browser permissions.", "error", ); this.status = Status.INACTIVE; @@ -486,10 +484,6 @@ class MicrophoneInput { } handleStatusChange(previousStatus, nextStatus) { - if (nextStatus !== Status.RECORDING) { - this.lastChunk = null; - } - switch (nextStatus) { case Status.INACTIVE: this.handleInactiveState(); @@ -517,8 +511,10 @@ class MicrophoneInput { } handleListeningState() { - this.stopRecording(); - this.audioChunks = []; + void this.stopRecording(); + this.pcmChunks = []; + this.pcmFrameCount = 0; + this.captureOverflow = false; this.hasStartedRecording = false; this.silenceStartTime = null; this.lastAudioTime = null; @@ -527,11 +523,18 @@ class MicrophoneInput { } handleRecordingState() { - if (!this.mediaRecorder) return; + if (!this.captureNode) return; - if (!this.hasStartedRecording && this.mediaRecorder.state !== "recording") { + if (!this.hasStartedRecording) { this.hasStartedRecording = true; - this.mediaRecorder.start(1000); + this.recordingId += 1; + this.pcmChunks = []; + this.pcmFrameCount = 0; + this.captureOverflow = false; + this.captureNode.port.postMessage({ + type: "start", + recordingId: this.recordingId, + }); } clearTimeout(this.waitingTimer); @@ -548,12 +551,22 @@ class MicrophoneInput { } handleProcessingState() { - this.stopRecording(); void this.process(); } - setupAudioAnalysis(stream) { - this.audioContext = new (window.AudioContext || window.webkitAudioContext)(); + async setupAudioPipeline(stream) { + const AudioContextClass = window.AudioContext || window.webkitAudioContext; + if (!AudioContextClass || !globalThis.AudioWorkletNode) { + throw new DOMException("AudioWorklet is unavailable", "NotSupportedError"); + } + + this.audioContext = new AudioContextClass(); + if (!this.audioContext.audioWorklet) { + throw new DOMException("AudioWorklet is unavailable", "NotSupportedError"); + } + await this.audioContext.audioWorklet.addModule( + `/plugins/${PLUGIN_NAME}/webui/pcm-capture-processor.js`, + ); this.mediaStreamSource = this.audioContext.createMediaStreamSource(stream); this.analyserNode = this.audioContext.createAnalyser(); this.analyserNode.fftSize = 2048; @@ -561,6 +574,45 @@ class MicrophoneInput { this.analyserNode.maxDecibels = -10; this.analyserNode.smoothingTimeConstant = 0.85; this.mediaStreamSource.connect(this.analyserNode); + + this.captureNode = new AudioWorkletNode( + this.audioContext, + "whisper-pcm-capture", + { + channelCount: 1, + channelCountMode: "explicit", + processorOptions: { + maxFrames: Math.ceil( + this.audioContext.sampleRate * PCM_MAX_DURATION_SECONDS, + ), + }, + }, + ); + this.silentGain = this.audioContext.createGain(); + this.silentGain.gain.value = 0; + this.captureNode.port.onmessage = (event) => this.handleCaptureMessage(event); + this.mediaStreamSource.connect(this.captureNode); + this.captureNode.connect(this.silentGain); + this.silentGain.connect(this.audioContext.destination); + } + + handleCaptureMessage(event) { + const message = event.data || {}; + if (message.recordingId !== this.recordingId) return; + + if (message.type === "chunk" && message.samples instanceof ArrayBuffer) { + const chunk = new Float32Array(message.samples); + this.pcmChunks.push(chunk); + this.pcmFrameCount += chunk.length; + } else if (message.type === "stopped") { + this.captureStopResolver?.(); + this.captureStopResolver = null; + } else if (message.type === "overflow") { + this.captureOverflow = true; + if (this.status === Status.RECORDING || this.status === Status.WAITING) { + this.status = Status.PROCESSING; + } + } } startAudioAnalysis() { @@ -616,10 +668,16 @@ class MicrophoneInput { } stopRecording() { - if (this.mediaRecorder?.state === "recording") { - this.mediaRecorder.stop(); - this.hasStartedRecording = false; - } + if (!this.captureNode || !this.hasStartedRecording) return Promise.resolve(); + + this.hasStartedRecording = false; + return new Promise((resolve) => { + this.captureStopResolver = resolve; + this.captureNode.port.postMessage({ + type: "stop", + recordingId: this.recordingId, + }); + }); } densify(value) { @@ -627,47 +685,51 @@ class MicrophoneInput { } async process() { - if (this.audioChunks.length === 0) { + const processingRecordingId = this.recordingId; + const sourceSampleRate = this.audioContext?.sampleRate; + if (!sourceSampleRate) return; + + await this.stopRecording(); + + if (this.disposed || processingRecordingId !== this.recordingId) return; + + if (this.pcmFrameCount === 0) { if (this.status === Status.PROCESSING) { this.status = Status.LISTENING; } return; } - const audioBlob = new Blob(this.audioChunks, { type: "audio/wav" }); - const audio = await this.convertBlobToBase64(audioBlob); + const sourcePcm = concatenatePcmChunks(this.pcmChunks, this.pcmFrameCount); + const samples = resampleMonoPcm( + sourcePcm, + sourceSampleRate, + ); + const audio = encodePcmPayload(samples); try { const result = await callJsonApi(`/plugins/${PLUGIN_NAME}/transcribe`, { audio, }); const text = this.filterResult(result?.text || ""); - if (text) { + if (text && !this.disposed && processingRecordingId === this.recordingId) { await this.updateCallback(text, true); } } catch (error) { - console.error("[Whisper STT] Transcription failed", error); - window.toastFetchError?.("Transcription error", error); + if (!this.disposed && processingRecordingId === this.recordingId) { + console.error("[Whisper STT] Transcription failed", error); + window.toastFetchError?.("Transcription error", error); + } } finally { - this.audioChunks = []; + this.pcmChunks = []; + this.pcmFrameCount = 0; + this.captureOverflow = false; if (this.status === Status.PROCESSING) { this.status = Status.LISTENING; } } } - convertBlobToBase64(audioBlob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - const result = String(reader.result || ""); - resolve(result.split(",")[1] || ""); - }; - reader.onerror = (error) => reject(error); - reader.readAsDataURL(audioBlob); - }); - } - filterResult(text) { const normalized = String(text || "").trim(); if (!normalized) return ""; @@ -678,7 +740,7 @@ class MicrophoneInput { (normalized.startsWith("[") && normalized.endsWith("]")); if (wrapped) { - console.log(`[Whisper STT] Discarding transcription: ${normalized}`); + console.log("[Whisper STT] Discarding non-speech transcription result"); return ""; } @@ -704,14 +766,20 @@ class MicrophoneInput { } dispose() { + this.disposed = true; clearTimeout(this.waitingTimer); this.waitingTimer = null; this.stopAudioAnalysis(); + this.captureStopResolver?.(); + this.captureStopResolver = null; + try { - this.mediaRecorder?.stream?.getTracks?.().forEach((track) => track.stop()); + this.captureNode?.disconnect?.(); + this.silentGain?.disconnect?.(); + this.mediaStreamSource?.disconnect?.(); } catch (_error) { - // Ignore media cleanup failures. + // Ignore audio graph cleanup failures. } try { @@ -727,12 +795,14 @@ class MicrophoneInput { } this.mediaStream = null; - this.mediaRecorder = null; this.mediaStreamSource = null; this.analyserNode = null; + this.captureNode = null; + this.silentGain = null; this.audioContext = null; - this.audioChunks = []; - this.lastChunk = null; + this.pcmChunks = []; + this.pcmFrameCount = 0; + this.captureOverflow = false; this.hasStartedRecording = false; } } diff --git a/preload.py b/preload.py index e06432ee5..57bbc59ed 100644 --- a/preload.py +++ b/preload.py @@ -1,3 +1,4 @@ +import requirements import asyncio from helpers import runtime from helpers.print_style import PrintStyle diff --git a/prepare.py b/prepare.py index 88a3bd8c9..5ea4695d5 100644 --- a/prepare.py +++ b/prepare.py @@ -1,3 +1,4 @@ +import requirements from helpers import dotenv, migration, runtime, settings import string import random diff --git a/prompts/agent.system.main.environment.md b/prompts/agent.system.main.environment.md index 0c4b81653..08ace39e9 100644 --- a/prompts/agent.system.main.environment.md +++ b/prompts/agent.system.main.environment.md @@ -1,10 +1,14 @@ ## Environment -live in kali linux docker container use debian kali packages +live in an official Python docker image based on Debian Trixie slim and use Debian packages agent zero framework is python project in /a0 folder linux fully root accessible via terminal -Python runtimes: -- /opt/venv/bin/python: task code and task dependencies -- /opt/venv-a0/bin/python: Agent Zero framework, backend, plugins/hooks and import checks -do not use one runtime as proof for the other +Python runtime: +- /usr/local/bin/python is the global environment for Agent Zero, WebUI/API handlers, plugins/hooks, and local task/user code. +- Install Python dependencies into the global environment unless the work explicitly targets an isolated sandbox image or the operating system. + +WebUI JSON API: +- API handlers live at /api/ and usually accept JSON POST requests. +- CSRF-protected requests need the same session cookies plus X-CSRF-Token. +- Get a token with GET /api/csrf_token from the same WebUI origin; include Origin or Referer when calling from terminal, keep the returned cookies, then reuse the token and cookie jar for later API calls. before Agent Zero framework development or WebUI API calls, load a0-development and read relevant references diff --git a/requirements.py b/requirements.py new file mode 100644 index 000000000..79879f86d --- /dev/null +++ b/requirements.py @@ -0,0 +1,6 @@ +from pathlib import Path + +import depfix + +# Resolve from the source tree so every entrypoint works from an arbitrary cwd. +depfix.default_requirements(Path(__file__).with_name("requirements.txt")) diff --git a/requirements.txt b/requirements.txt index ef4b7ebbf..8fe4ab7ad 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,8 @@ a2wsgi==1.10.8 ansio==0.0.1 -docker==7.1.0 -duckduckgo-search==6.1.12 +depfix +# docker==7.1.0 +# duckduckgo-search==6.1.12 pyreqwest-impersonate==0.5.3 # freeze nearest wheel-backed release; 0.5.5 is source-only faiss-cpu==1.11.0 fastmcp==3.2.4 @@ -18,7 +19,6 @@ kokoro>=0.9.2 simpleeval==1.0.3 langchain-core==0.3.49 langchain-community==0.3.19 -langchain-unstructured==0.1.6 liteparse==2.0.3 litellm==1.104.0 openai==2.54.0 diff --git a/run_tunnel.py b/run_tunnel.py index e7ac7908d..41587c7d1 100644 --- a/run_tunnel.py +++ b/run_tunnel.py @@ -1,3 +1,4 @@ +import requirements import threading from flask import Flask, request from helpers import runtime, dotenv, process diff --git a/run_ui.py b/run_ui.py index 59ad553de..5751c1ad6 100644 --- a/run_ui.py +++ b/run_ui.py @@ -1,3 +1,4 @@ +import requirements import initialize from helpers import dotenv, extension, runtime from helpers.api import csrf_protect, requires_auth diff --git a/skills/a0-create-agent/SKILL.md b/skills/a0-create-agent/SKILL.md index 8050e9c43..7ad5f04c4 100644 --- a/skills/a0-create-agent/SKILL.md +++ b/skills/a0-create-agent/SKILL.md @@ -309,7 +309,7 @@ The root `/a0/prompts` directory contains powerful defaults. A profile can overr | `agent.system.main.communication.md` | A different response contract, such as no `thoughts` array, a different JSON schema, plain Markdown answers, or a domain-specific output envelope. This is the main lever for output format changes. | | `agent.system.main.solving.md` | A different problem-solving loop, delegation policy, verification standard, or autonomy level. | | `agent.system.main.tips.md` | Different file-handling, skill-use, memory, or operational best-practice defaults. | -| `agent.system.main.environment.md` | A different runtime/environment description than the default Kali/Docker Agent Zero environment. | +| `agent.system.main.environment.md` | A different runtime/environment description than the default Debian Trixie Docker environment. | | `agent.system.main.role.md` | A fundamentally different base identity. Rare; prefer `specifics.md` unless replacing the base role is intentional. | | `agent.system.tool.response.md` | Different final-response tool instructions, such as stricter final formatting or use of includes for long output. | | `fw.user_message.md` / `fw.ai_response.md` | Different framework message wrapping. Advanced and fragile; override only with a clear reason. | @@ -322,7 +322,7 @@ When a blueprint includes any of these, add an entry to `prompt_strategy.root_pr |---|---|---| | `agent.system.main.role.md` | Replace the base role framing wholesale (rare — most profiles layer via `specifics.md` instead) | `/a0/agents/agent0/prompts/agent.system.main.role.md` | | `agent.system.main.communication.md` | Change reply format / communication style | `/a0/agents/developer/prompts/agent.system.main.communication.md`, `/a0/agents/researcher/prompts/...` | -| `agent.system.main.environment.md` | Describe a non-default runtime environment | `/a0/agents/hacker/prompts/agent.system.main.environment.md` (Kali/Docker) | +| `agent.system.main.environment.md` | Describe a non-default runtime environment | `/a0/agents/hacker/prompts/agent.system.main.environment.md` (Debian/security tooling) | | `agent.system.tool..md` | Document a profile-specific tool (see Step 6) | `/a0/agents/_example/prompts/agent.system.tool.example_tool.md` | > [!TIP] diff --git a/skills/a0-create-plugin/references/implementation.md b/skills/a0-create-plugin/references/implementation.md index af7c0be76..19d38b2dc 100644 --- a/skills/a0-create-plugin/references/implementation.md +++ b/skills/a0-create-plugin/references/implementation.md @@ -157,7 +157,7 @@ The framework calls exported functions through `helpers.plugins.call_plugin_hook | `pre_update()` | Immediately before updating plugin code | Stop plugin-owned processes or prepare state when required. | | `uninstall()` | Before the framework deletes the custom plugin directory | Stop owned processes, unregister integrations, and remove plugin-owned dependencies and resources. | -Hooks run inside the **Agent Zero framework runtime**, not the separate agent execution environment, and may be sync or async. Keep lifecycle entrypoints in `hooks.py`; delegate implementation to plugin-local helpers as needed. For example, with the corresponding helper functions implemented by the plugin: +Hooks run inside the **global Docker Python environment**; sandbox dependencies explicitly target that sandbox, and may be sync or async. Keep lifecycle entrypoints in `hooks.py`; delegate implementation to plugin-local helpers as needed. For example, with the corresponding helper functions implemented by the plugin: ```python from usr.plugins.my_plugin.helpers import runtime @@ -189,14 +189,14 @@ Omit `execute.py` by default. It is only for a separate, explicitly requested ma ### Environment targeting rules - If `hooks.py` runs `sys.executable -m pip install ...`, it installs into the same Python environment that is running Agent Zero. - That is correct for dependencies needed by the plugin inside the framework runtime. -- If the dependency is meant for the separate agent runtime or for OS-level tools, do **not** assume the current environment is correct. +- If the dependency is meant for the isolated sandbox runtime or for OS-level tools, do **not** assume the current environment is correct. Instead, explicitly switch targets in a subprocess: - invoke the exact Python interpreter for the target runtime - activate the target virtualenv in the subprocess before running `pip` - run the relevant OS package manager from a subprocess configured for the intended environment -In Docker, this usually means `hooks.py` affects `/opt/venv-a0` unless you intentionally target `/opt/venv` or another environment. +In Docker, `hooks.py` affects `/usr/local/bin/python`; dependencies intended for a sandbox must be installed inside that sandbox. --- @@ -219,6 +219,6 @@ Provide its callable contract in a policy-filtered `agent.system.tool.*.md` prom ## Local Verification -Verify the named Docker runtime and source sync first. Use `/opt/venv-a0/bin/python` for framework imports and hooks, and `/opt/venv/bin/python` only for task-runtime code. Compile changed Python, run focused tests, then exercise the actual API/tool/UI path. For lifecycle changes, exercise normal install, repeated install/update, and uninstall through management APIs using isolated test data; confirm readiness without Execute and removal of owned dependencies without touching shared ones. Check effective configuration, plugin toggles, and cleanup. A successful import is not a live behavior test. +Verify the named Docker runtime and source sync first. Use `depfix run` with `/usr/local/bin/python` for framework imports and hooks; use the local execution destination when modifying Agent Zero. Compile changed Python, run focused tests, then exercise the actual API/tool/UI path. For lifecycle changes, exercise normal install, repeated install/update, and uninstall through management APIs using isolated test data; confirm readiness without Execute and removal of owned dependencies without touching shared ones. Check effective configuration, plugin toggles, and cleanup. A successful import is not a live behavior test. For local-only plugins, a GitHub repository and Index submission are unnecessary. Do not add dependencies, pages, tools, or hooks that the requested feature does not need. diff --git a/skills/a0-development/SKILL.md b/skills/a0-development/SKILL.md index fbcec7ac6..fff23dbf1 100644 --- a/skills/a0-development/SKILL.md +++ b/skills/a0-development/SKILL.md @@ -42,7 +42,7 @@ Use this skill to develop Agent Zero or operate an existing instance on the user 2. Before editing, read the applicable `AGENTS.md` chain from the repo root to every file you expect to touch. 3. New capabilities should usually be plugins. For plugin-specific work, load `a0-create-plugin` for authoring/review/contribution or `a0-manage-plugin` for discovery and lifecycle operations. 4. Do not assume ports. Discover WebUI host/port from startup output, launcher or Docker mapping, or explicit `--host`, `--port`, `WEB_UI_HOST`, and `WEB_UI_PORT` configuration. -5. In Docker, framework checks belong to `/opt/venv-a0` and agent/user code execution belongs to `/opt/venv`. Do not use one runtime as proof for the other. +5. In Docker, framework checks and local agent/user Python execution use the official image's global Python environment; isolated sandbox images keep independent runtimes. 6. Treat `/a0/` as the runtime framework root inside Docker. In local development it means the repository root. If a live container matters, prove that `/a0` matches the checkout before trusting source-only conclusions. 7. Do not document or change ignored `usr/` or `tmp/` runtime state unless the user explicitly asks. diff --git a/skills/a0-development/references/architecture-runtime.md b/skills/a0-development/references/architecture-runtime.md index 97e7b09cd..7dad1887e 100644 --- a/skills/a0-development/references/architecture-runtime.md +++ b/skills/a0-development/references/architecture-runtime.md @@ -6,22 +6,14 @@ - WebUI entry point: `/a0/run_ui.py` - Runtime arguments and WebUI port resolution: `/a0/helpers/runtime.py` - Docker Python runtimes: `/a0/docker/base/fs/ins/install_python.sh` -- Docker framework activation: `/a0/docker/run/fs/ins/setup_venv.sh` - Docker UI launch manager: `/a0/docker/run/fs/exe/self_update_manager.py` - Search/discovery roots: `/a0/helpers/subagents.py`, `/a0/helpers/skills.py`, `/a0/helpers/projects.py` -## Runtime Split +## Python Runtime -Agent Zero has two Docker Python runtimes: +The outer Docker container is based on `python:3.12-slim-trixie`. Its global Python environment runs the WebUI backend, API, scheduler, agent loop, framework imports, plugin hooks, framework-side tools, and local agent/user Python execution. The image does not create or activate a virtual environment. -| Runtime | Python | Purpose | -|---|---|---| -| `/opt/venv-a0` | 3.12.4 | Framework runtime. Runs the WebUI backend, API, scheduler, agent loop, framework imports, plugin hooks, and framework-side tools. | -| `/opt/venv` | 3.13 | Agent execution runtime. Use for Python code executed on behalf of the agent or user task dependencies. | - -Use `/opt/venv-a0` for framework import checks, WebUI startup checks, API/plugin hook behavior, and `py_compile` of framework code inside Docker. Use `/opt/venv` only when the feature explicitly targets agent/user code execution. - -Do not claim a package works in the framework because it imports in `/opt/venv`, and do not claim user-code execution works because it imports in `/opt/venv-a0`. +Use `/usr/local/bin/python` for framework import checks, WebUI startup checks, API/plugin hook behavior, and local `py_compile` checks. Code run in an isolated sandbox uses the Python supplied by that sandbox image and is not evidence about the outer image's global environment, or vice versa. ## Ports And URLs diff --git a/skills/a0-development/references/plugins-workflow.md b/skills/a0-development/references/plugins-workflow.md index a6108c5ad..9682e9d69 100644 --- a/skills/a0-development/references/plugins-workflow.md +++ b/skills/a0-development/references/plugins-workflow.md @@ -32,8 +32,8 @@ Use root framework directories only when changing bundled framework behavior its - Bundled plugins under `plugins/` may use `plugins....` imports. - User plugins under `usr/plugins/` should use `usr.plugins....` imports. - Avoid `sys.path` hacks and symlink-dependent imports. -- `hooks.py` runs inside the framework runtime (`/opt/venv-a0` in Docker). Install/update setup and dependency installation belong in `install()`; cleanup and removal of owned dependencies belong in `uninstall()`. Never use `execute.py` for these operations. Follow the required lifecycle contract in `a0-create-plugin`. -- If a plugin must prepare the agent execution runtime or system packages, it must explicitly target that environment in a subprocess. +- `hooks.py` runs inside the global Docker Python environment. Install/update setup and dependency installation belong in `install()`; cleanup and removal of owned dependencies belong in `uninstall()`. Never use `execute.py` for these operations. Follow the required lifecycle contract in `a0-create-plugin`. +- If a plugin must prepare the isolated sandbox runtime or system packages, it must explicitly target that environment in a subprocess. ## Manifest And Configuration diff --git a/tests/test_browser_agent_regressions.py b/tests/test_browser_agent_regressions.py index 0d4dabccf..b4a3acad6 100644 --- a/tests/test_browser_agent_regressions.py +++ b/tests/test_browser_agent_regressions.py @@ -628,7 +628,8 @@ def test_browser_installs_current_patchright_chromium_for_host_architecture( def install(command, *, env): assert command == [ - sys.executable, + "depfix", + "run", "-m", "patchright", "install", @@ -744,6 +745,38 @@ def test_browser_playwright_binary_ignores_retired_usr_cache(monkeypatch, tmp_pa assert get_playwright_binary() is None +def test_browser_playwright_fallback_runs_depfix_managed_module(monkeypatch, tmp_path): + binary = tmp_path / "chromium" / "chrome" + discovered = iter((None, binary)) + commands = [] + monkeypatch.setattr( + browser_playwright_module, + "get_playwright_binary", + lambda: next(discovered), + ) + monkeypatch.setattr( + browser_playwright_module, + "configure_playwright_env", + lambda: str(tmp_path), + ) + monkeypatch.setattr( + browser_playwright_module.subprocess, + "check_call", + lambda command, **kwargs: commands.append((command, kwargs)), + ) + + assert browser_playwright_module.ensure_playwright_binary() == binary + assert commands[0][0] == [ + "depfix", + "run", + "-m", + "playwright", + "install", + "chromium", + ] + assert commands[0][1]["env"]["PLAYWRIGHT_BROWSERS_PATH"] == str(tmp_path) + + def test_browser_playwright_cache_migrates_valid_retired_usr_cache(monkeypatch, tmp_path): _patch_playwright_cache_root(monkeypatch, tmp_path) retired_cache = tmp_path / "usr" / "plugins" / "_browser" / "playwright" @@ -2691,7 +2724,7 @@ def test_browser_docker_installs_full_chromium_to_tmp_cache(): requirements = (PROJECT_ROOT / "requirements.txt").read_text(encoding="utf-8") assert "PLAYWRIGHT_BROWSERS_PATH=/a0/tmp/playwright" in script - assert "patchright install chromium --no-shell" in script + assert "depfix run -m patchright install chromium --no-shell" in script assert "playwright install chromium" not in script assert "uv pip install" not in script assert "patchright==1.61.2" in requirements diff --git a/tests/test_code_execution_destinations.py b/tests/test_code_execution_destinations.py new file mode 100644 index 000000000..96feb3266 --- /dev/null +++ b/tests/test_code_execution_destinations.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +import asyncio +from types import SimpleNamespace + +import pytest + +from plugins._code_execution.helpers import destinations as destination_helper +from plugins._code_execution.helpers.destinations import ExecutionDestination +from plugins._code_execution.tools import input as input_tool_module +from plugins._code_execution.tools.code_execution_tool import CodeExecution, State +from plugins._sandboxing.extensions.python.code_execution_destinations import ( + _10_sandboxes as sandbox_extension, +) +from plugins._sandboxing.extensions.python.code_execution_destinations import ( + _20_host as host_extension, +) + + +def test_named_missing_destination_is_lazy_sandbox(monkeypatch: pytest.MonkeyPatch) -> None: + async def only_local(agent): + return [ExecutionDestination("local", "local", "Local", "Local")] + + monkeypatch.setattr(destination_helper, "get_code_execution_destinations", only_local) + result = asyncio.run( + destination_helper.resolve_code_execution_destination(None, "research") + ) + assert result.kind == "sandbox" + assert result.target == "research" + assert result.status == "missing" + + +def test_unavailable_reserved_destinations_do_not_create_same_named_sandbox( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def only_local(agent): + return [ExecutionDestination("local", "local", "Local", "Local")] + + monkeypatch.setattr(destination_helper, "get_code_execution_destinations", only_local) + with pytest.raises(ValueError, match="not currently available"): + asyncio.run(destination_helper.resolve_code_execution_destination(None, "host")) + + +def test_sandbox_extension_advertises_default_and_all_managed_sandboxes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(sandbox_extension, "defaults", lambda agent=None: ("default", "temporary", "host")) + monkeypatch.setattr( + sandbox_extension, + "get_manager", + lambda agent=None: SimpleNamespace( + list=lambda: [ + SimpleNamespace(name="default", sandbox_type="temporary", network="host", status="running"), + SimpleNamespace(name="research", sandbox_type="permanent", network="none", status="stopped"), + ] + ), + ) + values = [ExecutionDestination("local", "local", "Local", "Local")] + asyncio.run(sandbox_extension.IncludeSandboxDestinations(None).execute(values)) + assert [value.id for value in values] == ["default", "local", "research"] + assert values[-1].target == "research" + assert values[-1].status == "stopped" + + +def test_host_extension_only_advertises_enabled_connector( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import plugins._a0_connector.helpers.remote_tool_prompts as prompts + + agent = SimpleNamespace(context=SimpleNamespace(id="chat-1")) + values: list[ExecutionDestination] = [] + monkeypatch.setattr( + prompts, + "remote_tool_prompt_availability", + lambda context_id: {"code_execution_remote": False}, + ) + host_extension.IncludeConnectedHostDestination(agent).execute(values) + assert values == [] + monkeypatch.setattr( + prompts, + "remote_tool_prompt_availability", + lambda context_id: {"code_execution_remote": True}, + ) + host_extension.IncludeConnectedHostDestination(agent).execute(values) + assert [(value.id, value.kind) for value in values] == [("host", "host")] + + +def test_code_execution_session_keys_include_destination() -> None: + tool = object.__new__(CodeExecution) + tool.destination = ExecutionDestination( + "default", "sandbox", "Default", "Default sandbox", target="default" + ) + tool.state = State(ssh_enabled=False, shells={}) + assert tool._session_key(0) == "default:0" + tool.destination = ExecutionDestination("local", "local", "Local", "Local") + assert tool._session_key(0) == 0 + + +def test_local_python_execution_uses_depfix_store_fallback(monkeypatch: pytest.MonkeyPatch) -> None: + tool = object.__new__(CodeExecution) + tool.destination = ExecutionDestination("local", "local", "Local", "Local") + + async def capture(_cfg, _session, command, _reset, _prefix): + return command + + monkeypatch.setattr(tool, "terminal_session", capture) + command = asyncio.run(tool.execute_python_code({}, 0, "import flask")) + + assert command == "depfix run -m IPython -- -c 'import flask'" + + +def test_input_uses_connector_input_operation_for_host( + monkeypatch: pytest.MonkeyPatch, +) -> None: + captured: dict[str, object] = {} + + class FakeCodeExecution: + def __init__(self, agent, name, method, args, message, loop_data): + captured["args"] = args + self.log = None + + async def execute(self, **kwargs): + captured["kwargs"] = kwargs + return SimpleNamespace(message="ok") + + monkeypatch.setattr(input_tool_module, "CodeExecution", FakeCodeExecution) + tool = object.__new__(input_tool_module.Input) + tool.args = {"destination": "host", "session": 4} + tool.agent = SimpleNamespace() + tool.message = None + tool.loop_data = None + tool.log = None + + asyncio.run(tool.execute(keyboard="Y")) + + assert captured["args"] == { + "runtime": "input", + "keyboard": "Y", + "session": 4, + "destination": "host", + } diff --git a/tests/test_docker_apt_layers.py b/tests/test_docker_apt_layers.py new file mode 100644 index 000000000..a9aba97af --- /dev/null +++ b/tests/test_docker_apt_layers.py @@ -0,0 +1,51 @@ +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +BASE = ROOT / "docker" / "base" +RUN = ROOT / "docker" / "run" + + +def _read(path: Path) -> str: + return path.read_text(encoding="utf-8") + + +def test_base_image_uses_builtin_utf8_locale() -> None: + dockerfile = _read(BASE / "Dockerfile") + + assert "ENV LANG=C.UTF-8" in dockerfile + assert "ENV LC_ALL=C.UTF-8" in dockerfile + assert "en_US.UTF-8" not in dockerfile + assert "install -y locales" not in dockerfile + assert "/etc/locale.gen" not in dockerfile + + +def test_every_build_time_apt_layer_removes_its_own_lists() -> None: + apt_layers = ( + BASE / "Dockerfile", + BASE / "fs" / "ins" / "install_base_packages1.sh", + BASE / "fs" / "ins" / "install_base_packages2.sh", + BASE / "fs" / "ins" / "install_base_packages4.sh", + BASE / "fs" / "ins" / "install_python.sh", + BASE / "fs" / "ins" / "after_install.sh", + RUN / "fs" / "ins" / "install_playwright.sh", + RUN / "fs" / "ins" / "install_additional.sh", + RUN / "fs" / "ins" / "post_install.sh", + ) + + for path in apt_layers: + contents = _read(path) + assert "/var/lib/apt/lists/*" in contents, path + + +def test_build_steps_do_not_prime_apt_for_later_layers() -> None: + pre_install = _read(RUN / "fs" / "ins" / "pre_install.sh") + + assert "apt-get update" not in pre_install + + +def test_base_image_keeps_the_standard_native_python_build_toolchain() -> None: + install_script = _read(BASE / "fs" / "ins" / "install_base_packages1.sh") + + assert "build-essential" in install_script + assert "cmake" in install_script diff --git a/tests/test_docker_python_runtime.py b/tests/test_docker_python_runtime.py new file mode 100644 index 000000000..148b44df4 --- /dev/null +++ b/tests/test_docker_python_runtime.py @@ -0,0 +1,159 @@ +import runpy +import sys +from pathlib import Path +from types import SimpleNamespace + + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +REQUIREMENTS = PROJECT_ROOT / "requirements.txt" +BASE_DOCKERFILE = PROJECT_ROOT / "docker" / "base" / "Dockerfile" +INSTALL_PYTHON = ( + PROJECT_ROOT / "docker" / "base" / "fs" / "ins" / "install_python.sh" +) +INSTALL_PACKAGES3 = ( + PROJECT_ROOT / "docker" / "base" / "fs" / "ins" / "install_base_packages3.sh" +) +SETUP_VENV = PROJECT_ROOT / "docker" / "run" / "fs" / "ins" / "setup_venv.sh" +SUPERVISOR_CONFIG = ( + PROJECT_ROOT + / "docker" + / "run" + / "fs" + / "etc" + / "supervisor" + / "conf.d" + / "supervisord.conf" +) +TRIGGER_SELF_UPDATE = ( + PROJECT_ROOT / "docker" / "run" / "fs" / "exe" / "trigger_self_update.sh" +) + + +def _read(path: Path) -> str: + return path.read_text(encoding="utf-8", errors="ignore") + + +def test_base_image_uses_official_python_trixie_image() -> None: + dockerfile = _read(BASE_DOCKERFILE) + + assert dockerfile.count("FROM ") == 3 + assert "FROM debian:trixie-slim AS gvisor-package" in dockerfile + assert "FROM python:3.12-slim-trixie AS runtime" in dockerfile + assert "ENV UV_SYSTEM_PYTHON=1" in dockerfile + assert "PIP_ROOT_USER_ACTION=ignore" in dockerfile + assert "kalilinux" not in dockerfile.lower() + + +def test_node_and_bundled_npm_come_from_official_node_stage() -> None: + dockerfile = _read(BASE_DOCKERFILE) + install_script = _read(INSTALL_PACKAGES3) + + assert "FROM node:22-trixie-slim AS node-runtime" in dockerfile + assert "COPY --from=node-runtime /usr/local/bin/node" in dockerfile + assert "COPY --from=node-runtime /usr/local/lib/node_modules" in dockerfile + assert "node --version" in install_script + assert "npm --version" in install_script + assert "apt-get install" not in install_script + assert "nodejs npm" not in install_script + + +def test_docker_installs_into_global_python_without_virtualenv() -> None: + install_script = _read(INSTALL_PYTHON) + assert not SETUP_VENV.exists() + assert "python -m pip install" in install_script + assert "python3-venv" not in install_script + assert " -m venv " not in install_script + assert "bin/activate" not in install_script + + +def test_torch_pruning_targets_only_development_artifacts() -> None: + install_script = _read(INSTALL_PYTHON) + + assert "rm -rf" in install_script + assert "/site-packages/torch/test" in install_script + assert "/site-packages/torch/include" in install_script + assert "/site-packages/torch/bin" in install_script + + +def test_python_service_entrypoints_use_the_global_runtime() -> None: + supervisor = _read(SUPERVISOR_CONFIG) + trigger = _read(TRIGGER_SELF_UPDATE) + + assert ( + "command=/usr/local/bin/python /exe/supervisor_event_listener.py" + in supervisor + ) + assert 'exec depfix run "$SCRIPT_DIR/self_update_manager.py"' in trigger + + +def test_requirements_bootstrap_is_independent_of_working_directory( + monkeypatch, tmp_path: Path +) -> None: + captured: list[Path] = [] + monkeypatch.setitem( + sys.modules, + "depfix", + SimpleNamespace(default_requirements=lambda path: captured.append(Path(path))), + ) + monkeypatch.chdir(tmp_path) + + runpy.run_path(str(PROJECT_ROOT / "requirements.py")) + + assert captured == [PROJECT_ROOT / "requirements.txt"] + + +def test_tracked_outer_docker_setup_has_no_virtualenv_or_legacy_python_runtime() -> None: + paths = [ + PROJECT_ROOT / "DockerfileLocal", + *( + path + for path in (PROJECT_ROOT / "docker").rglob("*") + if path.is_file() + ), + ] + combined = "\n".join(_read(path) for path in paths) + + for forbidden in ( + "/opt/venv", + "/opt/venv-a0", + "/opt/pyenv", + "python3.13", + "setup_venv.sh", + "bin/activate", + "kalilinux/kali-rolling", + ): + assert forbidden not in combined + + +def test_runtime_dependencies_and_playwright_use_depfix_store() -> None: + install_python = _read(INSTALL_PYTHON) + requirements = _read(REQUIREMENTS) + install_a0 = _read(PROJECT_ROOT / "docker" / "run" / "fs" / "ins" / "install_A0.sh") + install_a02 = _read(PROJECT_ROOT / "docker" / "run" / "fs" / "ins" / "install_A02.sh") + install_playwright = _read( + PROJECT_ROOT / "docker" / "run" / "fs" / "ins" / "install_playwright.sh" + ) + + assert "depfix" in install_python + assert "depfix" in requirements + assert "depfix pip install -r /git/agent-zero/requirements.txt" in install_a0 + assert "uv pip install" not in install_a0 + assert "uv pip install" not in install_playwright + assert "depfix run -m patchright install chromium --no-shell" in install_playwright + assert 'bash /ins/install_A0.sh "$@"' in install_a02 + assert 'bash /ins/install_playwright.sh "$@"' in install_a02 + assert "depfix run /git/agent-zero/preload.py --dockerized=true" in install_a02 + assert "pip cache purge" not in install_a02 + assert "uv cache" not in install_a02 + + +def test_runtime_python_launchers_enable_depfix_store_fallback() -> None: + run_a0 = _read(PROJECT_ROOT / "docker" / "run" / "fs" / "exe" / "run_A0.sh") + run_tunnel = _read( + PROJECT_ROOT / "docker" / "run" / "fs" / "exe" / "run_tunnel_api.sh" + ) + trigger_update = _read(TRIGGER_SELF_UPDATE) + + assert "exec depfix run /exe/self_update_manager.py docker-run-ui" in run_a0 + assert "exec depfix run /a0/run_tunnel.py" in run_tunnel + assert 'exec depfix run "$SCRIPT_DIR/self_update_manager.py"' in trigger_update diff --git a/tests/test_document_query_plugin.py b/tests/test_document_query_plugin.py index e160fba68..216bb7677 100644 --- a/tests/test_document_query_plugin.py +++ b/tests/test_document_query_plugin.py @@ -2,7 +2,9 @@ from __future__ import annotations import asyncio import ipaddress +import subprocess import sys +import threading from pathlib import Path import pytest @@ -14,6 +16,7 @@ if str(ROOT) not in sys.path: from helpers import network as network_helper from plugins._document_query import hooks as document_query_hooks +from plugins._document_query.helpers import ocr_dependencies from plugins._document_query.helpers.fetch import FetchedDocument, fetch_public_resource import plugins._document_query.helpers.document_query as document_query_module from plugins._document_query.helpers.document_query import ( @@ -23,8 +26,12 @@ from plugins._document_query.helpers.document_query import ( from plugins._document_query.helpers.parsers.base import BaseParser from plugins._document_query.helpers.parsers import get_parsers_for_mimetype from plugins._document_query.helpers.parsers import liteparse as liteparse_module +from plugins._document_query.helpers.parsers import pdf as pdf_module +from plugins._document_query.helpers.parsers import unstructured as unstructured_module from plugins._document_query.helpers.parsers.liteparse import LiteParseParser +from plugins._document_query.helpers.parsers.pdf import PdfParser from plugins._document_query.helpers.parsers.text import TextParser +from plugins._document_query.helpers.parsers.unstructured import UnstructuredParser def run_async(coro): @@ -264,6 +271,206 @@ def test_text_parser_uses_prefetched_content(): assert text == '{"ok": true}' +def test_unstructured_parser_uses_local_partitioner(monkeypatch, tmp_path): + document_path = tmp_path / "notes.bin" + document_path.write_bytes(b"opaque") + fetched = FetchedDocument( + uri=str(document_path), + source_uri=str(document_path), + scheme="file", + mimetype="application/octet-stream", + content=b"opaque", + local_path=str(document_path), + ) + seen = [] + + monkeypatch.setattr( + unstructured_module, + "_partition_file", + lambda file_path: seen.append(file_path) or ["first", "second"], + ) + + assert UnstructuredParser()._parse_sync(fetched, {}) == "first\nsecond" + assert seen == [str(document_path)] + + +def test_requirements_omit_legacy_langchain_unstructured_wrapper(): + root_requirements = (ROOT / "requirements.txt").read_text(encoding="utf-8") + + assert "langchain-unstructured" not in root_requirements + + +def test_outer_base_image_omits_legacy_ocr_system_packages(): + dockerfile = (ROOT / "docker" / "base" / "Dockerfile").read_text( + encoding="utf-8" + ) + install_scripts = "\n".join( + path.read_text(encoding="utf-8") + for path in (ROOT / "docker" / "base" / "fs" / "ins").glob("*.sh") + ) + + assert "install_base_packages4.sh" not in dockerfile + assert not ( + ROOT / "docker" / "base" / "fs" / "ins" / "install_base_packages4.sh" + ).exists() + assert "tesseract-ocr" not in install_scripts + assert "poppler-utils" not in install_scripts + + +def test_ocr_dependencies_skip_apt_when_already_available(monkeypatch): + monkeypatch.setattr(ocr_dependencies, "_READY_PROFILES", set()) + monkeypatch.setattr( + ocr_dependencies, + "_dependencies_present", + lambda _packages, _commands: True, + ) + monkeypatch.setattr( + ocr_dependencies, + "_run_apt_command", + lambda *_args, **_kwargs: pytest.fail("apt must not run"), + ) + + ocr_dependencies.ensure_pdf_ocr_dependencies() + + assert ocr_dependencies._READY_PROFILES == {"pdf_ocr", "tesseract"} + + +def test_ocr_dependencies_fail_only_at_fallback_without_apt_access(monkeypatch): + monkeypatch.setattr(ocr_dependencies, "_READY_PROFILES", set()) + monkeypatch.setattr( + ocr_dependencies, + "_dependencies_present", + lambda _packages, _commands: False, + ) + monkeypatch.setattr(ocr_dependencies, "_apt_command_prefix", lambda: []) + + with pytest.raises(RuntimeError, match="Automatic installation requires apt-get"): + ocr_dependencies.ensure_tesseract_dependencies() + + +def test_pdf_ocr_dependencies_install_once_across_threads(monkeypatch): + monkeypatch.setattr(ocr_dependencies, "_READY_PROFILES", set()) + installed = False + calls = [] + + def dependencies_present(_packages, _commands): + return installed + + def run_apt(command, *, timeout): + nonlocal installed + calls.append((command, timeout)) + if "install" in command: + installed = True + return subprocess.CompletedProcess(command, 0, stdout="", stderr="") + + monkeypatch.setattr(ocr_dependencies, "_dependencies_present", dependencies_present) + monkeypatch.setattr( + ocr_dependencies, + "_missing_apt_packages", + lambda packages: list(packages), + ) + monkeypatch.setattr( + ocr_dependencies, + "_apt_command_prefix", + lambda: ["apt-get"], + ) + monkeypatch.setattr(ocr_dependencies, "_run_apt_command", run_apt) + monkeypatch.setattr(ocr_dependencies.PrintStyle, "info", lambda _message: None) + + threads = [ + threading.Thread(target=ocr_dependencies.ensure_pdf_ocr_dependencies) + for _ in range(4) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert calls == [ + (["apt-get", "update"], 300), + ( + [ + "apt-get", + "install", + "-y", + "--no-install-recommends", + "tesseract-ocr", + "tesseract-ocr-script-latn", + "poppler-utils", + ], + 900, + ), + ] + assert ocr_dependencies._READY_PROFILES == {"pdf_ocr", "tesseract"} + + +def test_pdf_full_page_ocr_installs_before_poppler_and_tesseract(monkeypatch): + events = [] + import pdf2image + import pytesseract + + monkeypatch.setattr( + pdf_module, + "ensure_pdf_ocr_dependencies", + lambda: events.append("install"), + ) + monkeypatch.setattr( + pdf2image, + "convert_from_path", + lambda _path: events.append("render") or ["page"], + ) + monkeypatch.setattr( + pytesseract, + "image_to_string", + lambda _page: events.append("ocr") or "text", + ) + + assert PdfParser()._parse_with_ocr("scan.pdf") == "text" + assert events == ["install", "render", "ocr"] + + +def test_embedded_image_tesseract_install_is_lazy(monkeypatch): + events = [] + import pytesseract + + monkeypatch.setattr( + pdf_module, + "ensure_tesseract_dependencies", + lambda: events.append("install"), + ) + monkeypatch.setattr( + pytesseract, + "image_to_string", + lambda _image, lang: events.append(f"ocr:{lang}") or "embedded text", + ) + + parser = pdf_module._on_demand_tesseract_blob_parser() + + assert events == [] + assert parser._analyze_image(object()) == "embedded text" + assert events == ["install", "ocr:eng"] + + +def test_unstructured_installs_ocr_packages_only_for_pdf_and_images(monkeypatch): + events = [] + monkeypatch.setattr( + unstructured_module, + "ensure_tesseract_dependencies", + lambda: events.append("tesseract"), + ) + monkeypatch.setattr( + unstructured_module, + "ensure_pdf_ocr_dependencies", + lambda: events.append("pdf"), + ) + + unstructured_module._ensure_ocr_dependencies("text/plain", "notes.txt") + unstructured_module._ensure_ocr_dependencies("image/png", "scan.png") + unstructured_module._ensure_ocr_dependencies("application/pdf", "scan.pdf") + + assert events == ["tesseract", "pdf"] + + def test_compatibility_imports_point_to_plugin_classes(): pytest.importorskip("langchain_core") @@ -439,6 +646,34 @@ def test_liteparse_parser_always_uses_subprocess(monkeypatch): assert parser._parse_sync(fetched, {"liteparse_subprocess": False}) == "ok" +def test_liteparse_subprocess_uses_depfix_store_fallback(monkeypatch): + fetched = FetchedDocument( + uri="/tmp/report.pdf", + source_uri="/tmp/report.pdf", + scheme="file", + mimetype="application/pdf", + content=b"", + local_path="/tmp/report.pdf", + ) + parser = LiteParseParser() + calls = [] + + def fake_run(command, **kwargs): + calls.append((command, kwargs)) + return subprocess.CompletedProcess(command, 0, stdout='{"text": "ok"}', stderr="") + + monkeypatch.setattr(liteparse_module.subprocess, "run", fake_run) + monkeypatch.setattr(parser, "_liteparse_kwargs", lambda *_args: {}) + + assert parser._parse_subprocess(fetched, {}) == "ok" + assert calls[0][0] == [ + "depfix", + "run", + "-m", + "plugins._document_query.helpers.parsers.liteparse_worker", + ] + + def test_liteparse_auto_disables_ocr_for_large_text_pdf(monkeypatch): parser = LiteParseParser() fetched = FetchedDocument( diff --git a/tests/test_parallel_code_lifetime.py b/tests/test_parallel_code_lifetime.py index ff8e5654c..776dde6c9 100644 --- a/tests/test_parallel_code_lifetime.py +++ b/tests/test_parallel_code_lifetime.py @@ -9,15 +9,19 @@ from plugins._code_execution.tools import code_execution_tool as code @pytest.mark.asyncio +@pytest.mark.parametrize("destination", ["local", "default"]) @pytest.mark.parametrize("parallel,cancel", [(False, False), (True, False), (True, True)]) -async def test_code_job_keeps_polling_after_output_timeout_without_reexecuting(monkeypatch, parallel, cancel): +async def test_code_job_keeps_polling_after_output_timeout_without_reexecuting(monkeypatch, parallel, cancel, destination): shell = SimpleNamespace(running=True, session=SimpleNamespace(close=AsyncMock())) job = SimpleNamespace(result=None) if parallel else None agent = SimpleNamespace(handle_intervention=AsyncMock()) tool = object.__new__(code.CodeExecution) tool.agent = agent - tool.args = {"runtime": "terminal", "session": 0, "code": "long command"} - tool.state = SimpleNamespace(shells={0: shell}) + tool.args = {"destination": destination, "runtime": "terminal", "session": 0, "code": "long command"} + resolved = code.ExecutionDestination(destination, "local" if destination == "local" else "sandbox", destination, destination, target=destination) + tool.destination = resolved + tool.state = SimpleNamespace(shells={tool._session_key(0): shell}) + monkeypatch.setattr(code, "resolve_code_execution_destination", AsyncMock(return_value=resolved)) cfg = {"output_timeouts": {"first_output_timeout": 1}} monkeypatch.setattr(code, "_get_config", lambda _: cfg) monkeypatch.setattr(parallel_tools, "get_parallel_worker_job", lambda _: job) diff --git a/tests/test_sandboxing.py b/tests/test_sandboxing.py new file mode 100644 index 000000000..9525f6377 --- /dev/null +++ b/tests/test_sandboxing.py @@ -0,0 +1,670 @@ +from __future__ import annotations + +import datetime as dt +import dataclasses +import json +import os +import subprocess +from pathlib import Path +from unittest.mock import Mock + +import pytest + +from plugins._sandboxing.helpers.images import ( + SandboxImageConfig, + SandboxImageInfo, + SandboxImageManager, + image_info_dict, + normalize_image_reference, + validate_digest, +) +from plugins._sandboxing.helpers.manager import ( + ROOTFS_SNAPSHOT, + SandboxConfig, + SandboxError, + SandboxInfo, + SandboxManager, + SandboxMount, + sandbox_info_dict, + validate_name, +) + + +IMAGE_DIGEST = "sha256:" + "a" * 64 +IMAGE_REFERENCE = "docker.io/library/python:3.13-slim-bookworm" + + +def _cache_image( + images: SandboxImageManager, + *, + digest: str = IMAGE_DIGEST, + reference: str = IMAGE_REFERENCE, + last_used_at: str | None = None, +) -> SandboxImageInfo: + path = images.config.cache_dir / digest.replace(":", "-") + rootfs = path / "rootfs" + (rootfs / "bin").mkdir(parents=True) + (rootfs / "bin" / "sh").write_text("", encoding="utf-8") + (rootfs / "bin" / "bash").write_text("", encoding="utf-8") + (rootfs / "workspace").mkdir() + now = last_used_at or dt.datetime.now(dt.timezone.utc).isoformat() + info = SandboxImageInfo( + digest=digest, + reference=reference, + references=(reference,), + status="ready", + created_at=now, + last_used_at=now, + size_bytes=0, + os="linux", + architecture="amd64", + rootfs=rootfs, + environment=("PATH=/image/bin:/usr/bin:/bin",), + ) + images._write_info_path(path / "metadata.json", info) + return images.inspect(digest) + + +@pytest.fixture +def manager(tmp_path: Path) -> SandboxManager: + runsc = tmp_path / "runsc" + runsc.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + runsc.chmod(0o755) + images = SandboxImageManager( + SandboxImageConfig( + skopeo=runsc, + umoci=runsc, + cache_dir=tmp_path / "images", + default_image=IMAGE_REFERENCE, + cleanup_days=30, + max_output_bytes=4096, + ) + ) + _cache_image(images) + return SandboxManager( + SandboxConfig( + runsc=runsc, + instances_dir=tmp_path / "state" / "instances", + runsc_root=tmp_path / "runsc-root", + shared_dir=tmp_path / "shared", + default_image=IMAGE_REFERENCE, + temporary_lifetime_days=7, + max_output_bytes=4096, + ), + images, + ) + + +def _metadata( + manager: SandboxManager, + name: str, + *, + sandbox_type: str = "temporary", + status: str = "running", + last_used_at: str | None = None, +) -> dict: + now = last_used_at or dt.datetime.now(dt.timezone.utc).isoformat() + path = manager.config.instances_dir / name + for directory in (path, path / "bundle", path / "overlay", path / "logs"): + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + (path / ".lock").touch() + value = { + "schema_version": 2, + "name": name, + "sandbox_type": sandbox_type, + "network": "host", + "created_at": now, + "last_used_at": now, + "snapshot_at": None, + "rootfs_snapshot": None, + "image_ref": IMAGE_REFERENCE, + "image_digest": IMAGE_DIGEST, + "launch_mode": "detached", + "launcher_pid": None, + "last_known_status": status, + "mounts": [], + "ownership": {"chat_id": None, "project_id": None, "agent_id": None}, + } + manager._atomic_write_json(path / "metadata.json", value) + return value + + +def _info(name: str, status: str = "running") -> SandboxInfo: + now = dt.datetime.now(dt.timezone.utc).isoformat() + return SandboxInfo( + name=name, + status=status, + sandbox_type="temporary", + network="host", + created_at=now, + last_used_at=now, + snapshot_at=None, + expires_at=None, + ) + + +def test_name_validation_and_path_traversal_are_conservative() -> None: + for name in ("a", "alpha-1", "A.B_c", "x" * 64): + assert validate_name(name) == name + for name in ("", "../escape", "with/slash", "space here", "x" * 65): + with pytest.raises(SandboxError): + validate_name(name) + + +def test_public_info_is_json_serializable(tmp_path: Path) -> None: + info = dataclasses.replace( + _info("alpha"), mounts=(SandboxMount(tmp_path, "/mnt/data", True),) + ) + + encoded = json.dumps(sandbox_info_dict(info)) + + assert str(tmp_path) in encoded + + +def test_public_image_info_omits_private_rootfs_and_environment( + manager: SandboxManager, +) -> None: + info = manager.images.inspect(IMAGE_DIGEST) + + payload = image_info_dict(info) + + assert payload["digest"] == IMAGE_DIGEST + assert "rootfs" not in payload + assert "environment" not in payload + json.dumps(payload) + + +def test_image_reference_and_digest_validation_is_conservative() -> None: + assert normalize_image_reference("docker://python:3.13") == "python:3.13" + assert validate_digest(IMAGE_DIGEST) == IMAGE_DIGEST + for reference in ("", " docker:// ", "file:///tmp/image", "../image", "bad image"): + with pytest.raises(Exception): + normalize_image_reference(reference) + for digest in ("", "sha256:nope", "md5:" + "a" * 32): + with pytest.raises(Exception): + validate_digest(digest) + + +def test_daemonless_image_pull_is_digest_pinned_and_atomic( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + executable = tmp_path / "tool" + executable.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8") + executable.chmod(0o755) + images = SandboxImageManager( + SandboxImageConfig( + skopeo=executable, + umoci=executable, + cache_dir=tmp_path / "images", + default_image="docker.io/example/sandbox:latest", + max_output_bytes=4096, + ) + ) + calls: list[list[str]] = [] + + def fake_run(argv, *, timeout, operation, check=True): + command = list(argv) + calls.append(command) + if "inspect" in command: + return ( + 0, + json.dumps( + { + "Digest": IMAGE_DIGEST, + "Os": "linux", + "Architecture": "amd64", + } + ), + "", + False, + ) + if "unpack" in command: + bundle = Path(command[-1]) + rootfs = bundle / "rootfs" + (rootfs / "bin").mkdir(parents=True) + (rootfs / "bin" / "sh").write_text("sh", encoding="utf-8") + (rootfs / "bin" / "bash").write_text("bash", encoding="utf-8") + (bundle / "config.json").write_text( + json.dumps({"process": {"env": ["PATH=/custom/bin:/bin"]}}), + encoding="utf-8", + ) + return 0, "", "", False + + monkeypatch.setattr(images, "_run", fake_run) + + info = images.pull("docker.io/example/sandbox:latest") + + assert info.digest == IMAGE_DIGEST + assert info.rootfs and info.rootfs.is_dir() + copy = next(command for command in calls if "copy" in command) + assert ( + f"docker://docker.io/example/sandbox@{IMAGE_DIGEST}" in copy + ) + assert not any(path.name.startswith(".pull-") for path in images.config.cache_dir.iterdir()) + + +def test_image_cleanup_preserves_every_sandbox_reference( + manager: SandboxManager, +) -> None: + now = dt.datetime(2026, 8, 5, tzinfo=dt.timezone.utc) + old = (now - dt.timedelta(days=31)).isoformat() + unused_digest = "sha256:" + "b" * 64 + _cache_image( + manager.images, + digest=unused_digest, + reference="docker.io/example/unused:old", + last_used_at=old, + ) + _metadata(manager, "alpha", last_used_at=old) + + removed = manager.cleanup_images(now=now) + + assert removed == [unused_digest] + assert not (manager.images.config.cache_dir / unused_digest.replace(":", "-")).exists() + assert manager.images.inspect(IMAGE_DIGEST).digest == IMAGE_DIGEST + with pytest.raises(SandboxError, match="still used by sandboxes: alpha"): + manager.delete_image(IMAGE_DIGEST) + + +def test_tag_alias_updates_do_not_rebase_existing_digest( + manager: SandboxManager, +) -> None: + refreshed_digest = "sha256:" + "c" * 64 + _cache_image( + manager.images, + digest=refreshed_digest, + reference=IMAGE_REFERENCE, + ) + manager.images._ensure_layout() + with manager.images._cache_lock(): + manager.images._set_alias_locked(IMAGE_REFERENCE, refreshed_digest) + + old = manager.images.ensure(IMAGE_REFERENCE, digest=IMAGE_DIGEST) + new = manager.images.ensure(IMAGE_REFERENCE) + + assert old.digest == IMAGE_DIGEST + assert new.digest == refreshed_digest + + +def test_broken_unreferenced_image_can_be_deleted_by_exact_digest( + manager: SandboxManager, +) -> None: + digest = "sha256:" + "d" * 64 + path = manager.images.config.cache_dir / digest.replace(":", "-") + (path / "rootfs").mkdir(parents=True) + (path / "metadata.json").write_text("{}", encoding="utf-8") + + assert manager.delete_image(digest) is True + assert not path.exists() + + +def test_image_deletion_honors_digest_even_when_other_sandbox_metadata_is_broken( + manager: SandboxManager, +) -> None: + metadata = _metadata(manager, "broken-alpha") + metadata["schema_version"] = 999 + metadata["created_at"] = "not-a-timestamp" + manager._atomic_write_json( + manager.config.instances_dir / "broken-alpha" / "metadata.json", metadata + ) + + with pytest.raises(SandboxError, match="still used by sandboxes: broken-alpha"): + manager.delete_image(IMAGE_DIGEST) + + +def test_runsc_commands_select_fast_or_disk_overlay(manager: SandboxManager) -> None: + temporary = manager.runsc_command_for_test( + "alpha", "host", "temporary", "state", "alpha" + ) + permanent = manager.runsc_command_for_test( + "alpha", "none", "permanent", "state", "alpha" + ) + assert "--overlay2=root:memory" in temporary + assert not any(value.startswith("--overlay2=root:dir=") for value in temporary) + assert f"--overlay2=root:dir={manager.config.instances_dir / 'alpha' / 'overlay'}" in permanent + assert "--network=none" in permanent + for required in ( + "--allow-rootfs-tar-annotation", + "--rootless=true", + "--platform=systrap", + "--directfs=false", + "--file-access=exclusive", + "--file-access-mounts=shared", + ): + assert required in temporary + + +def test_oci_network_shared_and_optional_mount_contract( + manager: SandboxManager, tmp_path: Path +) -> None: + source_ro = tmp_path / "read-only" + source_rw = tmp_path / "read-write" + source_ro.mkdir() + source_rw.mkdir() + host = manager.oci_config_for_test( + "alpha", + "host", + "temporary", + mounts=[ + {"source": str(source_ro), "destination": "/mnt/input", "read_only": True}, + {"source": str(source_rw), "destination": "/mnt/output", "read_only": False}, + ], + ) + isolated = manager.oci_config_for_test("alpha", "none", "temporary") + assert {item["type"] for item in host["linux"]["namespaces"]} == { + "pid", + "ipc", + "uts", + "mount", + } + assert {item["type"] for item in isolated["linux"]["namespaces"]} == { + "pid", + "ipc", + "uts", + "mount", + "network", + } + mounts = {item["destination"]: item for item in host["mounts"]} + assert mounts["/shared"]["source"] == str(manager.config.shared_dir) + assert "rw" in mounts["/shared"]["options"] + assert "ro" in mounts["/mnt/input"]["options"] + assert "rw" in mounts["/mnt/output"]["options"] + assert "CAP_SYS_ADMIN" not in host["process"]["capabilities"]["bounding"] + assert host["root"]["path"] == str(manager.images.inspect(IMAGE_DIGEST).rootfs) + assert "PATH=/image/bin:/usr/bin:/bin" in host["process"]["env"] + + +def test_mounts_reject_symlinks_reserved_paths_and_duplicates( + manager: SandboxManager, tmp_path: Path +) -> None: + source = tmp_path / "source" + source.mkdir() + link = tmp_path / "link" + link.symlink_to(source, target_is_directory=True) + with pytest.raises(SandboxError): + manager.oci_config_for_test( + "alpha", "host", "temporary", [{"source": str(link), "destination": "/mnt/a"}] + ) + with pytest.raises(SandboxError): + manager.oci_config_for_test( + "alpha", "host", "temporary", [{"source": str(source), "destination": "/etc/a"}] + ) + with pytest.raises(SandboxError): + manager.oci_config_for_test( + "alpha", "host", "temporary", [{"source": str(source), "destination": "//etc/a"}] + ) + with pytest.raises(SandboxError): + manager.oci_config_for_test( + "alpha", + "host", + "temporary", + [ + {"source": str(source), "destination": "/mnt/a"}, + {"source": str(source), "destination": "/mnt/a"}, + ], + ) + + +def test_inspect_classifies_running_stopped_recoverable_stale_and_broken( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + metadata = _metadata(manager, "alpha") + monkeypatch.setattr(manager, "_runtime_state", lambda *args: ({"status": "running"}, None)) + assert manager.inspect("alpha").status == "running" + + snapshot = manager.config.instances_dir / "alpha" / ROOTFS_SNAPSHOT + snapshot.write_bytes(b"snapshot") + metadata["rootfs_snapshot"] = ROOTFS_SNAPSHOT + metadata["last_known_status"] = "stopped" + manager._atomic_write_json(snapshot.parent / "metadata.json", metadata) + monkeypatch.setattr(manager, "_runtime_state", lambda *args: (None, "container not found")) + assert manager.inspect("alpha").status == "stopped" + metadata["last_known_status"] = "running" + manager._atomic_write_json(snapshot.parent / "metadata.json", metadata) + assert manager.inspect("alpha").status == "recoverable" + snapshot.unlink() + assert manager.inspect("alpha").status == "stale" + monkeypatch.setattr(manager, "_runtime_state", lambda *args: (None, "permission denied")) + assert manager.inspect("alpha").status == "broken" + + +def test_invalid_metadata_and_symlink_entries_are_not_adopted( + manager: SandboxManager, tmp_path: Path +) -> None: + manager.config.instances_dir.mkdir(parents=True) + broken = manager.config.instances_dir / "broken" + broken.mkdir() + (broken / "metadata.json").write_text("{}", encoding="utf-8") + outside = tmp_path / "outside" + outside.mkdir() + (manager.config.instances_dir / "linked").symlink_to(outside, target_is_directory=True) + listed = manager.list() + assert [(item.name, item.status) for item in listed] == [("broken", "broken")] + with pytest.raises(SandboxError): + manager.delete("linked") + assert outside.exists() + + +def test_ensure_running_creates_missing_and_wakes_stopped( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + created = Mock(return_value=_info("new")) + monkeypatch.setattr(manager, "create", created) + assert manager.ensure_running("new").name == "new" + created.assert_called_once_with( + "new", network="host", sandbox_type="temporary", image="" + ) + + _metadata(manager, "sleeping", status="stopped") + monkeypatch.setattr(manager, "inspect", lambda name: _info(name, "stopped")) + started = Mock(return_value=_info("sleeping")) + monkeypatch.setattr(manager, "start", started) + assert manager.ensure_running("sleeping").status == "running" + started.assert_called_once_with("sleeping") + + +def test_stop_saves_before_termination_and_cleanup( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + _metadata(manager, "alpha") + calls: list[str] = [] + monkeypatch.setattr(manager, "_runtime_state", lambda *args: ({"status": "running"}, None)) + monkeypatch.setattr(manager, "_save_locked", lambda *args: calls.append("save")) + monkeypatch.setattr(manager, "_stop_runtime", lambda *args: calls.append("stop")) + monkeypatch.setattr(manager, "_force_runtime_delete", lambda *args: calls.append("delete") or True) + monkeypatch.setattr(manager, "inspect", lambda name: _info(name, "stopped")) + assert manager.stop("alpha").status == "stopped" + assert calls == ["save", "stop", "delete"] + + +def test_stop_runtime_force_deletes_when_kill_state_remains_running( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + metadata = _metadata(manager, "alpha") + monkeypatch.setattr( + manager, + "_runtime_state", + lambda *args: ({"status": "running"}, None), + ) + monkeypatch.setattr( + manager, + "_wait_for_status", + lambda *args, **kwargs: ({"status": "running"}, "last status was 'running'"), + ) + monkeypatch.setattr(manager, "_run_quiet", lambda *args, **kwargs: None) + force_delete = Mock(return_value=True) + monkeypatch.setattr(manager, "_force_runtime_delete", force_delete) + + manager._stop_runtime("alpha", metadata) + + force_delete.assert_called_once_with("alpha", metadata) + + +def test_start_refuses_missing_snapshot(manager: SandboxManager, monkeypatch: pytest.MonkeyPatch) -> None: + _metadata(manager, "alpha", status="stopped") + monkeypatch.setattr(manager, "_runtime_state", lambda *args: (None, "container not found")) + with pytest.raises(SandboxError, match="no valid restart snapshot"): + manager.start("alpha") + + +def test_failed_save_preserves_previous_snapshot( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + metadata = _metadata(manager, "alpha") + path = manager.config.instances_dir / "alpha" + snapshot = path / ROOTFS_SNAPSHOT + snapshot.write_bytes(b"last-good") + metadata["rootfs_snapshot"] = ROOTFS_SNAPSHOT + manager._atomic_write_json(path / "metadata.json", metadata) + monkeypatch.setattr(manager, "_runtime_state", lambda *args: ({"status": "running"}, None)) + monkeypatch.setattr( + subprocess, + "run", + lambda *args, **kwargs: subprocess.CompletedProcess(args[0], 1, "snapshot failed", ""), + ) + with pytest.raises(SandboxError, match="snapshot failed"): + manager.save("alpha") + assert snapshot.read_bytes() == b"last-good" + + +def test_delete_removes_exact_instance_only( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + _metadata(manager, "alpha") + _metadata(manager, "beta") + monkeypatch.setattr(manager, "_runtime_state", lambda *args: (None, "container not found")) + monkeypatch.setattr(manager, "_force_runtime_delete", lambda *args: True) + assert manager.delete("alpha") is True + assert not (manager.config.instances_dir / "alpha").exists() + assert (manager.config.instances_dir / "beta").exists() + + +def test_exec_uses_exact_argv_and_touches_last_use( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + metadata = _metadata(manager, "alpha") + monkeypatch.setattr(manager, "_runtime_state", lambda *args: ({"status": "running"}, None)) + captured: dict[str, object] = {} + + def fake_run(argv, *, timeout, operation): + captured.update(argv=argv, timeout=timeout, operation=operation) + return 37, "out", "err", False + + monkeypatch.setattr(manager, "_run_captured", fake_run) + result = manager.exec("alpha", ["sh", "-c", "exit 37"], timeout=12) + assert result.exit_code == 37 + assert result.stdout == "out" + assert captured["argv"][-7:] == [ + "exec", + "--cwd=/workspace", + "--user=0:0", + "alpha", + "sh", + "-c", + "exit 37", + ] + updated = json.loads((manager.config.instances_dir / "alpha" / "metadata.json").read_text()) + assert updated["last_used_at"] >= metadata["last_used_at"] + + +def test_interactive_command_uses_stdio_pty_without_unsupported_terminal_flag( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + _metadata(manager, "alpha") + monkeypatch.setattr( + manager, + "_runtime_state", + lambda *args: ({"status": "running"}, None), + ) + + command = manager.interactive_command("alpha") + + assert "--terminal" not in command + assert command[command.index("exec") :] == [ + "exec", + "--cwd=/workspace", + "--user=0:0", + "alpha", + "/bin/bash", + "--login", + ] + + +def test_cleanup_expired_only_deletes_old_temporary_sandboxes( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + now = dt.datetime(2026, 8, 4, tzinfo=dt.timezone.utc) + old = (now - dt.timedelta(days=8)).isoformat() + recent = (now - dt.timedelta(days=1)).isoformat() + items = [ + SandboxInfo("old", "stopped", "temporary", "host", old, old, None, (now - dt.timedelta(days=1)).isoformat()), + SandboxInfo("recent", "stopped", "temporary", "host", recent, recent, None, (now + dt.timedelta(days=6)).isoformat()), + SandboxInfo("permanent", "stopped", "permanent", "host", old, old, None, None), + ] + monkeypatch.setattr(manager, "list", lambda: items) + deleted: list[str] = [] + monkeypatch.setattr( + manager, + "_delete_if_expired", + lambda name, now: deleted.append(name) or True, + ) + assert manager.cleanup_expired(now=now) == ["old"] + assert deleted == ["old"] + + +def test_expiry_is_rechecked_under_the_deletion_lock( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + now = dt.datetime(2026, 8, 4, tzinfo=dt.timezone.utc) + _metadata( + manager, + "recently-used", + last_used_at=(now - dt.timedelta(days=1)).isoformat(), + ) + runtime_state = Mock() + monkeypatch.setattr(manager, "_runtime_state", runtime_state) + + assert manager._delete_if_expired("recently-used", now) is False + runtime_state.assert_not_called() + + +def test_doctor_never_requests_a_host_shell( + manager: SandboxManager, monkeypatch: pytest.MonkeyPatch +) -> None: + calls: list[dict] = [] + + def fake_run(*args, **kwargs): + calls.append(kwargs) + return subprocess.CompletedProcess(args[0], 0, "runsc version test", "") + + monkeypatch.setattr(subprocess, "run", fake_run) + manager.doctor() + assert calls and all(call.get("shell") is False for call in calls) + + +def test_docker_image_contains_sandbox_runtime_contract() -> None: + root = Path(__file__).resolve().parents[1] + dockerfile = (root / "docker" / "base" / "Dockerfile").read_text(encoding="utf-8") + packages = ( + root / "docker" / "base" / "fs" / "ins" / "install_base_packages4.sh" + ).read_text(encoding="utf-8") + compose = (root / "docker" / "run" / "docker-compose.yml").read_text( + encoding="utf-8" + ) + assert "AS sandbox-rootfs" not in dockerfile + assert "/opt/agent-zero/sandbox-rootfs" not in dockerfile + assert "FROM debian:trixie-slim AS gvisor-package" in dockerfile + assert "apt-get install -y --no-install-recommends runsc" in dockerfile + assert "https://storage.googleapis.com/gvisor/releases release main" in dockerfile + assert "COPY --from=gvisor-package /usr/bin/runsc /usr/bin/runsc" in dockerfile + assert ( + "COPY --from=gvisor-package /usr/bin/gvisor-bin/gvisor_sentry " + "/usr/bin/gvisor-bin/gvisor_sentry" + ) in dockerfile + assert "containerd-shim-runsc-v1" not in dockerfile + assert "checkpointgofer" not in dockerfile + assert "runsc-metric-server" not in dockerfile + assert "ca-certificates util-linux procps iproute2 skopeo umoci" in packages + assert "gnupg" not in packages + assert "privileged: false" in compose + assert "seccomp:unconfined" in compose diff --git a/tests/test_search_engine_tool.py b/tests/test_search_engine_tool.py index 21edee38e..9ec67211f 100644 --- a/tests/test_search_engine_tool.py +++ b/tests/test_search_engine_tool.py @@ -104,3 +104,10 @@ async def test_execute_survives_search_failure(monkeypatch): assert response.break_loop is False assert "search failed" in response.message.lower() + + +@pytest.mark.asyncio +async def test_search_reports_unfinished_sandbox_integration_without_network(): + response = await _make_tool().execute(query="test") + assert response.message == "the searxng plugin is not yet fully implemented" + assert response.break_loop is False diff --git a/tests/test_searxng_plugin.py b/tests/test_searxng_plugin.py new file mode 100644 index 000000000..ba3b2d377 --- /dev/null +++ b/tests/test_searxng_plugin.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +import asyncio +from pathlib import Path + +from plugins._searxng.helpers.searxng import NOT_IMPLEMENTED_MESSAGE, search +from plugins._searxng.tools.search_engine import SearchEngine + + +PROJECT_ROOT = Path(__file__).resolve().parents[1] + + +def test_search_engine_is_a_deterministic_placeholder() -> None: + tool = SearchEngine( + agent=None, # type: ignore[arg-type] + name="search_engine", + method=None, + args={}, + message="", + loop_data=None, + ) + + response = asyncio.run(tool.execute(query="latest news", unexpected="ignored")) + + assert response.message == "the searxng plugin is not yet fully implemented" + assert response.message == NOT_IMPLEMENTED_MESSAGE + assert response.break_loop is False + assert asyncio.run(search("anything")) == NOT_IMPLEMENTED_MESSAGE + + +def test_searxng_assets_are_plugin_owned() -> None: + expected = [ + "plugins/_searxng/plugin.yaml", + "plugins/_searxng/README.md", + "plugins/_searxng/helpers/searxng.py", + "plugins/_searxng/tools/search_engine.py", + "plugins/_searxng/prompts/agent.system.tool.search_engine.md", + ] + removed_core = [ + "helpers/searxng.py", + "helpers/searxng.py.dox.md", + "tools/search_engine.py", + "tools/search_engine.py.dox.md", + "tools/knowledge_tool._py", + "prompts/agent.system.tool.search_engine.md", + ] + + for relative_path in expected: + assert (PROJECT_ROOT / relative_path).is_file(), relative_path + for relative_path in removed_core: + assert not (PROJECT_ROOT / relative_path).exists(), relative_path + + +def test_outer_docker_images_have_no_searxng_runtime() -> None: + removed_paths = [ + "docker/base/fs/ins/install_searxng.sh", + "docker/base/fs/ins/install_searxng2.sh", + "docker/base/fs/etc/searxng/settings.yml", + "docker/base/fs/etc/searxng/limiter.toml", + "docker/run/fs/exe/run_searxng.sh", + "docker/run/fs/etc/searxng/settings.yml", + "docker/run/fs/etc/searxng/limiter.toml", + ] + for relative_path in removed_paths: + assert not (PROJECT_ROOT / relative_path).exists(), relative_path + + docker_files = [ + path + for root in ( + PROJECT_ROOT / "docker" / "base", + PROJECT_ROOT / "docker" / "run", + ) + for path in root.rglob("*") + if path.is_file() and "__pycache__" not in path.parts + ] + docker_files.append(PROJECT_ROOT / "DockerfileLocal") + combined = "\n".join( + path.read_text(encoding="utf-8", errors="ignore") for path in docker_files + ) + + forbidden = [ + "install_searxng", + "run_searxng", + "SEARXNG_SETTINGS_PATH", + "/etc/searxng", + "/usr/local/searxng", + "searx-pyenv", + "[program:run_searxng]", + ] + for marker in forbidden: + assert marker not in combined, marker + + +def test_readme_preserves_reimplementation_details() -> None: + readme = (PROJECT_ROOT / "plugins/_searxng/README.md").read_text(encoding="utf-8") + + for detail in ( + "git`, `build-essential`, `libxslt-dev`, `zlib1g-dev`, `libffi-dev`, and `libssl-dev", + "git clone https://github.com/searxng/searxng", + "python3.13 -m venv /usr/local/searxng/searx-pyenv", + "pip install --no-cache-dir -U pip setuptools wheel pyyaml lxml msgspec typing_extensions", + "pip install --no-cache-dir --use-pep517 --no-build-isolation .", + "http://localhost:55510/search", + "SEARXNG_SETTINGS_PATH=/etc/searxng/settings.yml", + 'secret_key: "dummy"', + "safe_search: 0", + "radio browser", + "wikidata", + "trusted_proxies = [\"127.0.0.1\"]", + ): + assert detail in readme, detail diff --git a/tests/test_self_update_runtime_sync.py b/tests/test_self_update_runtime_sync.py index 0d21cb381..c920ad320 100644 --- a/tests/test_self_update_runtime_sync.py +++ b/tests/test_self_update_runtime_sync.py @@ -135,7 +135,12 @@ def test_self_update_runtime_sync_starts_codex_refresh(monkeypatch, tmp_path): ) assert migration.start_codex_cli_refresh(manager_path) == "" - assert calls[0][0][0] == [sys.executable, str(manager_path), "refresh-codex"] + assert calls[0][0][0] == [ + "depfix", + "run", + str(manager_path), + "refresh-codex", + ] assert calls[0][1]["start_new_session"] is True diff --git a/tests/test_self_update_tag_filter.py b/tests/test_self_update_tag_filter.py index fe43e8274..41afc04d0 100644 --- a/tests/test_self_update_tag_filter.py +++ b/tests/test_self_update_tag_filter.py @@ -1119,7 +1119,6 @@ def test_self_update_manager_desktop_ssh_cleanup_failure_does_not_block_startup( "load_request_file", lambda: (request_data, "branch: main\ntag: v1.2\n"), ) - monkeypatch.setattr(manager, "clean_uv_cache", lambda logger: None) monkeypatch.setattr( manager, "clean_transient_desktop_agent_state", @@ -1141,72 +1140,6 @@ def test_self_update_manager_desktop_ssh_cleanup_failure_does_not_block_startup( ).read_text(encoding="utf-8") -def test_self_update_manager_clean_uv_cache_uses_uv_when_available(monkeypatch): - manager = load_self_update_manager() - commands = [] - monkeypatch.setattr( - manager.shutil, - "which", - lambda executable: "/usr/local/bin/uv" if executable == "uv" else None, - ) - - def fake_run_command(command, *, cwd, logger, error_message=None): - commands.append((command, cwd, error_message)) - - monkeypatch.setattr(manager, "run_command", fake_run_command) - - manager.clean_uv_cache(manager.NullLogger()) - - assert commands == [ - ( - ["/usr/local/bin/uv", "cache", "clean"], - None, - "Failed to clean uv cache during self-update.", - ) - ] - - -def test_self_update_manager_clean_uv_cache_skips_when_uv_missing(monkeypatch): - manager = load_self_update_manager() - commands = [] - monkeypatch.setattr(manager.shutil, "which", lambda executable: None) - monkeypatch.setattr( - manager, - "run_command", - lambda command, **kwargs: commands.append(command), - ) - - manager.clean_uv_cache(manager.NullLogger()) - - assert commands == [] - - -def test_self_update_manager_clean_uv_cache_is_best_effort(monkeypatch): - manager = load_self_update_manager() - messages = [] - monkeypatch.setattr( - manager.shutil, - "which", - lambda executable: "/usr/local/bin/uv" if executable == "uv" else None, - ) - - class Logger: - def log(self, message=""): - messages.append(message) - - def log_block(self, title, content): - return None - - def fail_run_command(command, **kwargs): - raise RuntimeError("cache cleanup failed") - - monkeypatch.setattr(manager, "run_command", fail_run_command) - - manager.clean_uv_cache(Logger()) - - assert any("uv cache clean skipped after error" in message for message in messages) - - def test_self_update_manager_refreshes_installed_codex_best_effort(monkeypatch): manager = load_self_update_manager() commands = [] diff --git a/tests/test_whisper_pcm_contract.py b/tests/test_whisper_pcm_contract.py new file mode 100644 index 000000000..29b2f52ca --- /dev/null +++ b/tests/test_whisper_pcm_contract.py @@ -0,0 +1,425 @@ +# ruff: noqa: E501 - Embedded JavaScript remains readable as executable browser code. + +from __future__ import annotations + +import asyncio +import base64 +import shutil +import subprocess +from pathlib import Path + +import numpy as np +import pytest +from flask import Response + +from plugins._whisper_stt.api.transcribe import Transcribe +from plugins._whisper_stt.helpers import runtime + +PROJECT_ROOT = Path(__file__).resolve().parents[1] + + +def pcm_payload( + samples: np.ndarray, + **overrides: object, +) -> dict[str, object]: + values: dict[str, object] = { + "version": 1, + "sample_rate": 16_000, + "channels": 1, + "sample_format": "f32le", + "frame_count": int(samples.size), + "data": base64.b64encode(samples.astype(" None: + expected = np.array([-1.0, -0.25, 0.0, 0.5, 1.0], dtype=np.float32) + + actual = runtime.decode_audio_payload(pcm_payload(expected)) + + assert actual.dtype == np.float32 + assert actual.flags.c_contiguous + assert actual.flags.writeable + np.testing.assert_array_equal(actual, expected) + + +@pytest.mark.parametrize( + ("overrides", "message"), + [ + ({"version": 2}, "version"), + ({"sample_rate": 8_000}, "sample rate"), + ({"channels": 2}, "channel count"), + ({"sample_format": "s16le"}, "sample format"), + ({"frame_count": True}, "integer"), + ({"frame_count": 0}, "empty"), + ({"frame_count": runtime.AUDIO_MAX_FRAMES + 1}, "120 seconds"), + ({"frame_count": 2}, "length"), + ({"data": "not base64!"}, "base64"), + ], +) +def test_pcm_v1_rejects_malformed_metadata_and_data( + overrides: dict[str, object], message: str +) -> None: + with pytest.raises(runtime.AudioPayloadError, match=message): + runtime.decode_audio_payload( + pcm_payload(np.array([0.25], dtype=np.float32), **overrides) + ) + + +@pytest.mark.parametrize("sample", [np.nan, np.inf, -np.inf, 1.01, -1.01]) +def test_pcm_v1_rejects_non_finite_or_unnormalized_samples(sample: float) -> None: + with pytest.raises(runtime.AudioPayloadError): + runtime.decode_audio_payload(pcm_payload(np.array([sample], dtype=np.float32))) + + +def test_pcm_v1_rejects_oversized_encoded_data_before_decoding( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(runtime, "AUDIO_MAX_BASE64_CHARS", 4) + + with pytest.raises(runtime.AudioPayloadError, match="byte limit"): + runtime.decode_audio_payload(pcm_payload(np.array([0.25], dtype=np.float32))) + + +def test_invalid_pcm_is_rejected_before_model_preload( + monkeypatch: pytest.MonkeyPatch, +) -> None: + preloaded = False + + async def fake_preload(_model_name: str) -> None: + nonlocal preloaded + preloaded = True + + monkeypatch.setattr(runtime, "_preload", fake_preload) + with pytest.raises(runtime.AudioPayloadError): + asyncio.run(runtime.transcribe({"version": 99}, {"model_size": "base"})) + + assert preloaded is False + + +def test_transcribe_api_returns_400_for_invalid_pcm( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def reject_audio(_audio: object) -> dict[str, object]: + raise runtime.AudioPayloadError("Unsupported audio payload version") + + monkeypatch.setattr(runtime, "is_globally_enabled", lambda: True) + monkeypatch.setattr(runtime, "transcribe", reject_audio) + handler = object.__new__(Transcribe) + + response = asyncio.run(handler.process({"audio": {"version": 99}}, None)) + + assert isinstance(response, Response) + assert response.status_code == 400 + assert response.get_data(as_text=True) == "Unsupported audio payload version" + + +def test_whisper_receives_samples_without_filename_or_subprocess( + monkeypatch: pytest.MonkeyPatch, +) -> None: + expected = np.array([0.0, 0.25, -0.25], dtype=np.float32) + received: dict[str, object] = {} + + async def fake_preload(_model_name: str) -> None: + return None + + class FakeModel: + def transcribe(self, audio: np.ndarray, **kwargs: object) -> dict[str, str]: + received["audio"] = audio + received["kwargs"] = kwargs + return {"text": "hello", "language": "en"} + + def reject_subprocess(*_args: object, **_kwargs: object) -> None: + raise AssertionError("PCM transcription must not launch a subprocess") + + monkeypatch.setattr(runtime, "_preload", fake_preload) + monkeypatch.setattr(runtime, "_model", FakeModel()) + monkeypatch.setattr(subprocess, "Popen", reject_subprocess) + + result = asyncio.run( + runtime.transcribe(pcm_payload(expected), {"language": "auto"}) + ) + + assert result["text"] == "hello" + assert isinstance(received["audio"], np.ndarray) + np.testing.assert_array_equal(received["audio"], expected) + assert received["kwargs"] == {"fp16": False} + + +def test_browser_pcm_helpers_mix_resample_and_encode_little_endian( + tmp_path: Path, +) -> None: + if not shutil.which("node"): + pytest.skip("Node.js is required for browser PCM helper verification") + + source = PROJECT_ROOT / "plugins/_whisper_stt/webui/audio-pcm.js" + module = tmp_path / "audio-pcm.mjs" + module.write_text(source.read_text(encoding="utf-8"), encoding="utf-8") + script = f""" +import {{ mixAudioChannels, resampleMonoPcm, concatenatePcmChunks, encodePcmPayload }} from {module.as_uri()!r}; +const assert = (condition, message) => {{ if (!condition) throw new Error(message); }}; +const mono = mixAudioChannels([new Float32Array([1, -1]), new Float32Array([-1, 1])]); +assert(mono.length === 2 && mono[0] === 0 && mono[1] === 0, "channel mixing"); +const down = resampleMonoPcm(new Float32Array([1, 1, -1, -1]), 32000, 16000); +assert(down.length === 2 && down[0] === 1 && down[1] === -1, "downsampling"); +const joined = concatenatePcmChunks([new Float32Array([0.5]), new Float32Array([-0.5])], 2); +const payload = encodePcmPayload(joined); +assert(payload.version === 1 && payload.sample_rate === 16000, "wire metadata"); +assert(payload.channels === 1 && payload.sample_format === "f32le" && payload.frame_count === 2, "wire shape"); +const bytes = Uint8Array.from(atob(payload.data), (character) => character.charCodeAt(0)); +const view = new DataView(bytes.buffer); +assert(view.getFloat32(0, true) === 0.5 && view.getFloat32(4, true) === -0.5, "little-endian samples"); +""" + subprocess.run(["node", "--input-type=module", "-e", script], check=True) + + +def test_audio_worklet_mixes_channels_and_enforces_capture_limit( + tmp_path: Path, +) -> None: + if not shutil.which("node"): + pytest.skip("Node.js is required for AudioWorklet verification") + + source_root = PROJECT_ROOT / "plugins/_whisper_stt/webui" + helper = tmp_path / "audio-pcm.mjs" + processor = tmp_path / "pcm-capture-processor.mjs" + helper.write_text( + (source_root / "audio-pcm.js").read_text(encoding="utf-8"), + encoding="utf-8", + ) + processor.write_text( + (source_root / "pcm-capture-processor.js") + .read_text(encoding="utf-8") + .replace('"./audio-pcm.js"', '"./audio-pcm.mjs"'), + encoding="utf-8", + ) + script = f""" +const assert = (condition, message) => {{ if (!condition) throw new Error(message); }}; +let Processor; +globalThis.sampleRate = 48000; +globalThis.AudioWorkletProcessor = class {{ + constructor() {{ + this.port = {{ + messages: [], + onmessage: null, + postMessage: (message) => this.port.messages.push(message), + }}; + }} +}}; +globalThis.registerProcessor = (_name, implementation) => {{ Processor = implementation; }}; +await import({processor.as_uri()!r}); +const capture = new Processor({{ processorOptions: {{ maxFrames: 2 }} }}); +capture.port.onmessage({{ data: {{ type: "start", recordingId: 7 }} }}); +assert(capture.process([[new Float32Array([1, -1]), new Float32Array([-1, 1])]]), "process"); +const chunk = capture.port.messages.find((message) => message.type === "chunk"); +const samples = new Float32Array(chunk.samples); +assert(samples.length === 2 && samples[0] === 0 && samples[1] === 0, "mixed chunk"); +assert(capture.port.messages.some((message) => message.type === "overflow"), "overflow"); +capture.port.onmessage({{ data: {{ type: "stop", recordingId: 7 }} }}); +assert(capture.port.messages.some((message) => message.type === "stopped"), "stopped"); +""" + subprocess.run(["node", "--input-type=module", "-e", script], check=True) + + +def test_microphone_pipeline_behavior(tmp_path: Path) -> None: + if not shutil.which("node"): + pytest.skip("Node.js is required for microphone lifecycle verification") + + source_root = PROJECT_ROOT / "plugins/_whisper_stt/webui" + helper = tmp_path / "audio-pcm.mjs" + store_module = tmp_path / "whisper-stt-store.mjs" + helper.write_text( + (source_root / "audio-pcm.js").read_text(encoding="utf-8"), + encoding="utf-8", + ) + store_source = (source_root / "whisper-stt-store.js").read_text(encoding="utf-8") + replacements = { + 'import { createStore } from "/js/AlpineStore.js";': "const createStore = (_name, value) => value;", + 'import { toastFrontendError } from "/components/notifications/notification-store.js";': "const toastFrontendError = async (...args) => globalThis.__frontendErrors.push(args);", + 'import { callJsonApi } from "/js/api.js";': "const callJsonApi = (...args) => globalThis.__callJsonApi(...args);", + 'import { sttService } from "/js/stt-service.js";': "const sttService = globalThis.__sttService;", + 'import { ttsService } from "/js/tts-service.js";': "const ttsService = globalThis.__ttsService;", + 'import { sendMessage, updateChatInput } from "/index.js";': "const sendMessage = async () => { globalThis.__sent += 1; };\n" + "const updateChatInput = (text) => { globalThis.__draft = text; };", + 'from "./audio-pcm.js";': 'from "./audio-pcm.mjs";', + } + for old, new in replacements.items(): + assert old in store_source + store_source = store_source.replace(old, new) + store_module.write_text(store_source, encoding="utf-8") + + script = f""" +const assert = (condition, message) => {{ if (!condition) throw new Error(message); }}; +const flush = async () => {{ await Promise.resolve(); await Promise.resolve(); }}; +globalThis.__frontendErrors = []; +globalThis.__sent = 0; +globalThis.__draft = ""; +globalThis.__apiCalls = []; +globalThis.__callJsonApi = async (url, body) => {{ + globalThis.__apiCalls.push({{ url, body }}); + return {{ text: "transcribed speech", language: "en" }}; +}}; +globalThis.__sttService = {{ + emitStatusChange: () => {{}}, + registerProvider: () => () => {{}}, +}}; +globalThis.__ttsService = {{ + addEventListener: () => {{}}, + isSpeaking: () => false, + stop: () => {{}}, +}}; +globalThis.localStorage = {{ getItem: () => "", setItem: () => {{}} }}; +globalThis.document = {{ getElementById: () => null }}; +globalThis.window = globalThis; +globalThis.window.toastFetchError = (...args) => globalThis.__transcriptionErrors.push(args); +globalThis.__transcriptionErrors = []; +globalThis.__toasts = []; +globalThis.toast = (...args) => globalThis.__toasts.push(args); +globalThis.__logs = []; +console.log = (...args) => globalThis.__logs.push(args.join(" ")); +globalThis.DOMException = globalThis.DOMException || class extends Error {{ + constructor(message, name) {{ super(message); this.name = name; }} +}}; +let animationCallback = null; +globalThis.requestAnimationFrame = (callback) => {{ animationCallback = callback; return 1; }}; +globalThis.cancelAnimationFrame = () => {{ animationCallback = null; }}; + +const tracks = [{{ stopped: false, stop() {{ this.stopped = true; }} }}]; +const stream = {{ getTracks: () => tracks }}; +const analyser = {{ + fftSize: 4, + connect: () => {{}}, + disconnect: () => {{}}, + values: [128, 128, 128, 128], + getByteTimeDomainData(target) {{ target.fill(this.values[0]); }}, +}}; +class FakePort {{ + constructor() {{ this.messages = []; this.onmessage = null; }} + postMessage(message) {{ this.messages.push(message); }} +}} +class FakeAudioWorkletNode {{ + constructor() {{ this.port = new FakePort(); this.disconnected = false; }} + connect() {{}} + disconnect() {{ this.disconnected = true; }} +}} +globalThis.AudioWorkletNode = FakeAudioWorkletNode; +class FakeAudioContext {{ + constructor() {{ + this.sampleRate = 48000; + this.destination = {{}}; + this.audioWorklet = {{ addModule: async () => {{}} }}; + this.closed = false; + }} + createMediaStreamSource() {{ return {{ connect: () => {{}}, disconnect: () => {{}} }}; }} + createAnalyser() {{ return analyser; }} + createGain() {{ return {{ gain: {{ value: 1 }}, connect: () => {{}}, disconnect: () => {{}} }}; }} + close() {{ this.closed = true; }} +}} +globalThis.AudioContext = FakeAudioContext; +Object.defineProperty(globalThis, "navigator", {{ configurable: true, value: {{ + mediaDevices: {{ + getUserMedia: async (constraints) => {{ globalThis.__constraints = constraints; return stream; }}, + enumerateDevices: async () => [ + {{ kind: "audioinput", deviceId: "default", label: "Default" }}, + {{ kind: "audioinput", deviceId: "usb", label: "USB mic" }}, + ], + addEventListener: () => {{}}, + }}, +}} }}); + +const {{ MicrophoneInput, Status, model }} = await import({store_module.as_uri()!r}); +const owner = {{ + config: {{ silence_threshold: 0.3, silence_duration: 10, waiting_timeout: 20 }}, + getSelectedDevice: () => ({{ deviceId: "usb" }}), + notifyStatusChange: () => {{}}, + requestMicrophonePermission: async () => true, + stop: () => {{}}, +}}; +const delivered = []; +const input = new MicrophoneInput(owner, async (text, final) => delivered.push([text, final])); +assert(await input.initialize(), "initialization"); +assert(input.selectedDeviceId === "usb", "selected device"); +assert(globalThis.__constraints.audio.deviceId.exact === "usb", "device constraint"); + +input.status = Status.LISTENING; +analyser.values = [255, 255, 255, 255]; +animationCallback(); +assert(input.status === Status.RECORDING, "speech starts recording"); +assert(input.captureNode.port.messages.at(-1).type === "start", "capture start"); +input.handleCaptureMessage({{ data: {{ + type: "chunk", recordingId: input.recordingId, + samples: new Float32Array([0.25, -0.25]).buffer, +}} }}); +analyser.values = [128, 128, 128, 128]; +const originalNow = Date.now; +let now = 100; +Date.now = () => now; +animationCallback(); +assert(input.status === Status.RECORDING, "initial silence keeps recording"); +input.silenceStartTime = now; +now = 111; +animationCallback(); +assert(input.status === Status.WAITING, "silence enters waiting"); +input.status = Status.PROCESSING; +input.handleCaptureMessage({{ data: {{ type: "stopped", recordingId: input.recordingId }} }}); +await flush(); +assert(globalThis.__apiCalls.length === 1, "transcription request"); +assert(globalThis.__apiCalls[0].body.audio.sample_rate === 16000, "resampled payload"); +assert(delivered.length === 1 && delivered[0][0] === "transcribed speech", "final delivery"); +assert(input.status === Status.LISTENING, "returns to listening"); + +input.status = Status.RECORDING; +assert(input.recordingId === 2, "repeated recording gets a fresh id"); +const cancellation = input.process(); +const context = input.audioContext; +input.dispose(); +await cancellation; +assert(context.closed && tracks[0].stopped, "teardown closes context and stream"); +assert(globalThis.__apiCalls.length === 1, "cancelled recording is not submitted"); +input.filterResult("[private transcript]"); +assert(!globalThis.__logs.some((line) => line.includes("private transcript")), "transcription privacy"); +Date.now = originalNow; + +const unsupported = new MicrophoneInput(owner, async () => {{}}); +globalThis.AudioWorkletNode = undefined; +assert(!(await unsupported.initialize()), "unsupported browser rejected"); +assert(globalThis.__toasts.at(-1)[0].includes("does not support"), "unsupported browser message"); + +globalThis.AudioWorkletNode = FakeAudioWorkletNode; +globalThis.navigator.mediaDevices.getUserMedia = async () => {{ throw new Error("denied"); }}; +const denied = new MicrophoneInput(owner, async () => {{}}); +assert(!(await denied.initialize()), "permission failure rejected"); +assert(globalThis.__toasts.at(-1)[0].includes("check browser permissions"), "permission message"); + +model.config.message_mode = "draft"; +model.microphoneInput = {{ messageSent: false }}; +model.stop = () => {{ globalThis.__draftStopped = true; }}; +await model.sendVoiceMessage(" draft text "); +assert(globalThis.__draft === "draft text" && globalThis.__sent === 0, "draft mode"); +model.config.message_mode = "send"; +model.microphoneInput = {{ messageSent: false }}; +await model.sendVoiceMessage("send text"); +assert(globalThis.__sent === 1 && model.microphoneInput.messageSent, "send mode"); + +model.devices = [{{ kind: "audioinput", deviceId: "usb" }}]; +model.microphoneInput = {{ selectedDeviceId: "old" }}; +model.stop = () => {{ globalThis.__deviceStopped = true; }}; +await model.selectDevice("usb"); +assert(model.selectedDevice === "usb" && globalThis.__deviceStopped, "device switch teardown"); + +globalThis.__callJsonApi = async () => {{ throw new Error("transcribe failed"); }}; +const failed = new MicrophoneInput(owner, async () => {{}}); +failed.audioContext = {{ sampleRate: 16000 }}; +failed.captureNode = new FakeAudioWorkletNode(); +failed.hasStartedRecording = true; +failed.recordingId = 9; +failed._status = Status.PROCESSING; +failed.pcmChunks = [new Float32Array([0.1])]; +failed.pcmFrameCount = 1; +const failure = failed.process(); +failed.handleCaptureMessage({{ data: {{ type: "stopped", recordingId: 9 }} }}); +await failure; +assert(globalThis.__transcriptionErrors.length === 1, "transcription error reported"); +""" + subprocess.run(["node", "--input-type=module", "-e", script], check=True) diff --git a/tools/knowledge_tool._py b/tools/knowledge_tool._py deleted file mode 100644 index 8999be71f..000000000 --- a/tools/knowledge_tool._py +++ /dev/null @@ -1,266 +0,0 @@ -import asyncio -from helpers import dotenv, perplexity_search, duckduckgo_search -from plugins._memory.helpers.memory import Memory -from plugins._memory.tools.memory import DEFAULT_THRESHOLD as DEFAULT_MEMORY_THRESHOLD - -from helpers.tool import Tool, Response -from plugins._document_query.helpers.document_query import DocumentQueryHelper - -SEARCH_ENGINE_RESULTS = 10 - - -class Knowledge(Tool): - async def execute(self, question="", **kwargs): - if not question: - question = kwargs.get("query", "") - if not question: - return Response(message="No question provided", break_loop=False) - - # Create tasks for all search methods - tasks = [ - self.searxng_search(question), - # self.perplexity_search(question), - # self.duckduckgo_search(question), - self.mem_search_enhanced(question), - ] - - # Run all tasks concurrently - results = await asyncio.gather(*tasks, return_exceptions=True) - - # perplexity_result, duckduckgo_result, memory_result = results - searxng_result, memory_result = results - - # enrich results with qa - searxng_result = await self.searxng_document_qa(searxng_result, question) - - # Handle exceptions and format results - searxng_result = self.format_result_searxng(searxng_result, "Search Engine") - memory_result = self.format_result(memory_result, "Memory") - - msg = self.agent.read_prompt( - "fw.knowledge_tool.response.md", - # online_sources = ((perplexity_result + "\n\n") if perplexity_result else "") + str(duckduckgo_result), - online_sources=((searxng_result + "\n\n") if searxng_result else ""), - memory=memory_result, - ) - - await self.agent.handle_intervention( - msg - ) # wait for intervention and handle it, if paused - - return Response(message=msg, break_loop=False) - - async def perplexity_search(self, question): - if dotenv.get_dotenv_value("API_KEY_PERPLEXITY"): - return await asyncio.to_thread( - perplexity_search.perplexity_search, question - ) - else: - PrintStyle.hint( - "No API key provided for Perplexity. Skipping Perplexity search." - ) - self.agent.context.log.log( - type="hint", - content="No API key provided for Perplexity. Skipping Perplexity search.", - ) - return None - - async def duckduckgo_search(self, question): - return await asyncio.to_thread(duckduckgo_search.search, question) - - async def searxng_search(self, question): - return await searxng(question) - - async def searxng_document_qa(self, result, query): - if isinstance(result, Exception) or not query or not result or not result["results"]: - return result - - result["results"] = result["results"][:SEARCH_ENGINE_RESULTS] - - tasks = [] - helper = DocumentQueryHelper(self.agent) - - for index, item in enumerate(result["results"]): - tasks.append(helper.document_qa(item["url"], [query])) - - task_results = list(await asyncio.gather(*tasks, return_exceptions=True)) - - for index, item in enumerate(result["results"]): - if isinstance(task_results[index], BaseException): - continue - found, qa = task_results[index] # type: ignore - if not found: - continue - result["results"][index]["qa"] = qa - - return result - - async def mem_search(self, question: str): - db = await Memory.get(self.agent) - docs = await db.search_similarity_threshold( - query=question, limit=5, threshold=DEFAULT_MEMORY_THRESHOLD - ) - text = Memory.format_docs_plain(docs) - return "\n\n".join(text) - - async def mem_search_enhanced(self, question: str): - """ - Enhanced memory search with knowledge source awareness. - Separates and prioritizes knowledge sources vs conversation memories. - """ - try: - db = await Memory.get(self.agent) - - # Search for knowledge sources (knowledge_source=True) - knowledge_docs = await db.search_similarity_threshold( - query=question, limit=5, threshold=DEFAULT_MEMORY_THRESHOLD, - filter="knowledge_source == True" - ) - - # Search for conversation memories (field doesn't exist or is not True) - conversation_docs = await db.search_similarity_threshold( - query=question, limit=5, threshold=DEFAULT_MEMORY_THRESHOLD, - filter="not knowledge_source if 'knowledge_source' in locals() else True" - ) - - # Combine and fallback to lower threshold if needed - all_docs = knowledge_docs + conversation_docs - threshold_note = "" - - # If no results with default threshold, try with lower threshold - if not all_docs: - lower_threshold = DEFAULT_MEMORY_THRESHOLD * 0.8 - knowledge_docs = await db.search_similarity_threshold( - query=question, limit=5, threshold=lower_threshold, - filter="knowledge_source == True" - ) - conversation_docs = await db.search_similarity_threshold( - query=question, limit=5, threshold=lower_threshold, - filter="not knowledge_source if 'knowledge_source' in locals() else True" - ) - all_docs = knowledge_docs + conversation_docs - if all_docs: - threshold_note = f" (threshold: {lower_threshold})" - - if not all_docs: - return await self._get_memory_diagnostics(db, question) - - # Separate knowledge sources from conversation memories - knowledge_sources = knowledge_docs - conversation_memories = conversation_docs - result_parts = [] - - # Add search summary - result_parts.append(f"## 🔍 Search Results for: '{question}'") - result_parts.append(f"**Found:** {len(knowledge_sources)} knowledge sources, {len(conversation_memories)} conversation memories{threshold_note}") - - # Show knowledge sources - if knowledge_sources: - result_parts.append("") - result_parts.append("## 📚 Knowledge Sources:") - for index, doc in enumerate(knowledge_sources): - source_file = doc.metadata.get('source_file', 'Unknown source') - file_type = doc.metadata.get('file_type', '').upper() - area = doc.metadata.get('area', 'main').upper() - - result_parts.append(f"**Source:** {source_file} ({file_type}) [{area}]") - result_parts.append(f"**Content:** {doc.page_content}") - if index < len(knowledge_sources) - 1: - result_parts.append("-" * 80) - - # Show conversation memories - if conversation_memories: - if knowledge_sources: - result_parts.append("") - result_parts.append("## 💭 Related Experience:") - for index, doc in enumerate(conversation_memories): - timestamp = doc.metadata.get('timestamp', 'Unknown time') - area = doc.metadata.get('area', 'main').upper() - consolidation_action = doc.metadata.get('consolidation_action', '') - - metadata_info = f"{timestamp} [{area}]" - if consolidation_action: - metadata_info += f" (consolidated: {consolidation_action})" - - result_parts.append(f"**Experience:** {metadata_info}") - result_parts.append(f"**Content:** {doc.page_content}") - if index < len(conversation_memories) - 1: - result_parts.append("-" * 80) - - return "\n".join(result_parts) - - except Exception as e: - handle_error(e) - return f"Memory search failed: {str(e)}" - - async def _get_memory_diagnostics(self, db, query: str): - """Provide memory diagnostics when no search results are found.""" - try: - # Get sample of all documents to see what's in memory - sample_docs = await db.search_similarity_threshold( - query="test", limit=20, threshold=0.0 - ) - - if not sample_docs: - return f"## 🔍 No Results for: '{query}'\n**Memory database appears to be empty.**" - - # Analyze what's in memory - area_counts: dict[str, int] = {} - knowledge_count = 0 - - for doc in sample_docs: - area = doc.metadata.get('area', 'unknown') - area_counts[area] = area_counts.get(area, 0) + 1 - if doc.metadata.get('knowledge_source', False): - knowledge_count += 1 - - result_parts = [ - f"## 🔍 No Results for: '{query}'", - f"**Database contains:** {len(sample_docs)} total documents", - f"**Areas:** {', '.join([f'{area.upper()}: {count}' for area, count in area_counts.items()])}", - f"**Knowledge sources:** {knowledge_count} documents", - "", - "**Suggestions:**", - "- Try different or more general search terms", - "- Check if the information was recently memorized", - f"- Current search threshold: {DEFAULT_MEMORY_THRESHOLD}" - ] - - return "\n".join(result_parts) - - except Exception as e: - return f"Memory diagnostics failed: {str(e)}" - - def format_result(self, result, source): - if isinstance(result, Exception): - handle_error(result) - return f"{source} search failed: {str(result)}" - return result if result else "" - - def format_result_searxng(self, result, source): - if isinstance(result, Exception): - handle_error(result) - return f"{source} search failed: {str(result)}" - - if not result or "results" not in result: - return "" - - outputs = [] - for item in result["results"]: - if "qa" in item: - outputs.append( - f"## Next Result\n" - f"*Title*: {item['title'].strip()}\n" - f"*URL*: {item['url'].strip()}\n" - f"*Search Engine Summary*:\n{item['content'].strip()}\n" - f"*Query Result*:\n{item['qa'].strip()}" - ) - else: - outputs.append( - f"## Next Result\n" - f"*Title*: {item['title'].strip()}\n" - f"*URL*: {item['url'].strip()}\n" - f"*Search Engine Summary*:\n{item['content'].strip()}" - ) - - return "\n\n".join(outputs[:SEARCH_ENGINE_RESULTS]).strip()