mirror of
https://github.com/agent0ai/agent-zero.git
synced 2026-12-04 03:58:09 +00:00
Move optional runtimes into persistent gVisor plugin sandboxes
Move tunnel, browser, document, speech and integration runtimes into plugin-owned sandboxes with lazy dependencies and instance-scoped lifecycle management. Reuse Tuxee display assets and the sandbox image's Python/Node runtimes, enable automatic Desktop login, and show elapsed time for each browser launch. Slim the outer image, use offline ONNX embeddings, and calculate sandbox storage only on demand. Include regression coverage and updated runtime documentation. Exclude local handoff notes and temporary verification artifacts from publication.
This commit is contained in:
1 parent
1ee5dcbb61
commit
188cff2073
505 files changed
+32613
-27776
No files matched your search
@@ -14,6 +14,7 @@
|
||||
## Local Contracts
|
||||
|
||||
- Docker publishing lives in `workflows/docker-publish.yml` and delegates planning to `scripts/docker_release_plan.py`.
|
||||
- `docker/run/Dockerfile` builds and bundles the default sandbox OCI image for each target architecture; it requires no separate sandbox registry publication or workflow build context.
|
||||
- Releasable tags are `vX.Y` tags at or above `v1.0`, matching the workflow environment.
|
||||
- On `main`, the newest eligible tag publishes both the version tag and `latest`, then creates or updates its GitHub release after the image push succeeds; other allowed branches publish only their branch tag.
|
||||
- Manual dispatch without a tag backfills missing Docker Hub tags. Manual dispatch with a tag rebuilds that target and refreshes `latest` and the GitHub release only when it remains the newest eligible tag on `main`.
|
||||
|
||||
@@ -171,6 +171,7 @@ jobs:
|
||||
if: steps.resolve.outputs.should_build == 'true'
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
# docker/run/Dockerfile bundles the sandbox OCI image for each platform.
|
||||
context: ${{ env.DOCKERFILE_DIR }}
|
||||
file: ${{ env.DOCKERFILE_PATH }}
|
||||
platforms: ${{ env.DOCKER_PLATFORMS }}
|
||||
|
||||
+5
-4
@@ -22,10 +22,7 @@
|
||||
/instruments/
|
||||
/logs/
|
||||
|
||||
# Handle tmp and usr directory
|
||||
tmp/**
|
||||
!tmp/**/
|
||||
|
||||
# Handle usr directory
|
||||
# hack to keep .gitkeep but ignore nested repos
|
||||
# Ignore everything under usr
|
||||
usr/**
|
||||
@@ -48,3 +45,7 @@ agent_history.gif
|
||||
.agent/**
|
||||
.claude/**
|
||||
.playwright-cli/
|
||||
|
||||
# Ignore runtime scratch data, including nested directory markers.
|
||||
/tmp/**
|
||||
!/tmp/.gitkeep
|
||||
@@ -8,7 +8,7 @@
|
||||
## Project
|
||||
|
||||
- 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.
|
||||
- Start the WebUI with `PYTHONDONTWRITEBYTECODE=1 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/`.
|
||||
|
||||
@@ -22,13 +22,15 @@
|
||||
- Native function calls use canonical call content for history and combine public response text with calls for repeat comparison. The canonical history content passes through the normal history template/masking hook; provider output metadata remains intact.
|
||||
- `initialize.py` owns framework initialization.
|
||||
- `models.py` owns model-provider configuration and LiteLLM integration. `get_api_key_raw()` reads the stored key or key list for settings/editing; `get_api_key()` selects a runtime key and runs provider extension hooks.
|
||||
- Local sentence-transformers load only on an embedding cache miss, not when importing `models`. `run_ui.init_a0` starts deferred preload before chat restoration and returns a completion callback so its end hooks (including watchdog registration) overlap warmup. `run` invokes that callback, allowing up to ten additional seconds for preload before starting MCP and the job loop, then HTTP. Chat restoration and extension hooks are outside this wait limit. Timeout leaves preload running, so a first chat can still wait for an uncached model. Waiting is best-effort: timeout or task failure does not prevent HTTP startup. Initialization hooks may disable preload or suppress completion; disabled preload still allows MCP/jobs, while a skipped initializer skips them. `preload.py` constructs the configured local embedding model in a worker thread; it must not import unused speech runtimes or block the shared background event loop.
|
||||
- Local ONNX embeddings load only on an embedding cache miss, not when importing `models`. `run_ui.init_a0` starts deferred preload before chat restoration and returns a completion callback so its end hooks (including watchdog registration) overlap warmup. `run` invokes that callback, allowing up to ten additional seconds for preload before starting MCP and the job loop, then HTTP. Chat restoration and extension hooks are outside this wait limit. Timeout leaves preload running, so a first chat can still wait for an uncached model. Waiting is best-effort: timeout or task failure does not prevent HTTP startup. Initialization hooks may disable preload or suppress completion; disabled preload still allows MCP/jobs, while a skipped initializer skips them. `preload.py` constructs the configured local embedding model in a worker thread; it must not import unused speech runtimes or block the shared background event loop.
|
||||
- `models._merge_provider_defaults` merges YAML-declared `extra_body` defaults with legacy top-level values for those declared fields and explicit nested overrides, in that order; unrelated kwargs and original-provider API-key selection remain intact.
|
||||
- `models.apply_rate_limiter` skips token counting and returns no limiter when all request, input, and output limits are unset; any configured limit retains normal accounting.
|
||||
- `requirements.txt` includes HTTPX's SOCKS extra so framework clients support SOCKS proxy environment variables before plugin setup.
|
||||
- `update_reqs.py` reads installed versions through standard-library `importlib.metadata`; it must not require the retired Torch-transitive setuptools/pkg_resources.
|
||||
- `requirements.txt` is the single root application/test/tooling manifest; plugin sandbox manifests remain independent. It includes HTTPX's SOCKS extra for framework clients before plugin setup. Source-only upgrades retain unused optional packages for private consumers; rerun the root install to obtain consolidated test tooling, and use a fresh environment or image to omit retired packages.
|
||||
- LiteLLM and OpenAI pins must remain compatible. Retain shared dependency security floors and verify upgrades with installed-SDK HTTP tests in `tests/test_litellm_sdk.py` using the framework runtime.
|
||||
- Native agent-turn response callbacks may receive a display-only commentary preview as their full text; legacy callbacks, accumulated model output, usage and native dispatch retain the original text and result metadata.
|
||||
- `run_ui.py` is the WebUI entry point.
|
||||
- `run_tunnel.py` is only a native sleep compatibility shim for old images until startup migration removes their Supervisor entry; Remote Control implementation and dependencies belong to `plugins/_tunnel/`.
|
||||
- `pytest.ini` and root `conftest.py` own test discovery: `tests` and `plugins` testpaths with importlib import mode, `tests/` importable for sibling test imports, and handler modules named like tests kept out of collection.
|
||||
- `prepare.py` migrates and loads legacy `.env` configuration before writing the root password; `helpers/migration.py` owns preservation of existing files and symlink handling.
|
||||
- `DockerfileLocal` must remain compatible with the contracts under `docker/`.
|
||||
@@ -44,15 +46,14 @@
|
||||
- Message-loop completion requires an explicit response-tool call with `break_loop`. Free text in either transport remains generation thoughts and silently continues; never synthesize a response-tool call from prose. Malformed tool intent keeps its repair path.
|
||||
- Reuse the startup-preloaded local embedding model for matching runtime configurations; wrappers retain their own rate-limit configuration while sharing the underlying inference model.
|
||||
- Embedding wrappers expose batch-shaped `embed(inputs)` for provider-ready inputs; keep `embed_documents` and `embed_query` as LangChain compatibility adapters.
|
||||
- The bundled local encoder is the checksum-pinned all-MiniLM-L6-v2 ONNX pipeline in `helpers/local_embeddings.py`. Build/setup prepares assets explicitly; inference is offline. Other local models or inference-changing kwargs fail explicitly until separately validated. Keep logical provider/model/cache identity only with persisted-index parity evidence. Source upgrades retain old optional packages/cache for private consumers and rollback; rebuilt images omit them.
|
||||
- Embedding requests never forward the chat-only `a0_api_mode` control to providers.
|
||||
- Prompt Markdown may retain fenced JSON examples for readability; final system-prompt rendering removes only their JSON fence markers before model calls and preserves non-JSON fences.
|
||||
- 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/`.
|
||||
- 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.
|
||||
- Linux processes sharing a checkout serialize dependency activation through `tmp/requirements.lock`, so cold graph verification cannot exhaust another startup process's Depfix cache-writer timeout. Preserve kernel lock release on errors, process exit and the one-time bootstrap exec.
|
||||
- For those four entrypoints only, an initial loader dependency ownership conflict may restart Python once using the verified graph's Depfix dependency paths. Preserve the selected artifacts, existing import path, original interpreter arguments and all ownership checks; embedded imports and other conflicts must fail normally. This bootstrap uses the pinned Depfix manifest/cache API and must be rechecked when upgrading Depfix.
|
||||
- Production Python entrypoints use installed dependencies directly. Install root `requirements.txt` during image build or local setup; do not add dependency graph activation to application imports.
|
||||
- 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
|
||||
|
||||
+26
-4
@@ -1,6 +1,6 @@
|
||||
# Use the pre-built base image for A0
|
||||
ARG BASE_IMAGE=agent-zero-base:local
|
||||
FROM ${BASE_IMAGE}
|
||||
FROM ${BASE_IMAGE} AS application
|
||||
# FROM agent0ai/agent-zero-base:testing
|
||||
# FROM agent0ai/agent-zero-base:latest
|
||||
|
||||
@@ -16,13 +16,13 @@ COPY ./ /git/agent-zero
|
||||
# pre installation steps
|
||||
RUN bash /ins/pre_install.sh $BRANCH
|
||||
|
||||
# Prime the Depfix store from the copied local source snapshot.
|
||||
# Install Python dependencies from the copied local source snapshot.
|
||||
RUN bash /ins/install_A0.sh $BRANCH
|
||||
|
||||
# install additional software
|
||||
RUN bash /ins/install_additional.sh $BRANCH
|
||||
|
||||
# Reuse exact Depfix packages and install runtime assets once from the final
|
||||
# Reuse installed Python 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
|
||||
@@ -33,7 +33,29 @@ 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_tunnel_api.sh /exe/trigger_self_update.sh
|
||||
RUN chmod +x /exe/initialize.sh /exe/run_A0.sh /exe/trigger_self_update.sh
|
||||
|
||||
# shortcut: import bytecode events can deadlock startup watchers; remove after fixing their lock ordering.
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
# initialize runtime and switch to supervisord
|
||||
CMD ["/exe/initialize.sh", "$BRANCH"]
|
||||
|
||||
FROM node:22-bookworm-slim AS sandbox-node
|
||||
FROM python:3.13-slim-bookworm AS sandbox-rootfs
|
||||
COPY --from=application /git/agent-zero/docker/sandbox/install.sh /tmp/install-sandbox.sh
|
||||
RUN --mount=type=bind,from=sandbox-node,source=/usr/local,target=/node \
|
||||
sh /tmp/install-sandbox.sh && rm /tmp/install-sandbox.sh
|
||||
|
||||
FROM node:22-bookworm-slim AS tuxee-build
|
||||
COPY --from=application /git/agent-zero/plugins/_desktop/build /recipe
|
||||
RUN sh /recipe/build.sh /output
|
||||
|
||||
FROM application
|
||||
COPY --from=tuxee-build /output/ /
|
||||
ARG TARGETARCH
|
||||
# Store the OCI bundle outside /a0 and usr so source/user mounts cannot hide it.
|
||||
RUN --mount=type=bind,from=sandbox-rootfs,target=/sandbox \
|
||||
cd /git/agent-zero && /usr/local/bin/python -m plugins._sandboxing.helpers.builtin_image \
|
||||
--rootfs /sandbox --output /opt/agent-zero/sandbox-image --architecture "$TARGETARCH" && \
|
||||
chmod -R a+rX /opt/agent-zero/sandbox-image
|
||||
@@ -11,11 +11,11 @@ class GetChatFilesPath(ApiHandler):
|
||||
|
||||
project_name = projects.get_context_project_name(context)
|
||||
if project_name:
|
||||
folder = files.normalize_a0_path(projects.get_project_folder(project_name))
|
||||
folder = projects.get_project_folder(project_name)
|
||||
else:
|
||||
folder = settings.get_settings()["workdir_path"]
|
||||
|
||||
return {
|
||||
"ok": True,
|
||||
"path": folder,
|
||||
}
|
||||
"path": files.fix_dev_path(folder) if folder else folder,
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- Return the local project/workdir path for the Files browser, resolving configured `/a0` aliases in development without changing stored settings or remote execution paths.
|
||||
- HTTP handlers must derive from `helpers.api.ApiHandler`; WebSocket handlers must derive from `helpers.ws.WsHandler`.
|
||||
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
|
||||
- `GetChatFilesPath` is an `ApiHandler`.
|
||||
@@ -25,7 +26,7 @@
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `self.use_context`, `projects.get_context_project_name`, `Exception`, `files.normalize_a0_path`, `projects.get_project_folder`, `settings.get_settings`.
|
||||
- Important called helpers/classes observed in the source: `self.use_context`, `projects.get_context_project_name`, `Exception`, `files.fix_dev_path`, `projects.get_project_folder`, `settings.get_settings`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
+2
-11
@@ -98,17 +98,8 @@ class GetCsrfToken(ApiHandler):
|
||||
if not allowed_origins:
|
||||
allowed_origins = self.get_default_allowed_origins()
|
||||
|
||||
# always allow tunnel url if running
|
||||
try:
|
||||
from api.tunnel_proxy import process as tunnel_api_process
|
||||
|
||||
tunnel = await tunnel_api_process({"action": "get"})
|
||||
if tunnel and isinstance(tunnel, dict) and tunnel.get("success"):
|
||||
tunnel_origin = origin_from_url(tunnel.get("tunnel_url"))
|
||||
if tunnel_origin:
|
||||
allowed_origins.append(tunnel_origin)
|
||||
except Exception:
|
||||
pass
|
||||
from helpers.tunnel_origins import get_active_tunnel_origins
|
||||
allowed_origins.extend(get_active_tunnel_origins())
|
||||
|
||||
return allowed_origins
|
||||
|
||||
|
||||
@@ -55,3 +55,5 @@
|
||||
## Child DOX Index
|
||||
|
||||
No child DOX files.
|
||||
|
||||
Active Remote Control origins come from the plugin through `helpers.tunnel_origins.get_active_tunnel_origins`; no secondary HTTP controller is queried.
|
||||
@@ -2,7 +2,7 @@ from helpers.api import ApiHandler, Input, Output, Request, Response
|
||||
|
||||
|
||||
from helpers.file_browser import FileBrowser
|
||||
from helpers import files, runtime, extension
|
||||
from helpers import extension
|
||||
from api import get_work_dir_files
|
||||
|
||||
|
||||
@@ -15,8 +15,7 @@ class DeleteWorkDirFile(ApiHandler):
|
||||
|
||||
current_path = input.get("currentPath", "")
|
||||
|
||||
# browser = FileBrowser()
|
||||
res = await runtime.call_development_function(delete_file, file_path)
|
||||
res = await delete_file(file_path)
|
||||
|
||||
if res:
|
||||
await extension.call_extensions_async(
|
||||
@@ -30,8 +29,7 @@ class DeleteWorkDirFile(ApiHandler):
|
||||
},
|
||||
)
|
||||
# Get updated file list
|
||||
# result = browser.get_files(current_path)
|
||||
result = await runtime.call_development_function(get_work_dir_files.get_files, current_path)
|
||||
result = await get_work_dir_files.get_files(current_path)
|
||||
return {"data": result}
|
||||
else:
|
||||
return {"error": "File not found or could not be deleted"}
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- Invoke the existing file helpers locally in both development and production; await their async entry points. Path validation, response shapes and mutation hooks remain unchanged.
|
||||
|
||||
- HTTP handlers must derive from `helpers.api.ApiHandler`; WebSocket handlers must derive from `helpers.ws.WsHandler`.
|
||||
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
|
||||
- `DeleteWorkDirFile` is an `ApiHandler`.
|
||||
@@ -27,7 +29,7 @@
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `FileBrowser`, `browser.delete_file`, `file_path.startswith`, `runtime.call_development_function`, `extension.call_extensions_async`.
|
||||
- Important called helpers/classes observed in the source: `FileBrowser`, `browser.delete_file`, `file_path.startswith`, `extension.call_extensions_async`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from helpers.api import ApiHandler, Input, Output, Request
|
||||
from helpers.file_browser import FileBrowser
|
||||
from helpers import runtime, extension
|
||||
from helpers import extension
|
||||
from api import get_work_dir_files
|
||||
from helpers.file_archives import normalize_paths
|
||||
|
||||
@@ -17,7 +17,7 @@ class DeleteWorkDirFiles(ApiHandler):
|
||||
if not paths:
|
||||
return {"error": "No file paths provided"}
|
||||
|
||||
result = await runtime.call_development_function(delete_files, paths)
|
||||
result = await delete_files(paths)
|
||||
deleted = result["deleted"]
|
||||
failed = result["failed"]
|
||||
|
||||
@@ -33,9 +33,7 @@ class DeleteWorkDirFiles(ApiHandler):
|
||||
},
|
||||
)
|
||||
|
||||
files_result = await runtime.call_development_function(
|
||||
get_work_dir_files.get_files, current_path
|
||||
)
|
||||
files_result = await get_work_dir_files.get_files(current_path)
|
||||
|
||||
if not deleted:
|
||||
return {
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- Invoke the existing file helpers locally in both development and production; await their async entry points. Path validation, response shapes and mutation hooks remain unchanged.
|
||||
|
||||
- HTTP handlers must derive from `helpers.api.ApiHandler`; WebSocket handlers must derive from `helpers.ws.WsHandler`.
|
||||
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
|
||||
- `DeleteWorkDirFiles` is an `ApiHandler`.
|
||||
@@ -28,7 +30,7 @@
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `FileBrowser`, `collapse_nested_paths`, `browser.delete_file`, `normalize_paths`, `runtime.call_development_function`, `path.strip`, `extension.call_extensions_async`, `item.count`, `clean_path.startswith`, `parent.rstrip`.
|
||||
- Important called helpers/classes observed in the source: `FileBrowser`, `collapse_nested_paths`, `browser.delete_file`, `normalize_paths`, `path.strip`, `extension.call_extensions_async`, `item.count`, `clean_path.startswith`, `parent.rstrip`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import base64
|
||||
from io import BytesIO
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Response
|
||||
from helpers.api import ApiHandler, Input, Output, Request
|
||||
from helpers import files, runtime, file_archives
|
||||
from helpers import files, file_archives
|
||||
from api import file_info
|
||||
|
||||
|
||||
@@ -31,50 +29,27 @@ class DownloadFile(ApiHandler):
|
||||
file_path = f"/{file_path}"
|
||||
|
||||
try:
|
||||
file_path = await runtime.call_development_function(
|
||||
resolve_download_path, file_path
|
||||
)
|
||||
file_path = resolve_download_path(file_path)
|
||||
except ValueError as exc:
|
||||
return Response(str(exc), status=400)
|
||||
|
||||
file = await runtime.call_development_function(
|
||||
file_info.get_file_info, file_path
|
||||
)
|
||||
file = await file_info.get_file_info(file_path)
|
||||
|
||||
if not file["exists"]:
|
||||
raise Exception(f"File {file_path} not found")
|
||||
|
||||
if file["is_dir"]:
|
||||
zip_file = await runtime.call_development_function(files.zip_dir, file["abs_path"])
|
||||
zip_file = files.zip_dir(file["abs_path"])
|
||||
directory_name = os.path.basename(file_path.rstrip("/")) or "directory"
|
||||
download_name = f"{directory_name}.zip"
|
||||
if runtime.is_development():
|
||||
try:
|
||||
b64 = await runtime.call_development_function(files.read_file_base64, zip_file)
|
||||
finally:
|
||||
await runtime.call_development_function(files.delete_file, zip_file)
|
||||
file_data = BytesIO(base64.b64decode(b64))
|
||||
return stream_file_download(
|
||||
file_data,
|
||||
download_name=download_name
|
||||
)
|
||||
else:
|
||||
try:
|
||||
return stream_file_download(zip_file, download_name=download_name, delete_after=True)
|
||||
except BaseException:
|
||||
files.delete_file(zip_file)
|
||||
raise
|
||||
try:
|
||||
return stream_file_download(zip_file, download_name=download_name, delete_after=True)
|
||||
except BaseException:
|
||||
files.delete_file(zip_file)
|
||||
raise
|
||||
elif file["is_file"]:
|
||||
if runtime.is_development():
|
||||
b64 = await runtime.call_development_function(files.read_file_base64, file["abs_path"])
|
||||
file_data = BytesIO(base64.b64decode(b64))
|
||||
return stream_file_download(
|
||||
file_data,
|
||||
download_name=os.path.basename(file_path)
|
||||
)
|
||||
else:
|
||||
return stream_file_download(
|
||||
file["abs_path"],
|
||||
download_name=os.path.basename(file["file_name"])
|
||||
)
|
||||
return stream_file_download(
|
||||
file["abs_path"],
|
||||
download_name=os.path.basename(file["file_name"])
|
||||
)
|
||||
raise Exception(f"File {file_path} not found")
|
||||
@@ -1,7 +1,7 @@
|
||||
# Generic file download
|
||||
|
||||
Retain authenticated/CSRF-protected GET downloads for general clients, including Connector HTTP staging. This route resolves container filesystem paths and supports directories. It does not select Files preferences from query flags. Files uses its explicit `download_work_dir_files` preparation/delivery route.
|
||||
Retain authenticated/CSRF-protected GET downloads for general clients, including Connector HTTP staging. This route resolves local filesystem paths and supports directories. It does not select Files preferences from query flags. Files uses its explicit `download_work_dir_files` preparation/delivery route.
|
||||
|
||||
Shared `helpers.file_transfers.stream_file_download` serves and hashes a held descriptor, emits safe Content-Disposition and integrity headers, and closes resources. Development RFC uses `files.read_file_base64`; directory archives are removed remotely in `finally`. Production directory responses own their temporary ZIP via `delete_after=True`, with cleanup if response preparation fails. The string-returning resolver delegates to `file_archives.resolve_download_path` with explicit `/` root.
|
||||
Shared `helpers.file_transfers.stream_file_download` serves and hashes a held descriptor, emits safe Content-Disposition and integrity headers, and closes resources. Both runtime modes stream local files directly. Directory responses own their temporary ZIP via `delete_after=True`, with cleanup if response preparation fails. The string-returning resolver delegates to `file_archives.resolve_download_path` with explicit `/` root.
|
||||
|
||||
Verify generic download integrity and filesystem-root scope with `tests/test_download_work_dir_file.py` and path tests. Preserve authentication and CSRF.
|
||||
@@ -1,13 +1,9 @@
|
||||
"""Authenticated Files downloads; policy and I/O belong to shared helpers."""
|
||||
import base64
|
||||
import asyncio
|
||||
from io import BytesIO
|
||||
import json
|
||||
|
||||
from helpers.api import ApiHandler, Input, Output, Request, Response
|
||||
from helpers import files, runtime
|
||||
from helpers.file_browser import prepare_files_download, prepare_files_response, remove_download_temporary, register_files_download
|
||||
from helpers.file_transfers import stream_file_download, take_download_response, FileLimitExceeded
|
||||
from helpers.file_browser import prepare_files_response, register_files_download
|
||||
from helpers.file_transfers import take_download_response, FileLimitExceeded
|
||||
|
||||
|
||||
class DownloadFiles(ApiHandler):
|
||||
@@ -25,19 +21,7 @@ class DownloadFiles(ApiHandler):
|
||||
return Response(json.dumps({"error": str(error)}), status=403, mimetype="application/json")
|
||||
paths = input.get("paths", [])
|
||||
try:
|
||||
if runtime.is_development():
|
||||
download = await runtime.call_development_function(prepare_files_download, paths, input.get("currentPath", ""))
|
||||
try:
|
||||
data = await runtime.call_development_function(files.read_file_base64, download["file_source"])
|
||||
finally:
|
||||
if download["delete_after"]:
|
||||
await runtime.call_development_function(remove_download_temporary, download["file_source"])
|
||||
download["file_source"] = BytesIO(base64.b64decode(data))
|
||||
download["delete_after"] = False
|
||||
response = await asyncio.to_thread(stream_file_download, **download)
|
||||
name = download["download_name"]
|
||||
else:
|
||||
response, name = await prepare_files_response(paths, input.get("currentPath", ""))
|
||||
response, name = await prepare_files_response(paths, input.get("currentPath", ""))
|
||||
token = register_files_download(response, paths)
|
||||
return {"download_url": "/api/download_work_dir_files?token=" + token, "name": name}
|
||||
except FileLimitExceeded as error:
|
||||
|
||||
@@ -2,10 +2,8 @@
|
||||
|
||||
Authenticated, CSRF-protected POST accepts `paths` and optional `currentPath`. Shared FileBrowser helpers select local/remote storage, enforce operation policy and prepare a streamed response. Return a download URL and filename; the browser follows it natively without loading a file into a JavaScript Blob.
|
||||
|
||||
Authenticated GET claims the opaque single-use token. Unclaimed responses expire after two minutes; remote permissions are rechecked at claim. This endpoint does not select byte limits. File/ZIP work runs outside the request event loop. The existing development RFC adapter remains separate from production HTTP streaming.
|
||||
Authenticated GET claims the opaque single-use token. Unclaimed responses expire after two minutes; remote permissions are rechecked at claim. This endpoint does not select byte limits. File/ZIP work runs outside the request event loop. Development and production both await the shared local preparation path, including cancellation cleanup.
|
||||
|
||||
Verify preparation errors, token auth/CSRF, one-time delivery, limits and response cleanup. Generic Connector downloads use `download_work_dir_file` instead.
|
||||
|
||||
This endpoint maps plain size, missing-token and permission exceptions to explicit 413/404/403 responses. Framework-wide exception and malformed-JSON behavior is unchanged.
|
||||
|
||||
Development RFC reads use `files.read_file_base64` directly, without importing another endpoint.
|
||||
@@ -3,7 +3,7 @@ import os
|
||||
|
||||
from helpers.api import ApiHandler, Input, Output, Request
|
||||
from helpers.file_browser import FileBrowser
|
||||
from helpers import runtime, extension
|
||||
from helpers import extension
|
||||
|
||||
|
||||
class EditWorkDirFile(ApiHandler):
|
||||
@@ -27,7 +27,7 @@ class EditWorkDirFile(ApiHandler):
|
||||
if not file_path.startswith("/"):
|
||||
file_path = f"/{file_path}"
|
||||
|
||||
data = await runtime.call_development_function(load_file, file_path)
|
||||
data = await load_file(file_path)
|
||||
return {"data": data}
|
||||
|
||||
file_path = input.get("path", "")
|
||||
@@ -42,7 +42,7 @@ class EditWorkDirFile(ApiHandler):
|
||||
|
||||
FileBrowser.text_bytes(content)
|
||||
|
||||
res = await runtime.call_development_function(save_file, file_path, content)
|
||||
res = save_file(file_path, content)
|
||||
if not res:
|
||||
return {"error": "Failed to save file"}
|
||||
|
||||
@@ -58,7 +58,6 @@ class EditWorkDirFile(ApiHandler):
|
||||
return {"ok": True}
|
||||
except Exception as e:
|
||||
# Extract clean error message from exception
|
||||
# RPC calls may return full tracebacks in exception strings
|
||||
return {"error": self._extract_error_message(str(e))}
|
||||
|
||||
|
||||
|
||||
@@ -21,6 +21,8 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- Invoke the existing file helpers locally in both development and production; await their async entry points. Path validation, response shapes and mutation hooks remain unchanged.
|
||||
|
||||
- HTTP handlers must derive from `helpers.api.ApiHandler`; WebSocket handlers must derive from `helpers.ws.WsHandler`.
|
||||
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
|
||||
- `EditWorkDirFile` is an `ApiHandler`.
|
||||
@@ -31,7 +33,7 @@
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important helpers: `FileBrowser.text_bytes`, `FileBrowser.decode_text`, `browser.get_full_path`, `browser.save_text_file`, `runtime.call_development_function`, and `extension.call_extensions_async`.
|
||||
- Important helpers: `FileBrowser.text_bytes`, `FileBrowser.decode_text`, `browser.get_full_path`, `browser.save_text_file`, and `extension.call_extensions_async`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from helpers import extension, runtime
|
||||
from helpers import extension
|
||||
from helpers.api import ApiHandler, Input, Output, Request
|
||||
from api import get_work_dir_files
|
||||
|
||||
@@ -17,7 +17,7 @@ class ExtractWorkDirArchive(ApiHandler):
|
||||
path = f"/{path}"
|
||||
|
||||
try:
|
||||
extracted_path = await runtime.call_development_function(extract_archive, path)
|
||||
extracted_path = extract_archive(path)
|
||||
except (OSError, ValueError) as exc:
|
||||
return {"error": str(exc)}
|
||||
|
||||
@@ -32,5 +32,5 @@ class ExtractWorkDirArchive(ApiHandler):
|
||||
"current_path": current_path,
|
||||
},
|
||||
)
|
||||
listing = await runtime.call_development_function(get_work_dir_files.get_files, current_path)
|
||||
listing = await get_work_dir_files.get_files(current_path)
|
||||
return {"data": listing, "extracted_path": extracted_path}
|
||||
@@ -1,6 +1,6 @@
|
||||
# Files extraction
|
||||
|
||||
Authenticated/CSRF-protected handler validates the request, delegates extraction to `helpers.file_archives`, emits the existing mutation hook and refreshes the listing. Keep archive inspection, size/count policy, controlled writes and cleanup in helpers. The operation is distinct from Backup & Restore.
|
||||
Authenticated/CSRF-protected handler validates the request, calls local extraction through `helpers.file_archives`, emits the existing mutation hook and refreshes the listing. Keep archive inspection, size/count policy, controlled writes and cleanup in helpers. The operation is distinct from Backup & Restore.
|
||||
|
||||
Verify `tests/test_file_browser_archives.py` and `tests/test_file_transfer_safety.py`.
|
||||
|
||||
|
||||
+4
-4
@@ -1,12 +1,12 @@
|
||||
import os
|
||||
from helpers.api import ApiHandler, Input, Output, Request, Response
|
||||
from helpers import files, runtime
|
||||
from helpers import files
|
||||
from typing import TypedDict
|
||||
|
||||
class FileInfoApi(ApiHandler):
|
||||
async def process(self, input: Input, request: Request) -> Output:
|
||||
path = input.get("path", "")
|
||||
info = await runtime.call_development_function(get_file_info, path)
|
||||
info = await get_file_info(path)
|
||||
return info
|
||||
|
||||
class FileInfo(TypedDict):
|
||||
@@ -26,7 +26,7 @@ class FileInfo(TypedDict):
|
||||
message: str
|
||||
|
||||
async def get_file_info(path: str) -> FileInfo:
|
||||
abs_path = files.get_abs_path(path)
|
||||
abs_path = files.get_abs_path_development(path)
|
||||
exists = os.path.exists(abs_path)
|
||||
message = ""
|
||||
|
||||
@@ -48,4 +48,4 @@ async def get_file_info(path: str) -> FileInfo:
|
||||
"file_name": os.path.basename(abs_path),
|
||||
"file_ext": os.path.splitext(abs_path)[1],
|
||||
"message": message
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,9 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- Invoke the existing file helpers locally in both development and production; await their async entry points. Path validation, response shapes and mutation hooks remain unchanged.
|
||||
- Resolve development `/a0` aliases before local stat calls; retain the original `input_path` and report the resolved local `abs_path`.
|
||||
|
||||
- HTTP handlers must derive from `helpers.api.ApiHandler`; WebSocket handlers must derive from `helpers.ws.WsHandler`.
|
||||
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
|
||||
- `FileInfoApi` is an `ApiHandler`.
|
||||
@@ -28,7 +31,7 @@
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `files.get_abs_path`, `os.path.exists`, `os.path.dirname`, `os.path.basename`, `runtime.call_development_function`, `os.path.isdir`, `os.path.isfile`, `os.path.islink`, `os.path.getsize`, `os.path.getmtime`, `os.path.getctime`, `os.path.splitext`, `os.stat`.
|
||||
- Important called helpers/classes observed in the source: `files.get_abs_path`, `os.path.exists`, `os.path.dirname`, `os.path.basename`, `os.path.isdir`, `os.path.isfile`, `os.path.islink`, `os.path.getsize`, `os.path.getmtime`, `os.path.getctime`, `os.path.splitext`, `os.stat`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from helpers.api import ApiHandler, Request, Response
|
||||
from helpers.file_browser import FileBrowser
|
||||
from helpers import runtime, files
|
||||
from helpers import files
|
||||
|
||||
class GetWorkDirFiles(ApiHandler):
|
||||
|
||||
@@ -13,15 +13,9 @@ class GetWorkDirFiles(ApiHandler):
|
||||
return {"limits": FileBrowser.limits()}
|
||||
current_path = request.args.get("path", "") or "$WORK_DIR"
|
||||
if current_path == "$WORK_DIR":
|
||||
# if runtime.is_development():
|
||||
# current_path = "work_dir"
|
||||
# else:
|
||||
# current_path = "root"
|
||||
current_path = "/a0"
|
||||
|
||||
# browser = FileBrowser()
|
||||
# result = browser.get_files(current_path)
|
||||
result = await runtime.call_development_function(get_files, current_path)
|
||||
result = await get_files(current_path)
|
||||
|
||||
return {"data": result, "limits": FileBrowser.limits()}
|
||||
|
||||
@@ -32,4 +26,4 @@ async def get_files(path):
|
||||
import asyncio
|
||||
return await asyncio.to_thread(file_connections.listing, path)
|
||||
browser = FileBrowser()
|
||||
return browser.get_files(path)
|
||||
return browser.get_files(files.fix_dev_path(str(browser.base_dir / path)))
|
||||
@@ -19,6 +19,8 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- Invoke the existing file helpers locally in both development and production; await their async entry points. Path validation, response shapes and mutation hooks remain unchanged.
|
||||
|
||||
- Responses include FileBrowser-owned `limits`; `?limits=1` returns only those constraints without listing a directory. Files and Editor use this metadata instead of separate frontend caps.
|
||||
|
||||
- HTTP handlers must derive from `helpers.api.ApiHandler`; WebSocket handlers must derive from `helpers.ws.WsHandler`.
|
||||
@@ -30,8 +32,8 @@
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `FileBrowser`, `browser.get_files`, `runtime.call_development_function`.
|
||||
- Empty `path` requests and explicit `$WORK_DIR` requests resolve to the default workdir path before `FileBrowser` is called, so the WebUI never receives an empty startup path for the default file browser view.
|
||||
- Important called helpers/classes observed in the source: `FileBrowser`, `browser.get_files`.
|
||||
- Empty `path` requests and explicit `$WORK_DIR` requests resolve to `/a0` (the local checkout in development) before `FileBrowser` is called. Local listings translate `/a0` aliases and return local paths for subsequent mutations; remote-provider paths bypass that translation.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
+3
-37
@@ -1,11 +1,8 @@
|
||||
import base64
|
||||
import os
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
from helpers.api import ApiHandler, Request, Response, send_file
|
||||
from helpers import files, runtime
|
||||
import io
|
||||
from mimetypes import guess_type
|
||||
|
||||
|
||||
IMAGE_EXTENSIONS = (
|
||||
@@ -49,41 +46,10 @@ class ImageGet(ApiHandler):
|
||||
except ValueError as exc:
|
||||
return Response(str(exc), status=403, mimetype="text/plain")
|
||||
|
||||
# in development environment, try to serve the image from local file system if exists, otherwise from docker
|
||||
if runtime.is_development():
|
||||
if files.exists(local_path):
|
||||
response = send_file(local_path)
|
||||
else:
|
||||
# Try fetching from Docker via RFC as fallback
|
||||
try:
|
||||
remote_path = await runtime.call_development_function(
|
||||
_resolve_allowed_image_path, path
|
||||
)
|
||||
if await runtime.call_development_function(
|
||||
files.exists, remote_path
|
||||
):
|
||||
b64_content = await runtime.call_development_function(
|
||||
files.read_file_base64, remote_path
|
||||
)
|
||||
file_content = base64.b64decode(b64_content)
|
||||
mime_type, _ = guess_type(filename)
|
||||
if not mime_type:
|
||||
mime_type = "application/octet-stream"
|
||||
response = send_file(
|
||||
io.BytesIO(file_content),
|
||||
mimetype=mime_type,
|
||||
as_attachment=False,
|
||||
download_name=filename,
|
||||
)
|
||||
else:
|
||||
response = _send_fallback_icon("image")
|
||||
except Exception:
|
||||
response = _send_fallback_icon("image")
|
||||
if files.exists(local_path):
|
||||
response = send_file(local_path)
|
||||
else:
|
||||
if files.exists(local_path):
|
||||
response = send_file(local_path)
|
||||
else:
|
||||
response = _send_fallback_icon("image")
|
||||
response = _send_fallback_icon("image")
|
||||
|
||||
_set_image_headers(response, filename, file_ext)
|
||||
return response
|
||||
|
||||
@@ -23,13 +23,15 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- Resolve and validate local image paths in both modes, preserving development `/a0/` mapping, symlink/root containment and SVG security headers. Missing images use the existing icon fallback without contacting a sibling.
|
||||
|
||||
- HTTP handlers must derive from `helpers.api.ApiHandler`; WebSocket handlers must derive from `helpers.ws.WsHandler`.
|
||||
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
|
||||
- `ImageGet` is an `ApiHandler`.
|
||||
- `ImageGet` defines `process(...)`.
|
||||
- `ImageGet` defines `get_methods(...)`.
|
||||
- Observed side-effect areas: filesystem reads, network calls, subprocess/runtime control, settings/state persistence.
|
||||
- Imported dependency areas include: `base64`, `helpers`, `helpers.api`, `io`, `mimetypes`, `os`, `pathlib`, `urllib.parse`.
|
||||
- Observed side-effect areas: filesystem reads.
|
||||
- Imported dependency areas include: `helpers`, `helpers.api`, `os`, `pathlib`, `urllib.parse`.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from helpers.api import ApiHandler, Input, Output, Request
|
||||
from helpers.file_browser import FileBrowser
|
||||
from helpers import runtime, extension
|
||||
from helpers import extension
|
||||
from api import get_work_dir_files
|
||||
import posixpath
|
||||
|
||||
@@ -26,9 +26,7 @@ class RenameWorkDirFile(ApiHandler):
|
||||
]
|
||||
if not destination_path.startswith("/"):
|
||||
destination_path = f"/{destination_path}"
|
||||
moved_paths = await runtime.call_development_function(
|
||||
move_items, file_paths, destination_path
|
||||
)
|
||||
moved_paths = await move_items(file_paths, destination_path)
|
||||
res = bool(moved_paths)
|
||||
changed_paths = [*file_paths, *moved_paths]
|
||||
elif action in {"rename", "create-folder"}:
|
||||
@@ -40,9 +38,7 @@ class RenameWorkDirFile(ApiHandler):
|
||||
parent_path = input.get("parentPath", current_path)
|
||||
if not parent_path:
|
||||
return {"error": "Parent path is required"}
|
||||
res = await runtime.call_development_function(
|
||||
create_folder, parent_path, new_name
|
||||
)
|
||||
res = await create_folder(parent_path, new_name)
|
||||
changed_paths = [
|
||||
posixpath.join(str(parent_path).rstrip("/"), new_name)
|
||||
]
|
||||
@@ -52,9 +48,7 @@ class RenameWorkDirFile(ApiHandler):
|
||||
return {"error": "Path is required"}
|
||||
if not file_path.startswith("/"):
|
||||
file_path = f"/{file_path}"
|
||||
res = await runtime.call_development_function(
|
||||
rename_item, file_path, new_name
|
||||
)
|
||||
res = await rename_item(file_path, new_name)
|
||||
changed_paths = [
|
||||
file_path,
|
||||
posixpath.join(posixpath.dirname(file_path), new_name),
|
||||
@@ -73,9 +67,7 @@ class RenameWorkDirFile(ApiHandler):
|
||||
"current_path": current_path,
|
||||
},
|
||||
)
|
||||
result = await runtime.call_development_function(
|
||||
get_work_dir_files.get_files, current_path
|
||||
)
|
||||
result = await get_work_dir_files.get_files(current_path)
|
||||
return {"data": result}
|
||||
|
||||
error_msg = {
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- Invoke the existing file helpers locally in both development and production; await their async entry points. Path validation, response shapes and mutation hooks remain unchanged.
|
||||
|
||||
- HTTP handlers must derive from `helpers.api.ApiHandler`; WebSocket handlers must derive from `helpers.ws.WsHandler`.
|
||||
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
|
||||
- `RenameWorkDirFile` is an `ApiHandler`.
|
||||
@@ -29,7 +31,7 @@
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `FileBrowser`, `browser.rename_item`, `browser.create_folder`, `browser.move_items`, `strip`, `runtime.call_development_function`, `posixpath.join`, `file_path.startswith`, `extension.call_extensions_async`, `str.rstrip`, `posixpath.dirname`.
|
||||
- Important called helpers/classes observed in the source: `FileBrowser`, `browser.rename_item`, `browser.create_folder`, `browser.move_items`, `strip`, `posixpath.join`, `file_path.startswith`, `extension.call_extensions_async`, `str.rstrip`, `posixpath.dirname`.
|
||||
- The `move` action accepts `paths` plus `destinationPath`, emits the standard mutation hook, and returns the refreshed `currentPath` listing used by drag-and-drop clients.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
|
||||
+3
-65
@@ -1,65 +1,3 @@
|
||||
from helpers.api import ApiHandler, Request, Response
|
||||
from helpers import runtime
|
||||
from helpers.tunnel_manager import TunnelManager
|
||||
|
||||
class Tunnel(ApiHandler):
|
||||
async def process(self, input: dict, request: Request) -> dict | Response:
|
||||
return await process(input)
|
||||
|
||||
async def process(input: dict) -> dict | Response:
|
||||
action = input.get("action", "get")
|
||||
|
||||
tunnel_manager = TunnelManager.get_instance()
|
||||
|
||||
if action == "health":
|
||||
return {"success": True}
|
||||
|
||||
if action == "create":
|
||||
port = runtime.get_web_ui_port()
|
||||
provider = input.get("provider", "serveo") # Default to serveo
|
||||
tunnel_url = tunnel_manager.start_tunnel(port, provider)
|
||||
error = tunnel_manager.get_last_error()
|
||||
if error:
|
||||
return {
|
||||
"success": False,
|
||||
"tunnel_url": None,
|
||||
"message": error,
|
||||
"notifications": tunnel_manager.get_notifications()
|
||||
}
|
||||
|
||||
return {
|
||||
"success": tunnel_url is not None,
|
||||
"tunnel_url": tunnel_url,
|
||||
"notifications": tunnel_manager.get_notifications()
|
||||
}
|
||||
|
||||
elif action == "stop":
|
||||
return stop()
|
||||
|
||||
elif action == "get":
|
||||
tunnel_url = tunnel_manager.get_tunnel_url()
|
||||
return {
|
||||
"success": tunnel_url is not None,
|
||||
"tunnel_url": tunnel_url,
|
||||
"is_running": tunnel_manager.is_running
|
||||
}
|
||||
|
||||
elif action == "notifications":
|
||||
return {
|
||||
"success": True,
|
||||
"notifications": tunnel_manager.get_notifications(),
|
||||
"tunnel_url": tunnel_manager.get_tunnel_url(),
|
||||
"is_running": tunnel_manager.is_running
|
||||
}
|
||||
|
||||
return {
|
||||
"success": False,
|
||||
"error": "Invalid action. Use 'create', 'stop', 'get', or 'notifications'."
|
||||
}
|
||||
|
||||
def stop():
|
||||
tunnel_manager = TunnelManager.get_instance()
|
||||
tunnel_manager.stop_tunnel()
|
||||
return {
|
||||
"success": True
|
||||
}
|
||||
"""Compatibility endpoint for the Remote Control plugin."""
|
||||
from plugins._tunnel.api.tunnel import Tunnel, process
|
||||
from plugins._tunnel.helpers.runtime import stop
|
||||
+3
-46
@@ -1,48 +1,5 @@
|
||||
# tunnel.py DOX
|
||||
# Legacy Tunnel Endpoint
|
||||
|
||||
## Purpose
|
||||
Compatibility entry for the Remote Control plugin's API. Requests delegate to `plugins._tunnel.api.tunnel` and retain normal route authentication and CSRF protection. There is no separate tunnel API port or in-process provider fallback.
|
||||
|
||||
- Own the `tunnel.py` API endpoint.
|
||||
- This module manages tunnel provider status, start, and stop actions.
|
||||
- Keep this file-level DOX profile synchronized with `tunnel.py` because this directory is intentionally flat.
|
||||
|
||||
## Ownership
|
||||
|
||||
- `tunnel.py` owns the runtime implementation.
|
||||
- `tunnel.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation.
|
||||
- Classes:
|
||||
- `Tunnel` (`ApiHandler`)
|
||||
- `async process(self, input: dict, request: Request) -> dict | Response`
|
||||
- Top-level functions:
|
||||
- `async process(input: dict) -> dict | Response`
|
||||
- `stop()`
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- HTTP handlers must derive from `helpers.api.ApiHandler`; WebSocket handlers must derive from `helpers.ws.WsHandler`.
|
||||
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
|
||||
- `Tunnel` is an `ApiHandler`.
|
||||
- `Tunnel` defines `process(...)`.
|
||||
- Observed side-effect areas: tunnel state.
|
||||
- Imported dependency areas include: `helpers`, `helpers.api`, `helpers.tunnel_manager`.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `TunnelManager.get_instance`, `tunnel_manager.stop_tunnel`, `runtime.get_web_ui_port`, `tunnel_manager.start_tunnel`, `tunnel_manager.get_last_error`, `process`, `tunnel_manager.get_notifications`, `stop`, `tunnel_manager.get_tunnel_url`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
- Preserve authentication, CSRF, loopback, and API-key checks unless the endpoint contract explicitly changes.
|
||||
- Update frontend callers, plugin callers, and tests together when payload shape changes.
|
||||
- Use `helpers.api.Response` for non-JSON responses, files, redirects, or status-specific replies.
|
||||
|
||||
## Verification
|
||||
|
||||
- Run endpoint-specific or API/WebSocket tests for changed behavior; smoke-test browser callers when no focused test exists.
|
||||
- Related tests observed by source search:
|
||||
- `tests/test_tunnel_remote_link.py`
|
||||
|
||||
## Child DOX Index
|
||||
|
||||
No child DOX files.
|
||||
The plugin owns create/stop/get/notifications/verify behavior and sandbox state. Verify with tunnel plugin/provider tests, origin security tests, and a real authenticated HTTP request.
|
||||
+2
-38
@@ -1,38 +1,2 @@
|
||||
from helpers.api import ApiHandler, Request, Response
|
||||
from helpers import dotenv, runtime
|
||||
from helpers.tunnel_manager import TunnelManager
|
||||
import requests
|
||||
|
||||
|
||||
class TunnelProxy(ApiHandler):
|
||||
async def process(self, input: dict, request: Request) -> dict | Response:
|
||||
return await process(input)
|
||||
|
||||
async def process(input: dict) -> dict | Response:
|
||||
# Get configuration from environment
|
||||
tunnel_api_port = (
|
||||
runtime.get_arg("tunnel_api_port")
|
||||
or int(dotenv.get_dotenv_value("TUNNEL_API_PORT", 0))
|
||||
or 55520
|
||||
)
|
||||
|
||||
# first verify the service is running:
|
||||
service_ok = False
|
||||
try:
|
||||
response = requests.post(f"http://localhost:{tunnel_api_port}/", json={"action": "health"})
|
||||
if response.status_code == 200:
|
||||
service_ok = True
|
||||
except Exception as e:
|
||||
service_ok = False
|
||||
|
||||
# forward this request to the tunnel service if OK
|
||||
if service_ok:
|
||||
try:
|
||||
response = requests.post(f"http://localhost:{tunnel_api_port}/", json=input)
|
||||
return response.json()
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
else:
|
||||
# forward to API handler directly
|
||||
from api.tunnel import process as local_process
|
||||
return await local_process(input)
|
||||
"""Compatibility endpoint; no separate tunnel control service."""
|
||||
from plugins._tunnel.api.tunnel import Tunnel as TunnelProxy, process
|
||||
@@ -1,46 +1,5 @@
|
||||
# tunnel_proxy.py DOX
|
||||
# Legacy Tunnel Endpoint
|
||||
|
||||
## Purpose
|
||||
Compatibility entry for the Remote Control plugin's API. Requests delegate to `plugins._tunnel.api.tunnel` and retain normal route authentication and CSRF protection. There is no separate tunnel API port or in-process provider fallback.
|
||||
|
||||
- Own the `tunnel_proxy.py` API endpoint.
|
||||
- This module proxies tunnel-related HTTP traffic through the configured tunnel provider.
|
||||
- Keep this file-level DOX profile synchronized with `tunnel_proxy.py` because this directory is intentionally flat.
|
||||
|
||||
## Ownership
|
||||
|
||||
- `tunnel_proxy.py` owns the runtime implementation.
|
||||
- `tunnel_proxy.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation.
|
||||
- Classes:
|
||||
- `TunnelProxy` (`ApiHandler`)
|
||||
- `async process(self, input: dict, request: Request) -> dict | Response`
|
||||
- Top-level functions:
|
||||
- `async process(input: dict) -> dict | Response`
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- HTTP handlers must derive from `helpers.api.ApiHandler`; WebSocket handlers must derive from `helpers.ws.WsHandler`.
|
||||
- Update this file whenever request payloads, authentication or CSRF requirements, response shapes, route side effects, or WebSocket event contracts change.
|
||||
- `TunnelProxy` is an `ApiHandler`.
|
||||
- `TunnelProxy` defines `process(...)`.
|
||||
- Observed side-effect areas: network calls, settings/state persistence, tunnel state.
|
||||
- Imported dependency areas include: `helpers`, `helpers.api`, `helpers.tunnel_manager`, `requests`.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `runtime.get_arg`, `requests.post`, `process`, `dotenv.get_dotenv_value`, `response.json`, `local_process`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
- Preserve authentication, CSRF, loopback, and API-key checks unless the endpoint contract explicitly changes.
|
||||
- Update frontend callers, plugin callers, and tests together when payload shape changes.
|
||||
- Use `helpers.api.Response` for non-JSON responses, files, redirects, or status-specific replies.
|
||||
|
||||
## Verification
|
||||
|
||||
- Run endpoint-specific or API/WebSocket tests for changed behavior; smoke-test browser callers when no focused test exists.
|
||||
- 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.
|
||||
The plugin owns create/stop/get/notifications/verify behavior and sandbox state. Verify with tunnel plugin/provider tests, origin security tests, and a real authenticated HTTP request.
|
||||
@@ -4,9 +4,8 @@ from werkzeug.datastructures import FileStorage
|
||||
from helpers.api import ApiHandler, Request, Response
|
||||
from helpers.file_browser import FileBrowser
|
||||
from helpers.file_transfers import FileLimitExceeded
|
||||
from helpers import files, runtime, extension
|
||||
from helpers import extension
|
||||
from api import get_work_dir_files
|
||||
import os
|
||||
import posixpath
|
||||
|
||||
|
||||
@@ -41,8 +40,7 @@ class UploadWorkDirFiles(ApiHandler):
|
||||
},
|
||||
)
|
||||
|
||||
# result = browser.get_files(current_path)
|
||||
result = await runtime.call_development_function(get_work_dir_files.get_files, current_path)
|
||||
result = await get_work_dir_files.get_files(current_path)
|
||||
|
||||
return {
|
||||
"message": (
|
||||
@@ -57,22 +55,8 @@ class UploadWorkDirFiles(ApiHandler):
|
||||
|
||||
|
||||
async def upload_files(uploaded_files: list[FileStorage], current_path: str):
|
||||
if runtime.is_development():
|
||||
successful = []
|
||||
failed = []
|
||||
for file in uploaded_files:
|
||||
base64_content = await asyncio.to_thread(FileBrowser.encode_upload, file)
|
||||
if await runtime.call_development_function(
|
||||
upload_file, current_path, file.filename, base64_content
|
||||
):
|
||||
successful.append(file.filename)
|
||||
else:
|
||||
failed.append(file.filename)
|
||||
else:
|
||||
browser = FileBrowser()
|
||||
successful, failed = await asyncio.to_thread(browser.save_files, uploaded_files, current_path)
|
||||
|
||||
return successful, failed
|
||||
browser = FileBrowser()
|
||||
return await asyncio.to_thread(browser.save_files, uploaded_files, current_path)
|
||||
|
||||
|
||||
async def upload_file(current_path: str, filename: str, base64_content: str):
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
|
||||
Authenticated, CSRF-protected multipart uploads accept `files[]` and `path`. Delegate local/remote streaming, size enforcement, and atomic writes to FileBrowser; do not inspect a private size checker or duplicate policy in this endpoint. The endpoint maps plain `FileLimitExceeded` to a 413 response without changing ApiHandler. Successful changes still emit `workdir_file_mutation_after` and refresh the listing.
|
||||
|
||||
Production blocking file/provider I/O runs in a worker thread. Development RFC uses the FileBrowser-owned bounded encoding adapter. Failed local writes preserve existing files; partial batch failures retain the successful/failed filename response fields.
|
||||
Blocking file/provider I/O runs in a worker thread in both development and production, with no base64 roundtrip. The async `upload_file` base64 entry point remains available for compatibility. Failed local writes preserve existing files; partial batch failures retain the successful/failed filename response fields.
|
||||
|
||||
Verify multipart boundaries, atomic preservation, remote provider uploads and mutation notifications.
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
- `base/` owns the base image context.
|
||||
- `run/` owns the runnable image context and compose file.
|
||||
- `sandbox/` owns the Python and Node image used inside gVisor sandboxes.
|
||||
- Root `DockerfileLocal` is owned by the root contract but must stay compatible with this directory.
|
||||
|
||||
## Local Contracts
|
||||
@@ -40,3 +41,4 @@ Direct child DOX files:
|
||||
| --- | --- |
|
||||
| [base/AGENTS.md](base/AGENTS.md) | Base image Dockerfile, copied filesystem, and installation scripts. |
|
||||
| [run/AGENTS.md](run/AGENTS.md) | Runnable image Dockerfile, compose example, entrypoints, and install scripts. |
|
||||
| [sandbox/AGENTS.md](sandbox/AGENTS.md) | Sandbox image with global Python, IPython, Node.js and npm. |
|
||||
@@ -19,13 +19,15 @@
|
||||
- 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 `runsc` plus its Sentry, Sentry prewarmer, proc umounter and file-descriptor parking sidecars 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.
|
||||
- Seed CPU Torch/Torchvision with `numpy<2` and `filelock>=3.20.3,<4`, matching the application graph so Depfix can retain CPU selections during its bulk solve.
|
||||
- Pin the global Depfix bootstrap to the application requirement so cached package planning preserves requested extras.
|
||||
- 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.
|
||||
- Copy daemonless `skopeo` and `umoci` plus `/etc/containers` and `/usr/share/containers` defaults from the tool stage. Install their shared libraries and GPG explicitly; do not inherit Debian's unused CNI/network-stack dependency. Verify registry copy, OCI unpack and rootless use after changing this boundary.
|
||||
- Keep pip, uv and IPython for dependency installation and explicit local execution, and pipx for launching configured MCP servers. Pin pipx to 1.16.7 until newer releases support the framework's filelock/packaging bounds.
|
||||
- Use `uv pip install --no-cache` so temporary wheels/build artifacts are removed in the installing layer; installed packages and embedding model assets remain intact.
|
||||
- Keep compilers, Make, CMake and development headers out of the outer runtime. Native builds belong in disposable build stages or requesting plugin sandboxes. Preserve `libstdc++6` and `libatomic1` for Node/native runtime loading.
|
||||
- Do not preinstall unused wget/unzip or ALSA libraries. Keep curl and 7-Zip, which serve runtime downloads and archive extraction.
|
||||
- Disable implicit Python bytecode generation before installation/preload, and pass `--no-compile` to pip; runtime services already run without writing bytecode.
|
||||
- The runnable image bundles the default sandbox OCI layout; writable sandbox roots and image-cache lifecycle remain owned by `plugins/_sandboxing/`.
|
||||
- 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.
|
||||
- Do not install Tesseract, OCR language packs, or Poppler in the base image; `plugins/_document_query/` installs those system packages inside its sandbox 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.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# unbundled npm dependency tree.
|
||||
FROM node:22-trixie-slim AS node-runtime
|
||||
|
||||
# Install the signed gVisor package outside the final image. Current gVisor
|
||||
# Install the signed gVisor package and OCI tools 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
|
||||
@@ -15,7 +15,7 @@ RUN apt-get update \
|
||||
&& 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 \
|
||||
&& apt-get install -y --no-install-recommends runsc skopeo umoci \
|
||||
&& test -x /usr/bin/runsc \
|
||||
&& test -x /usr/bin/gvisor-bin/gvisor_sentry \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
@@ -25,12 +25,17 @@ FROM python:3.12-slim-trixie AS runtime
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ENV UV_SYSTEM_PYTHON=1 \
|
||||
PIP_ROOT_USER_ACTION=ignore
|
||||
PIP_ROOT_USER_ACTION=ignore \
|
||||
PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
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
|
||||
# Skopeo uses registry configuration and shared libraries, not Debian's CNI stack.
|
||||
COPY --from=gvisor-package /usr/bin/skopeo /usr/bin/umoci /usr/bin/
|
||||
COPY --from=gvisor-package /etc/containers/ /etc/containers/
|
||||
COPY --from=gvisor-package /usr/share/containers/ /usr/share/containers/
|
||||
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
|
||||
|
||||
|
||||
@@ -6,8 +6,7 @@ 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 \
|
||||
build-essential cmake
|
||||
sudo curl git cron 7zip libstdc++6 libatomic1
|
||||
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ echo "====================BASE PACKAGES2 START===================="
|
||||
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends \
|
||||
libasound2t64 openssh-server supervisor
|
||||
openssh-server supervisor
|
||||
|
||||
rm -rf /var/lib/apt/lists/* # for docker layers size
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ echo "====================BASE PACKAGES4 START===================="
|
||||
# sandboxing
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends \
|
||||
ca-certificates util-linux procps iproute2 skopeo umoci
|
||||
ca-certificates util-linux procps iproute2 gpg libgpgme11t64 libsqlite3-0
|
||||
|
||||
rm -rf /var/lib/apt/lists/* # for docker layers size
|
||||
|
||||
|
||||
@@ -7,21 +7,9 @@ apt-get update
|
||||
apt-get -y upgrade
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# The official Python image provides the global interpreter and pip.
|
||||
python -m pip install --no-cache-dir --upgrade \
|
||||
pip pipx ipython uv 'depfix==0.12.7'
|
||||
|
||||
# Install CPU-only variants before the application requirements are resolved.
|
||||
# Match the application's NumPy and LiteLLM/Filelock bounds so its bulk solve
|
||||
# can retain these CPU packages instead of dropping all installed preferences.
|
||||
depfix pip install torch torchvision 'numpy<2' 'filelock>=3.20.3,<4' \
|
||||
--index-url https://download.pytorch.org/whl/cpu
|
||||
|
||||
# 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
|
||||
# Newer pipx requires filelock/packaging versions incompatible with LiteLLM/LangChain.
|
||||
python -m pip install --no-cache-dir --no-compile --upgrade \
|
||||
pip ipython pipx==1.16.7 uv
|
||||
|
||||
# clean up pip cache
|
||||
python -m pip cache purge
|
||||
|
||||
+10
-6
@@ -20,12 +20,13 @@
|
||||
- Preserve exposed ports for SSH, HTTP, and tunneled services unless docs and workflows are updated together.
|
||||
- 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.
|
||||
- Run Supervisor's event listener with Debian's `/usr/bin/python3`, matching the apt-owned Supervisor package; application services still use the official global Python.
|
||||
- Install LibreOffice/UNO and GTK from the Debian trixie base repositories; retain compatible Xpra component pins from signed Xpra trixie. Do not cross-upgrade the official base from Kali/forky snapshots. Refresh Xpra through `plugins/_desktop/helpers/refresh_xpra_index.sh`; its signed compressed index preserves the ARM64 metadata workaround.
|
||||
- Build embedded Tuxee with `plugins/_desktop/build/` in a disposable stage, copying only its runtime and minimal VNC/window manager. Install that recipe's native runtime libraries in the outer image; no LibreOffice/UNO, Xfce, Xpra or Collabora belongs there. Browser mounts the shared `/usr/local/lib/tuxee-gui` bundle read-only in its sandbox and uses noVNC.
|
||||
- Do not bake secrets, local `.env` values, or user data into the image.
|
||||
- Install `libsndfile1` for the selected platform-neutral SoundFile wheel and embedding/audio imports.
|
||||
- The consolidated root requirements include SoundFile for WAV test fixtures; supported wheels bundle its audio library. Speech runtimes remain in their guests; do not add outer APT audio packages for test tooling.
|
||||
- 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 a separate tunnel API service. The Remote Control plugin starts its provider inside a standalone sandbox on demand; startup migration removes legacy Supervisor entries on source updates.
|
||||
- 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.
|
||||
@@ -33,10 +34,13 @@
|
||||
- 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.
|
||||
- Install application requirements with `uv pip install --no-cache --python /usr/local/bin/python` in both installation passes; launch services directly with `/usr/local/bin/python`. Later overlay cache deletion cannot reclaim base layers.
|
||||
- Keep `PYTHONDONTWRITEBYTECODE=1` for services and their subprocesses: import-time bytecode events can expose a lock inversion between watchdog registration and event dispatch during startup.
|
||||
- The cache-busted final install reuses installed packages, prepares checksum-pinned default ONNX/tokenizer assets with a failing-on-error inference check, then runs embedding preload. Do not ship unused Torch weights or an outer training stack. Chromium, document parsing and speech assets install only in their plugin sandboxes on first use.
|
||||
- Patchright Python, its driver, Chromium and display runtime belong entirely to the Browser sandbox. Telegram aiogram, IMAP/Exchange packages and WhatsApp npm dependencies likewise install in their guests on demand. `install_playwright.sh` is a no-op compatibility entry point.
|
||||
- Images built with the retired shared dependency store require rebuilt base and runtime images; source-only self-update cannot supply missing global packages or replace image-owned launchers.
|
||||
- Both this Dockerfile and `DockerfileLocal` build the shared `docker/sandbox/install.sh` recipe and package its rootfs as an OCI layout at `/opt/agent-zero/sandbox-image`. Keep it outside `/a0` and `usr/` so mounts and source updates cannot hide it. Packaging uses a read-only build-stage mount, avoiding a second full rootfs layer. Do not add eager sandbox image setup to WebUI startup.
|
||||
- The bundled OCI layout is public image content: make its metadata and blobs readable by normal Linux users so rootless callers can reuse it without rebuilding.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
|
||||
+26
-4
@@ -1,5 +1,5 @@
|
||||
# Use the pre-built base image for A0
|
||||
FROM agent-zero-base:local
|
||||
FROM agent-zero-base:local AS application
|
||||
# FROM agent0ai/agent-zero-base:testing
|
||||
# FROM agent0ai/agent-zero-base:latest
|
||||
|
||||
@@ -14,13 +14,13 @@ COPY ./fs/ /
|
||||
# pre installation steps
|
||||
RUN bash /ins/pre_install.sh $BRANCH
|
||||
|
||||
# Prime the Depfix store from the currently cached branch snapshot.
|
||||
# Install Python dependencies from the currently cached branch snapshot.
|
||||
RUN bash /ins/install_A0.sh $BRANCH
|
||||
|
||||
# install additional software
|
||||
RUN bash /ins/install_additional.sh $BRANCH
|
||||
|
||||
# Refresh the branch through the cache buster, reuse exact Depfix packages, and
|
||||
# Refresh the branch through the cache buster, reuse installed Python 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
|
||||
@@ -31,7 +31,29 @@ 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_tunnel_api.sh /exe/trigger_self_update.sh
|
||||
RUN chmod +x /exe/initialize.sh /exe/run_A0.sh /exe/trigger_self_update.sh
|
||||
|
||||
# shortcut: import bytecode events can deadlock startup watchers; remove after fixing their lock ordering.
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
# initialize runtime and switch to supervisord
|
||||
CMD ["/exe/initialize.sh", "$BRANCH"]
|
||||
|
||||
FROM node:22-bookworm-slim AS sandbox-node
|
||||
FROM python:3.13-slim-bookworm AS sandbox-rootfs
|
||||
COPY --from=application /git/agent-zero/docker/sandbox/install.sh /tmp/install-sandbox.sh
|
||||
RUN --mount=type=bind,from=sandbox-node,source=/usr/local,target=/node \
|
||||
sh /tmp/install-sandbox.sh && rm /tmp/install-sandbox.sh
|
||||
|
||||
FROM node:22-bookworm-slim AS tuxee-build
|
||||
COPY --from=application /git/agent-zero/plugins/_desktop/build /recipe
|
||||
RUN sh /recipe/build.sh /output
|
||||
|
||||
FROM application
|
||||
COPY --from=tuxee-build /output/ /
|
||||
ARG TARGETARCH
|
||||
# Store the OCI bundle outside /a0 and usr so source/user mounts cannot hide it.
|
||||
RUN --mount=type=bind,from=sandbox-rootfs,target=/sandbox \
|
||||
cd /git/agent-zero && /usr/local/bin/python -m plugins._sandboxing.helpers.builtin_image \
|
||||
--rootfs /sandbox --output /opt/agent-zero/sandbox-image --architecture "$TARGETARCH" && \
|
||||
chmod -R a+rX /opt/agent-zero/sandbox-image
|
||||
@@ -57,20 +57,6 @@ startretries=3
|
||||
stopasgroup=true
|
||||
killasgroup=true
|
||||
|
||||
[program:run_tunnel_api]
|
||||
command=/exe/run_tunnel_api.sh
|
||||
environment=
|
||||
user=root
|
||||
stopwaitsecs=60
|
||||
stdout_logfile=/dev/stdout
|
||||
stdout_logfile_maxbytes=0
|
||||
stderr_logfile=/dev/stderr
|
||||
stderr_logfile_maxbytes=0
|
||||
autorestart=true
|
||||
startretries=3
|
||||
stopasgroup=true
|
||||
killasgroup=true
|
||||
|
||||
[eventlistener:the_listener]
|
||||
command=/usr/bin/python3 /exe/supervisor_event_listener.py
|
||||
events=PROCESS_STATE_FATAL
|
||||
|
||||
@@ -4,4 +4,4 @@
|
||||
|
||||
echo "Starting A0 bootstrap manager..."
|
||||
cd /a0
|
||||
exec depfix run /exe/self_update_manager.py docker-run-ui
|
||||
exec /usr/local/bin/python /exe/self_update_manager.py docker-run-ui
|
||||
@@ -1,17 +1,3 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Wait until run_tunnel.py exists
|
||||
echo "Starting tunnel API..."
|
||||
|
||||
sleep 1
|
||||
while [ ! -f /a0/run_tunnel.py ]; do
|
||||
echo "Waiting for /a0/run_tunnel.py to be available..."
|
||||
sleep 1
|
||||
done
|
||||
|
||||
cd /a0
|
||||
exec depfix run /a0/run_tunnel.py \
|
||||
--dockerized=true \
|
||||
--port=80 \
|
||||
--tunnel_api_port=55520 \
|
||||
--host="0.0.0.0"
|
||||
#!/bin/sh
|
||||
# Legacy image compatibility; startup migration removes this service.
|
||||
exec sleep infinity
|
||||
@@ -923,8 +923,6 @@ def restore_git_state(
|
||||
|
||||
|
||||
def launch_ui_process(repo_dir: Path, logger: AttemptLogger) -> subprocess.Popen[bytes]:
|
||||
run_office_cleanup_hook(repo_dir, logger)
|
||||
|
||||
prepare_script = repo_dir / "prepare.py"
|
||||
if prepare_script.exists():
|
||||
logger.log("Running prepare.py before UI start")
|
||||
@@ -945,31 +943,6 @@ def launch_ui_process(repo_dir: Path, logger: AttemptLogger) -> subprocess.Popen
|
||||
)
|
||||
|
||||
|
||||
def run_office_cleanup_hook(repo_dir: Path, logger: AttemptLogger) -> None:
|
||||
hook_path = repo_dir / "plugins" / "_office" / "hooks.py"
|
||||
if not hook_path.exists():
|
||||
return
|
||||
try:
|
||||
if str(repo_dir) not in sys.path:
|
||||
sys.path.insert(0, str(repo_dir))
|
||||
spec = importlib.util.spec_from_file_location("a0_office_hooks", hook_path)
|
||||
if spec is None or spec.loader is None:
|
||||
logger.log("Office cleanup hook could not be loaded.")
|
||||
return
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
cleanup = getattr(module, "cleanup_stale_runtime_state", None)
|
||||
if not callable(cleanup):
|
||||
return
|
||||
result = cleanup()
|
||||
if isinstance(result, dict) and result.get("errors"):
|
||||
logger.log(f"Office cleanup hook reported errors: {result.get('errors')}")
|
||||
else:
|
||||
logger.log("Office cleanup hook completed.")
|
||||
except Exception as exc:
|
||||
logger.log(f"Office cleanup hook skipped after error: {exc}")
|
||||
|
||||
|
||||
def wait_for_health(
|
||||
process: subprocess.Popen[bytes],
|
||||
*,
|
||||
|
||||
@@ -4,4 +4,4 @@ set -eu
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
|
||||
cd /a0
|
||||
exec depfix run "$SCRIPT_DIR/self_update_manager.py" trigger-update "$@"
|
||||
exec /usr/local/bin/python "$SCRIPT_DIR/self_update_manager.py" trigger-update "$@"
|
||||
@@ -26,5 +26,5 @@ else
|
||||
}
|
||||
fi
|
||||
|
||||
# Materialize the complete application dependency graph in Depfix's shared store.
|
||||
depfix pip install -r /git/agent-zero/requirements.txt
|
||||
# Install application dependencies into the framework's global Python environment.
|
||||
uv pip install --no-cache --python /usr/local/bin/python -r /git/agent-zero/requirements.txt
|
||||
@@ -8,8 +8,8 @@ if [ "$1" != "local" ]; then
|
||||
rm -rf /git/agent-zero
|
||||
fi
|
||||
|
||||
# Refresh the branch and re-resolve once against the already populated Depfix
|
||||
# store. Runtime assets are deliberately installed only on this final pass.
|
||||
# Refresh the branch and reuse installed packages. Runtime assets are
|
||||
# deliberately installed only on this final pass.
|
||||
bash /ins/install_A0.sh "$@"
|
||||
bash /ins/install_playwright.sh "$@"
|
||||
depfix run /git/agent-zero/preload.py --dockerized=true
|
||||
(cd /git/agent-zero && /usr/local/bin/python -m helpers.local_embeddings)
|
||||
/usr/local/bin/python /git/agent-zero/preload.py --dockerized=true
|
||||
@@ -1,77 +1,6 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
if ! command -v apt-get >/dev/null 2>&1; then
|
||||
echo "apt-get unavailable; skipping LibreOffice install"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
XPRA_VERSION="6.5.2-r0-1"
|
||||
arch="$(dpkg --print-architecture)"
|
||||
|
||||
XPRA_HTML5_VERSION="19-r1-1"
|
||||
if [ "$arch" = "arm64" ]; then
|
||||
XPRA_HTML5_VERSION="21-r1-1"
|
||||
fi
|
||||
|
||||
LIBREOFFICE_PACKAGES=(
|
||||
"libreoffice-core"
|
||||
"libreoffice-writer"
|
||||
"libreoffice-calc"
|
||||
"libreoffice-impress"
|
||||
"libreoffice-gtk3"
|
||||
"python3-uno"
|
||||
)
|
||||
XPRA_PACKAGES=(
|
||||
"xpra-common=$XPRA_VERSION"
|
||||
"xpra-server=$XPRA_VERSION"
|
||||
"xpra-client=$XPRA_VERSION"
|
||||
"xpra-client-gtk3=$XPRA_VERSION"
|
||||
"xpra-x11=$XPRA_VERSION"
|
||||
"xpra-html5=$XPRA_HTML5_VERSION"
|
||||
)
|
||||
|
||||
# Match the official Debian base; do not cross-upgrade it from a rolling snapshot.
|
||||
set -eu
|
||||
apt-get update
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ca-certificates wget libsndfile1
|
||||
wget -O /usr/share/keyrings/xpra.asc https://xpra.org/xpra.asc
|
||||
cat >/etc/apt/sources.list.d/xpra.sources <<EOF
|
||||
Types: deb
|
||||
URIs: https://xpra.org
|
||||
Suites: trixie
|
||||
Components: main
|
||||
Signed-By: /usr/share/keyrings/xpra.asc
|
||||
Architectures: $arch
|
||||
EOF
|
||||
bash /git/agent-zero/plugins/_desktop/helpers/refresh_xpra_index.sh /etc/apt/sources.list.d/xpra.sources
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --allow-downgrades \
|
||||
gir1.2-atk-1.0 \
|
||||
gir1.2-gtk-3.0 \
|
||||
"${LIBREOFFICE_PACKAGES[@]}" \
|
||||
"${XPRA_PACKAGES[@]}" \
|
||||
xfce4-session \
|
||||
xfwm4 \
|
||||
xfce4-panel \
|
||||
xfdesktop4 \
|
||||
xfce4-settings \
|
||||
thunar \
|
||||
gvfs \
|
||||
libglib2.0-bin \
|
||||
xfce4-terminal \
|
||||
x11-xserver-utils \
|
||||
x11-utils \
|
||||
x11-apps \
|
||||
xdotool \
|
||||
xclip \
|
||||
xauth \
|
||||
xvfb \
|
||||
dbus-x11 \
|
||||
fonts-dejavu \
|
||||
fonts-liberation \
|
||||
fonts-crosextra-caladea \
|
||||
fonts-crosextra-carlito \
|
||||
fonts-noto-core \
|
||||
fonts-noto-cjk \
|
||||
fonts-noto-color-emoji
|
||||
|
||||
mapfile -t packages < /git/agent-zero/plugins/_desktop/build/runtime-packages.txt
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "${packages[@]}"
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
@@ -1,15 +1,3 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# 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"
|
||||
|
||||
# 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
|
||||
#!/bin/sh
|
||||
# Compatibility entry point: Browser installs Chromium inside its sandbox on first use.
|
||||
set -eu
|
||||
@@ -0,0 +1,35 @@
|
||||
# Sandbox Image DOX
|
||||
|
||||
## Purpose
|
||||
|
||||
- Own the small OCI image used for agent code execution inside gVisor.
|
||||
|
||||
## Ownership
|
||||
|
||||
- `install.sh` owns Python/IPython and Node/npm setup and runtime checks, shared by Docker builds and the lazy gVisor builder.
|
||||
- `Dockerfile` builds the standalone image from matching official Python and Node images.
|
||||
- `README.md` owns default-image delivery, recovery and optional standalone builds.
|
||||
|
||||
## Local Contracts
|
||||
|
||||
- Use official Python and Node images with the same Debian release.
|
||||
- Keep Python and pip in the global `/usr/local` environment; do not create a venv.
|
||||
- Include IPython for the existing Python code execution tool, and npm/npx for Node.
|
||||
- Keep shared-library dependencies needed by Node on both amd64 and arm64.
|
||||
- Do not copy Agent Zero source, credentials, user data, or the framework's dependencies into this image.
|
||||
- Image selection, digest pinning, unpacking and lifecycle belong to `plugins/_sandboxing/`.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
- Keep project-specific libraries out of the base; install them in the sandbox as needed.
|
||||
- The built-in reference is `agent-zero-sandbox:1`; bump its recipe version deliberately when changing the runtime contract. It is resolved locally, not pulled from Docker Hub.
|
||||
- Keep the Python and Node base references in both outer Dockerfiles and `plugins/_sandboxing/helpers/builtin_image.py` synchronized.
|
||||
|
||||
## Verification
|
||||
|
||||
- Build `docker/sandbox`; its build checks verify global Python and each command.
|
||||
- Exercise Python/IPython, global pip installation, Node and npm inside a real gVisor sandbox.
|
||||
|
||||
## Child DOX Index
|
||||
|
||||
No child DOX files.
|
||||
@@ -0,0 +1,12 @@
|
||||
FROM node:22-bookworm-slim AS node-runtime
|
||||
FROM python:3.13-slim-bookworm
|
||||
|
||||
ENV PIP_ROOT_USER_ACTION=ignore
|
||||
|
||||
COPY install.sh /tmp/install-sandbox.sh
|
||||
RUN --mount=type=bind,from=node-runtime,source=/usr/local,target=/node \
|
||||
sh /tmp/install-sandbox.sh && rm /tmp/install-sandbox.sh
|
||||
|
||||
WORKDIR /workspace
|
||||
|
||||
CMD ["/bin/bash"]
|
||||
@@ -0,0 +1,55 @@
|
||||
# Python and Node sandbox image
|
||||
|
||||
This image provides Python 3.13, pip and IPython in the global Python environment,
|
||||
plus Node.js 22, npm and npx. Both official runtime images use Debian Bookworm.
|
||||
It contains no Agent Zero framework dependencies or user data.
|
||||
|
||||
`agent-zero-sandbox:1` is the default for new sandboxes. Both Agent Zero Docker
|
||||
builds include an OCI bundle at `/opt/agent-zero/sandbox-image`, outside the
|
||||
source and user-data mounts. No registry publication or manual import is needed.
|
||||
The first sandbox creation unpacks that bundle into the normal disk cache,
|
||||
without network access. Later starts reuse the cached image and private files.
|
||||
|
||||
If the bundle is absent or damaged (including native installs and older Docker
|
||||
images), the sandbox manager builds it on first use in a temporary gVisor
|
||||
sandbox. It pulls the official Python and Node images and runs `install.sh`,
|
||||
the same recipe used by Docker builds. This needs internet access and working
|
||||
`runsc`, `skopeo` and `umoci`; host Python packages remain untouched. Builds are
|
||||
serialized and cached, and never run as part of ordinary WebUI startup.
|
||||
Existing sandboxes retain their pinned digest and explicit image settings are
|
||||
preserved. Rebuilding cannot substitute a different digest for a lost pinned
|
||||
base; preserve the image cache with your sandbox backups.
|
||||
|
||||
An optional standalone image can be built from the repository root:
|
||||
|
||||
```sh
|
||||
docker build -t agent-zero-sandbox:local docker/sandbox
|
||||
docker run --rm agent-zero-sandbox:local python -c 'import sys; assert sys.prefix == sys.base_prefix'
|
||||
docker run --rm agent-zero-sandbox:local node --version
|
||||
docker run --rm agent-zero-sandbox:local npm --version
|
||||
```
|
||||
|
||||
`python -m pip install ...` installs globally inside the sandbox. Node projects
|
||||
can use `npm install` normally. Each sandbox owns its writable filesystem, so
|
||||
these installations do not modify the cached base image or other sandboxes.
|
||||
|
||||
To try a separately modified local image, import it into an Agent Zero container
|
||||
(replace `YOUR_A0_CONTAINER`):
|
||||
|
||||
```sh
|
||||
docker save -o /tmp/agent-zero-sandbox.tar agent-zero-sandbox:local
|
||||
docker cp /tmp/agent-zero-sandbox.tar YOUR_A0_CONTAINER:/tmp/agent-zero-sandbox.tar
|
||||
docker exec -w /a0 YOUR_A0_CONTAINER /usr/local/bin/python -m helpers.sandbox \
|
||||
import-image /tmp/agent-zero-sandbox.tar agent-zero-sandbox:local
|
||||
```
|
||||
|
||||
Set **Sandboxing → Default image** to `agent-zero-sandbox:local`. Native
|
||||
installations can run the same Python command directly with the archive path.
|
||||
The loader uses Skopeo and umoci; Agent Zero never needs a Docker socket.
|
||||
The imported image stays in the normal disk cache and remains protected while
|
||||
any sandbox references it. Reimport after manually deleting the cached image
|
||||
or after unused-image expiry. Importing a rebuilt image under the same reference
|
||||
changes the base for new sandboxes; existing sandboxes retain their pinned image.
|
||||
|
||||
Other custom images can also be published to a registry and selected in
|
||||
Sandboxing settings. The built-in default needs no separate registry image.
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
# /node is the official Node image's read-only /usr/local directory.
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends libstdc++6 libatomic1
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
cp /node/bin/node /usr/local/bin/node
|
||||
cp -a /node/lib/node_modules /usr/local/lib/
|
||||
ln -sf ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm
|
||||
ln -sf ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx
|
||||
PIP_ROOT_USER_ACTION=ignore python -m pip install --no-cache-dir 'ipython==9.18.1'
|
||||
mkdir -p /workspace
|
||||
|
||||
python -c 'import sys; assert sys.prefix == sys.base_prefix'
|
||||
python -m pip check
|
||||
ipython --version
|
||||
node --version
|
||||
npm --version
|
||||
npx --version
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
- `guides/local-folders.md` owns Docker bind-mount examples and persistence guidance; `guides/launcher.md#workspace-storage` owns Launcher storage choices and folder mappings.
|
||||
- `guides/opencode.md` owns the fresh-instance OpenCode Go provider-plugin journey, with real captures under `res/usage/opencode/`. Onboarding shares its model-gate image. Keep model IDs tied to the provider's current catalog and distinguish verified setup from untested model responses.
|
||||
- `guides/codex.md` owns ChatGPT device-code permission, Codex account sign-in, Main/Utility selection and continuation in the original chat. Its real captures under `res/usage/codex/` must hide account identities and device codes; reuse the current onboarding-ready capture. Link it from the README, docs index and Onboarding.
|
||||
- `developer/` covers compact developer references and source handoffs.
|
||||
- `developer/` covers compact developer references. `developer/plugin-sandboxes.md` owns plugin worker integration; runtime prerequisites and Linux smoke checks live in `plugins/_sandboxing/README.md`.
|
||||
- `plans/` covers implementation plans, migration notes, and staged technical roadmaps.
|
||||
- `res/` contains documentation images and other documentation assets.
|
||||
- `guides/migrate-agents.md` owns the real Pi, Hermes and Claude Code CLI export, preview, import, file-copy and continuation journeys, with neutral captures under `res/usage/migration/`; source-format and parser contracts stay in the bundled Migrate Agents plugin. The migration and usage guides share the sidebar message-search capture and describe its loaded-conversation/filter limits.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Local ONNX embeddings
|
||||
|
||||
The bundled `huggingface / sentence-transformers/all-MiniLM-L6-v2` model runs on
|
||||
CPU using ONNX Runtime. Its provider, model name, cache namespace and index
|
||||
metadata remain unchanged. The pinned revision is
|
||||
`1110a243fdf4706b3f48f1d95db1a4f5529b4d41`; the full-precision upstream ONNX graph
|
||||
matches the previously bundled safetensors weights. No quantization is used.
|
||||
|
||||
The pipeline retains the exact tokenizer, 256-token truncation including special
|
||||
tokens, attention-mask mean pooling, model-defined L2 normalization, float32 and
|
||||
384 dimensions. There are no query/document prefixes or extra encode-time
|
||||
normalization. Existing default-model databases require no reindexing.
|
||||
|
||||
Docker builds prepare and checksum-check the ONNX graph and tokenizer, and run
|
||||
an inference check. A fresh container can embed offline. Source/local setup is:
|
||||
|
||||
```sh
|
||||
python -m pip install -r requirements.txt
|
||||
python -m helpers.local_embeddings
|
||||
```
|
||||
|
||||
The explicit preparation command first runs the existing legacy model-settings
|
||||
migration (preserving backups), then can download missing public model assets;
|
||||
embedding requests never do. Preparation covers the global configuration and all
|
||||
saved presets and persisted raw chat overrides using the bundled model, including
|
||||
project and agent-profile selections. Each selection retains its resolved `cache_folder` and
|
||||
`use_auth_token`, including Default inheritance. Configure custom caches before
|
||||
running the command, and rerun it after adding or changing a cache location. Docker
|
||||
source upgrades prepare these caches after settings migration and preset
|
||||
initialization, preserving their old contents.
|
||||
`use_auth_token` retains its Hugging Face access meaning.
|
||||
|
||||
Only the bundled model/revision on CPU is validated. Other local models, a
|
||||
changed revision, GPU devices, remote model code and nonempty `model_kwargs`
|
||||
raise an actionable error without substituting a model or touching indexes.
|
||||
Additional architectures need their own parity validation before support can be
|
||||
claimed. Remote embeddings and local server providers such as Ollama still use
|
||||
the existing provider dispatch. Changing embedding models through settings keeps
|
||||
the existing model-change/reindex behavior.
|
||||
|
||||
A source update installs ONNX Runtime and prepares missing assets before startup
|
||||
continues. It conservatively retains the previous training packages and cached
|
||||
weights for private plugins and source rollback. Their implicit availability is
|
||||
absent in new images; custom consumers must declare and install their own
|
||||
requirements in their intended runtime. Rebuild both base and application images
|
||||
to remove the old packages and reclaim their immutable layers. Speech/document
|
||||
worker dependencies remain in their existing guests.
|
||||
|
||||
The reproducible compatibility runner is `tests/integration_onnx_compatibility.py`.
|
||||
Run `old /tmp/onnx-compat` in the previous runtime, copy that synthetic fixture
|
||||
unchanged into the new runtime at the same path, then run `new /tmp/onnx-compat`
|
||||
and `restart /tmp/onnx-compat` in separate processes. It covers memory, unchanged
|
||||
knowledge import, Document Query indexes, raw vector/score/norm tolerance,
|
||||
ranking/thresholds, new inserts, sync/async batching and cache-bypass assertions.
|
||||
The accepted absolute tolerance is 0.000002; near ties within twice that tolerance
|
||||
may reorder. Empty strings are supported; an empty batch now returns an empty
|
||||
list (the old sentence-transformers version raised IndexError).
|
||||
@@ -0,0 +1,173 @@
|
||||
# Sandboxed plugin runtimes
|
||||
|
||||
Document Query, Whisper STT, Local TTS, Telegram, WhatsApp, mail and the internal Browser use the shared
|
||||
gVisor lifecycle manager. Their tools, settings and authenticated APIs stay in
|
||||
Agent Zero. Heavy execution and dependency installation happen in the guest.
|
||||
|
||||
## Choosing dependency location
|
||||
|
||||
Prefer these existing sandboxes for plugin-owned Python, Node and native packages,
|
||||
heavy inference, browser/document/media workers and external integration clients.
|
||||
Keep lightweight tools, hooks, configuration and authenticated API/UI adapters in
|
||||
the framework; they call the guest without importing guest-only libraries. Do not
|
||||
add optional guest packages to root requirements or global pip/npm/apt installs.
|
||||
Main-environment dependencies are appropriate only for functionality that must
|
||||
execute there: document the concrete reason in the plugin README and keep them
|
||||
minimal. Hooks still execute in the framework; worker sandboxing is not total
|
||||
plugin isolation, and host networking is not a network isolation boundary.
|
||||
|
||||
Use [`helpers.sandbox.get_manager()`](../../helpers/sandbox.py) for the configured,
|
||||
instance-scoped lifecycle rather than building another runtime. The bundled
|
||||
[`SandboxWorker`](../../helpers/sandbox_worker.py) provides blocking `call`, async
|
||||
`acall`, explicit `aprepare` and `stop`; construction alone does not provision.
|
||||
Its current source lookup is `plugins/<plugin>/`, so it is not a drop-in for custom
|
||||
plugins under `usr/plugins/`. For those, use the same manager with explicit
|
||||
`SandboxMount` source paths, plugin ownership, `service=True`, `share_usr=False`
|
||||
and child lifetime (`standalone=False`), following the worker's private input and
|
||||
bounded result handling. Mount only required plugin-owned or authorized data;
|
||||
preserve authentication, credential handling and user-data ownership.
|
||||
|
||||
Keep manifests/installers with the plugin and execute them inside its persistent
|
||||
guest. The [Document Query adapter](../../plugins/_document_query/helpers/sandbox.py)
|
||||
and [installer](../../plugins/_document_query/sandbox/install.sh) show the bundled
|
||||
pattern. The shared [worker boot script](../../plugins/_sandboxing/sandbox/boot.sh)
|
||||
uses `sandbox/install.sh` and `sandbox/requirements.txt`, fingerprints setup inputs
|
||||
and records success only after installation. Preserve idempotent setup, failure
|
||||
reporting and retry; stopping a guest retains its packages and model caches.
|
||||
|
||||
Install/update/uninstall remain owned by `hooks.py` and framework management APIs.
|
||||
Hooks may delegate guest provisioning to automatic worker setup on first actual
|
||||
use. Early-needed features and configured inbound listeners must instead prepare
|
||||
at enablement/startup before they are needed; do not wait for a message the
|
||||
unstarted receiver cannot receive. Respect disabled state. Disable stops owned
|
||||
workers; uninstall removes owned sandboxes/resources while preserving shared
|
||||
dependencies and unrelated or separately mounted user data. Never require
|
||||
`execute.py` or a user-run post-install command.
|
||||
|
||||
Developer/reviewer check: optional guest dependencies stay out of main requirements
|
||||
and feature import/general boot paths do not eagerly install them. Verify first-use
|
||||
setup/retry, required enablement/startup readiness and owned cleanup. Lazy provisioning
|
||||
reduces the shipped/default footprint, but may not reduce total disk after use.
|
||||
|
||||
## Existing runtime behavior
|
||||
|
||||
| Runtime | Starts | Stops | Persistent files |
|
||||
| --- | --- | --- | --- |
|
||||
| Document parsing/OCR | First parse or PDF/HTML knowledge import | After the request | Packages and parser model caches |
|
||||
| Whisper STT | First transcription or explicit preload | After 120 seconds idle, disable or parent exit | Packages and Whisper models |
|
||||
| Paradee/Kokoro TTS | First synthesis or explicit preload | After 120 seconds idle, disable or parent exit | Packages and speech models |
|
||||
| Internal Browser | First browser use | Runtime shutdown, configuration change, disable or parent exit | Packages, Chromium, existing profile and downloads |
|
||||
| Telegram | Enabled bot job-loop startup or connection test | Disable, shutdown or transport recovery | Packages; configuration stays in A0 |
|
||||
| WhatsApp | Enabled job-loop startup or explicit pairing | Disable, shutdown or configuration change | Packages and mounted existing login/session/media directories |
|
||||
| Mail | Configured polling, connection test or send | After 120 seconds idle, disable or shutdown | Packages; UID checkpoints and configuration stay in A0 |
|
||||
|
||||
All use child lifetime and instance-scoped service names. Configured inbound integrations start from their existing job-loop hooks on enablement/startup; disabled integrations do not provision. Other feature guests remain cold until needed. The tunnel separately uses standalone
|
||||
lifetime. Installation reuses the configured OCI image and prepares Python 3.12
|
||||
inside the guest for compatibility with existing package pins. These installers
|
||||
require a Debian-compatible image with Python and apt. Initial setup requires
|
||||
internet access and can take several minutes; later starts reuse the disk root.
|
||||
CPU Torch wheels are selected explicitly.
|
||||
|
||||
The shared `helpers.sandbox_worker.SandboxWorker` uses private, read-only request
|
||||
mounts and bounded result reads with symlink protection. Requests/results are
|
||||
cleared after acknowledgement. Cancellation and request errors stop the worker;
|
||||
setup has a separate 30-minute bound. No outer worker server or new listening
|
||||
port is introduced. Service sandboxes do not share the agent `/shared` exchange
|
||||
or Agent Zero's whole `usr/` directory. Network mode currently remains `host`,
|
||||
which permits both internet and host loopback access.
|
||||
|
||||
The browser exposes only its existing profile, downloads directory and selected
|
||||
extension directories. Uploads pass selected file bytes through Patchright;
|
||||
screenshots return through its normal protocol. The complete automation runtime (including Patchright Python and its Node driver) runs inside the guest. A browser-specific multiplexed pipe carries operations, frames and cancellation acknowledgements; no host browser SDK is imported. Tuxee’s minimal Xvnc remains on loopback behind the authenticated, token-scoped noVNC
|
||||
virtual-desktop gateway. Browser directory pickers see the guest filesystem;
|
||||
arbitrary host folders are not implicitly mounted.
|
||||
|
||||
`python -m helpers.sandbox list` lists these services alongside other instance
|
||||
sandboxes. Stop retains dependencies and models; delete removes the private
|
||||
disk root. Browser profile/download mounts remain owned by the browser and are
|
||||
not deleted with the sandbox. Uninstall removes the owned sandbox; disable stops it.
|
||||
|
||||
Fresh outer images omit Patchright/Playwright, their bundled drivers, optional
|
||||
transport packages (aiogram, IMAPClient, Exchange), WhatsApp node_modules and the
|
||||
retired Office/Xfce/Xpra stack. Shared memory/embedding libraries and the cached
|
||||
embedding model remain included. Office tools and separate Office tabs are absent.
|
||||
Editor retains the existing Office text/history store and backups without deleting
|
||||
the source. User documents, configurations, browser profiles and login state remain.
|
||||
|
||||
Desktop embeds the pinned Tuxee runtime directly in the outer image. Its native
|
||||
minimal VNC session and window manager use the existing Desktop panel, with HTTP
|
||||
and WebSockets proxied at `/desktop/tuxee/`. The internal listener binds to loopback;
|
||||
publish only the usual A0 WebUI port. A0 authentication and same-origin gating run
|
||||
before Tuxee's own PAM/session/CSRF checks. In the managed Docker runtime, Desktop
|
||||
automatically signs in as root when `ROOT_PASSWORD` is configured. The proxy keeps
|
||||
that shared session cookie in memory; the browser retains its normal CSRF checks.
|
||||
Other runtimes, missing credentials or failed login attempts show Tuxee's normal
|
||||
Linux login page. Failed automatic attempts retry after a 60-second cooldown on
|
||||
the next page load. Existing manual sessions take precedence. Explicit logout
|
||||
returns that browser to manual login for its browser session; other clients sharing
|
||||
the automatic session reconnect. This follows the existing A0 access policy,
|
||||
including instances with WebUI login unconfigured. The iframe retains its terminal
|
||||
when docked; Office applications are not installed.
|
||||
|
||||
Both supported image recipes build Tuxee from pinned, checksum-verified sources
|
||||
with a small relative-URL patch. The patch intentionally changes login public
|
||||
bytes to support the embedding prefix without bypassing authentication. Tuxee's
|
||||
in-app updater is disabled; its pinned version follows Agent Zero. Source-only
|
||||
upgrades build missing/stale Tuxee assets in a disposable sandbox on first Desktop
|
||||
use (administrator access and network required), publishing the binary after a
|
||||
successful build. The startup retirement migration uninstalls only replaced outer
|
||||
Python distributions and named installer caches. It defers native package/service
|
||||
retirement while old GUI processes may contain unsaved work, then retries on the
|
||||
next restart. Service declarations retain a reversible backup. Rebuild the image
|
||||
to reclaim immutable old layers. Existing speech model caches are preserved and
|
||||
may be downloaded again into the guests.
|
||||
|
||||
Guest installation failures leave no success marker; subsequent use retries.
|
||||
Stopping retains each private disk root, while disable hooks stop the corresponding
|
||||
workers. WhatsApp uses a per-process token on its loopback bridge; Telegram/mail
|
||||
carry credential input only in private transient IPC. Guest networking still uses
|
||||
host mode, so it is not a network isolation boundary. No live account or external
|
||||
message is needed for the fixture checks in `tests/integration_guest_smoke.py`.
|
||||
|
||||
These changes inherit the gVisor launch requirements in the
|
||||
[sandbox runtime guide](../../plugins/_sandboxing/README.md#gvisor-runtime). They do not establish compatibility with
|
||||
every Docker default seccomp profile.
|
||||
|
||||
## Python runtimes and image cleanup
|
||||
|
||||
The outer image has one global Python 3.12 environment for the framework, plugin
|
||||
hooks and explicit `local` code execution. There is no separate host code-execution
|
||||
venv or pyenv. Debian's Python 3.13 belongs to Supervisor and its event listener;
|
||||
it is not an alternative framework environment. Outer IPython and Node remain
|
||||
available for explicit local execution. SSH and connected-host destinations keep
|
||||
their existing routing; the default destination is the isolated sandbox.
|
||||
|
||||
The bundled sandbox base has global Python 3.13, IPython and Node. Feature guests
|
||||
also prepare Python 3.12 in `/opt/runtime` for their existing package pins; this
|
||||
venv points to a guest-owned uv-managed interpreter and does not reuse the host
|
||||
framework's site-packages. These isolated runtimes are intentional. Stopping a
|
||||
guest preserves its installed packages and model caches.
|
||||
|
||||
Base and both application installation passes disable uv's wheel/build cache,
|
||||
while preserving installed files and the included embedding model. New images
|
||||
omit Newspaper, jieba3k, pyreqwest-impersonate and the exclusive feed/parser
|
||||
dependencies. Framework HTML fetching uses HTTPX and document parsing uses the
|
||||
existing Document Query guest. Shared Pillow, lxml, BeautifulSoup, requests, YAML
|
||||
and NLTK (including its security floor) remain.
|
||||
|
||||
Custom plugins using these scraper libraries must declare/install them explicitly;
|
||||
implicit outer availability is no longer supported. Source-update retirement
|
||||
preserves packages required by other installed distributions, but cannot detect
|
||||
undeclared imports in user scripts. A rebuilt image is needed to reclaim old
|
||||
cache/dependency layers; a source-only update cannot shrink the underlying image.
|
||||
|
||||
The outer image does not include GCC/G++, Make, CMake, compiler development headers,
|
||||
wget, unzip or speech-device/audio-codec libraries. Native compilation
|
||||
belongs in a build stage or a plugin's install script inside its sandbox. Curl,
|
||||
7-Zip, IPython, Node, pipx (for MCP servers) and the native runtime libraries remain. Skopeo and Umoci
|
||||
are copied with their registry configuration and shared-library dependencies,
|
||||
without Debian's unused CNI network stack. Image builds also skip Python bytecode
|
||||
generation and omit Torch's native test runners while retaining its shared-memory
|
||||
manager. Existing installations retain their tools and user-installed packages;
|
||||
rebuild both base and application images to obtain these savings. Source-only
|
||||
updates do not automatically purge generic system tools or shared libraries.
|
||||
@@ -13,6 +13,7 @@ manual.
|
||||
| Goal | Start here |
|
||||
| --- | --- |
|
||||
| Build your first plugin | [Create a Small Plugin](../guides/create-plugin.md) |
|
||||
| Choose where plugin dependencies run | [Sandboxed plugin runtimes](plugin-sandboxes.md#choosing-dependency-location) |
|
||||
| Understand how plugins are loaded | [DeepWiki](https://deepwiki.com/agent0ai/agent-zero) |
|
||||
| Decide what is safe to publish | [Sharing and Safety](sharing-and-safety.md) |
|
||||
| Contribute a plugin upstream | [Contributing Guide](../guides/contribution.md) |
|
||||
@@ -40,6 +41,22 @@ version: 1.0.0
|
||||
Ask Agent Zero to keep the first version small. A tiny plugin that does one
|
||||
visible thing is easier to test, review, and share.
|
||||
|
||||
## Plugin Dependencies
|
||||
|
||||
Prefer existing sandbox/worker facilities for plugin-owned Python, Node and native
|
||||
packages, including inference, browser/document/media workers and integration
|
||||
clients. Keep lightweight tools, hooks, configuration and authenticated API/UI
|
||||
adapters in the framework and call the guest. Install in the main environment
|
||||
only when functionality must execute there; document that concrete need and keep
|
||||
the dependency set minimal. Hooks still run in the framework.
|
||||
|
||||
Lifecycle hooks and management APIs own setup and cleanup. They can delegate to
|
||||
automatic guest setup on first use, or at enablement/startup for features and
|
||||
listeners that need early readiness; no manual post-install step is required.
|
||||
Use the [sandbox guide](plugin-sandboxes.md#choosing-dependency-location) for the
|
||||
existing pattern. Lazy setup reduces the shipped/default dependency footprint,
|
||||
but may not reduce total disk usage after the feature is used.
|
||||
|
||||
## Sharing A Plugin
|
||||
|
||||
Before publishing a plugin:
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# Tunnel sandbox PoC
|
||||
|
||||
Remote Control now owns its UI, providers and installer in `plugins/_tunnel`.
|
||||
No outer tunnel API server is started. Its authenticated API forwards control
|
||||
to the shared sandbox manager; normal Agent Zero HTTP/WebSocket handling stays
|
||||
in place. Cloudflare runs as a native daemon in its sandbox.
|
||||
|
||||
## Shared Python interface
|
||||
|
||||
```python
|
||||
from helpers.sandbox import get_manager, SandboxMount
|
||||
from pathlib import Path
|
||||
|
||||
manager = get_manager()
|
||||
manager.create(
|
||||
"my-service",
|
||||
image="", # configured system image
|
||||
sandbox_type="permanent",
|
||||
standalone=True,
|
||||
service=True,
|
||||
share_usr=False,
|
||||
network="host",
|
||||
ownership={"plugin_id": "my-plugin"},
|
||||
mounts=[SandboxMount(Path("/absolute/plugin"), "/plugin", True)],
|
||||
command=["/bin/sh", "/plugin/boot.sh"],
|
||||
)
|
||||
manager.list()
|
||||
manager.stop("my-service")
|
||||
manager.start("my-service")
|
||||
manager.restart("my-service")
|
||||
manager.delete("my-service")
|
||||
```
|
||||
|
||||
The boot script runs an idempotent installer and then execs its service. Default
|
||||
image: `docker.io/library/python:3.13-slim-bookworm`; registry image overrides
|
||||
are supported. There is no Dockerfile builder: plugins supply installer scripts.
|
||||
|
||||
## CLI
|
||||
|
||||
Run from the Agent Zero checkout using its installed Python:
|
||||
|
||||
```sh
|
||||
python -m helpers.sandbox list
|
||||
python -m helpers.sandbox create demo --standalone
|
||||
python -m helpers.sandbox exec demo sh -c 'echo retained > /workspace/example'
|
||||
python -m helpers.sandbox restart demo
|
||||
python -m helpers.sandbox exec demo cat /workspace/example
|
||||
python -m helpers.sandbox stop demo
|
||||
python -m helpers.sandbox delete demo --yes
|
||||
```
|
||||
|
||||
Without `--standalone`, create/start/restart stay attached to the child. Closing
|
||||
the parent pipe terminates the guest, including on an abrupt parent exit.
|
||||
Standalone processes survive Agent Zero exits. On Docker/container or host
|
||||
restart, processes die; Agent Zero automatically restores standalone instances
|
||||
whose desired running state was not cleared by Stop.
|
||||
|
||||
## Files, networking and identity
|
||||
|
||||
New sandboxes have a writable disk root, copied from the cached image using
|
||||
reflinks where supported. Restart reuses it without tar snapshots or rebuilding.
|
||||
Temporary/permanent controls expiry, independently of child/standalone lifetime.
|
||||
|
||||
`/a0/usr` shares this installation's usr/ by default (`--no-usr` disables it).
|
||||
`--host-root` explicitly exposes the outer root at `/host`. In Docker these are
|
||||
container paths, not the desktop host's root. The tunnel opts out of usr sharing.
|
||||
|
||||
`--network host` is the default and provides internet and host loopback access.
|
||||
`--network none` is offline. Separate internet-only networking is not implemented.
|
||||
|
||||
The existing persistent runtime ID namespaces instance storage, runsc roots/IDs,
|
||||
and OCI annotations. Separate installations must have distinct persistent IDs.
|
||||
Service sandboxes are excluded from agent execution destinations and tool actions.
|
||||
|
||||
## Verification
|
||||
|
||||
Focused tests cover disk recovery without snapshots, instance separation,
|
||||
parent lifetimes, scoped mounts, bounded no-symlink status reads, plugin API
|
||||
protection, origin handling, providers and Supervisor retirement. The watcher
|
||||
regression reproduces an event arriving during registration; scheduling never
|
||||
holds the registry lock while waiting for watchdog's dispatch lock.
|
||||
|
||||
Live checks use a dedicated container with the existing gVisor PoC settings
|
||||
(`--init --security-opt no-new-privileges --security-opt seccomp=unconfined`).
|
||||
These settings remain necessary for this tested environment; this work does not
|
||||
establish compatibility with every default Docker seccomp profile. Run the same
|
||||
checks on another kernel/architecture before claiming support there.
|
||||
|
||||
The amd64 PoC passed a real Cloudflare connection through Agent Zero login,
|
||||
protected plugin API calls, invalid-CSRF rejection, and WebSockets. Disk writes
|
||||
survived abrupt Docker restart and the startup hook restored standalone services;
|
||||
child sandboxes remained stopped. A UID 1001 check also passed create, shared usr
|
||||
access, private disk writes, and restart. One warm lifecycle restart took 0.52 s.
|
||||
An active Cloudflare sandbox's two host processes accounted for approximately
|
||||
35 MiB PSS in one snapshot; the earlier idle Python controller measured 222 MiB.
|
||||
These are snapshots, not cross-platform resource guarantees.
|
||||
@@ -43,7 +43,7 @@ such as `-v /home/user/agent-zero-data:/a0/usr`, creates a **bind mount**.
|
||||
## Keep Agent Zero User Data In A Local Folder
|
||||
|
||||
Mount your dedicated data folder at **`/a0/usr`** to keep settings, chats,
|
||||
memory, projects, and custom plugins outside the container. The folder itself
|
||||
memory, application logs, projects, and custom plugins outside the container. The folder itself
|
||||
contains `settings.json`, `chats/`, and other user data; you do not need to add
|
||||
another `usr` folder inside it.
|
||||
|
||||
@@ -100,6 +100,21 @@ Compose resolves `./agent-zero-data` relative to the Compose file's directory.
|
||||
> upgrades. For a major version upgrade, follow the
|
||||
> [backup and restore instructions](../setup/installation.md#updating-from-v120-to-v20).
|
||||
|
||||
## Application Logs
|
||||
|
||||
Application print output is saved as UTF-8 plain text in `usr/logs` (Docker:
|
||||
`/a0/usr/logs`). Each process creates a unique `.log` file with a UTC timestamp
|
||||
in its name. Messages retain line breaks, blank lines, indentation and Unicode;
|
||||
console colors and HTML presentation are not written to these files. Existing
|
||||
secret masking applies. Chat history and its UI remain separate.
|
||||
|
||||
The directory is created automatically and is included in user-data mounts and
|
||||
backups. Logs are not rotated or automatically deleted; remove unneeded files
|
||||
when the instance is stopped. Older top-level `logs` folders are left intact,
|
||||
without conversion or automatic relocation. Back those up separately before
|
||||
replacing an older container. Docker service output remains available through
|
||||
`docker logs`; self-update and sandbox diagnostic logs keep their own locations.
|
||||
|
||||
## Share A Separate Work Folder
|
||||
|
||||
To let Agent Zero work on an existing folder without making it the entire user
|
||||
|
||||
+56
-49
@@ -11,7 +11,7 @@ This guide will show you how to setup a local development environment for Agent
|
||||
|
||||
> [!NOTE]
|
||||
> - Agent Zero runs in a Docker container, this simplifies installation and ensures unified environment and behavior across systems.
|
||||
> - Developing and debugging in a container would be complicated though, therefore we use a hybrid approach where the python framework runs on your machine (in VS Code for example) and only connects to a Dockerized instance when it needs to execute code or use other pre-installed functionality like the built-in search engine.
|
||||
> - The Python framework can also run on your machine in an IDE. File operations and scheduler jobs run in that local process. Code execution uses the selected local, SSH, connected-host or sandbox destination; it does not require a sibling Agent Zero instance for development RFC calls.
|
||||
|
||||
|
||||
## To follow this guide you will need:
|
||||
@@ -60,27 +60,43 @@ Now when you select one of the python files in the project, you should see prope
|
||||

|
||||

|
||||
|
||||
- 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.
|
||||
- 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, for example `(/home/user/agent-zero/.conda)`. This shows the environment is active in the terminal.
|
||||
|
||||

|
||||
|
||||
3. Install dependencies. Run these commands from the project root:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
PLAYWRIGHT_BROWSERS_PATH=./tmp/playwright patchright install chromium --no-shell
|
||||
python -m pip install -r requirements.txt
|
||||
python -m helpers.local_embeddings
|
||||
PLAYWRIGHT_BROWSERS_PATH=./tmp/playwright python -m patchright install chromium --no-shell
|
||||
```
|
||||
|
||||
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. 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.
|
||||
The second command downloads and verifies the pinned local embedding model for
|
||||
offline inference. Run it before starting the framework. If you configure a
|
||||
custom embedding `cache_folder`, rerun it after saving that setting so the same
|
||||
folder is prepared. See [Local ONNX embeddings](../developer/onnx-embeddings.md)
|
||||
for supported settings.
|
||||
|
||||
If you skip the second command, local development can still download Chromium on
|
||||
The third 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. Docker builds install
|
||||
`requirements.txt` into `/usr/local/bin/python`'s global environment and use
|
||||
that interpreter to install Chromium. Application startup uses installed
|
||||
packages directly, without activating a dependency graph.
|
||||
|
||||
Keep `PYTHONDONTWRITEBYTECODE=1` in the runtime environment, including IDE launch
|
||||
settings. Docker sets it automatically. This avoids import-time bytecode events
|
||||
triggering a known file-watcher deadlock during startup.
|
||||
|
||||
For images built with the retired shared dependency store, rebuild both the
|
||||
base and runtime images. A source-only self-update does not install all packages
|
||||
into global Python or replace the image's service launchers. Preserve the
|
||||
existing `usr/` volume when recreating the container.
|
||||
|
||||
If you skip the third command, local development can still download Chromium on
|
||||
first Browser use through `ensure_playwright_binary()` in
|
||||
`plugins/_browser/helpers/playwright.py`. Pre-installing avoids that wait.
|
||||
|
||||
@@ -91,7 +107,7 @@ Errors in the code editor caused by missing packages should now be gone. If not,
|
||||
|
||||
## Step 4: Run Agent Zero in the IDE
|
||||
Great work! Now you should be able to run Agent Zero from your IDE including real-time debugging.
|
||||
It will not be able to do code execution and few other features requiring the Docker container just yet, but most of the framework will already work.
|
||||
Local file operations and scheduler jobs work without another Agent Zero instance. Select the code execution destination explicitly as described below; sandboxed plugins provision their own runtimes.
|
||||
|
||||
1. The project is pre-configured for debugging. Go to Debugging tab, select "run_ui.py" and click the green play button (or press F5 by default). The configuration can be found at `.vscode/launch.json`.
|
||||
|
||||
@@ -101,12 +117,12 @@ The framework will run at the default port 5000. If you open `http://localhost:5
|
||||
|
||||
You can also set the bind host via `"--host=0.0.0.0"` (or `WEB_UI_HOST=0.0.0.0`).
|
||||
|
||||
It may take a while the first time. You should see output like the screenshot below. The RFC error is ok for now as we did not yet connect our local development to another instance in docker.
|
||||
It may take a while the first time. The screenshot below is from an older setup; its development RFC error is no longer part of the local startup workflow.
|
||||

|
||||
|
||||
|
||||
After inserting my API key in settings, my Agent Zero instance works. I can send a simple message and get a response.
|
||||
Some tools like code execution will not work yet because they need to be connected to a Dockerized instance.
|
||||
For code execution, configure the desired runtime as described below.
|
||||
|
||||

|
||||
|
||||
@@ -122,48 +138,39 @@ Some tools like code execution will not work yet because they need to be connect
|
||||

|
||||
|
||||
|
||||
## Step 5: Run another instance of Agent Zero in Docker
|
||||
- Some parts of A0 require standardized linux environment, additional web services and preinstalled binaries that would be unneccessarily complex to set up in a local environment.
|
||||
- To make development easier, we can use existing A0 instance in docker and forward some requests to be executed there using SSH and RFC (Remote Function Call).
|
||||
## Step 5: Choose the execution runtime
|
||||
|
||||
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 `/home/user/agent-zero`:
|
||||
File browsing, editing, image loading, attachment staging and scheduler jobs run
|
||||
locally in development. Stored `/a0` paths are development aliases for the local
|
||||
checkout where these operations resolve them; a second Agent Zero instance and
|
||||
an RFC password are not required.
|
||||
|
||||

|
||||

|
||||
Code execution destinations remain explicit:
|
||||
|
||||
- For the framework's own operating system, select `destination: local` and set
|
||||
**Code Execution** plugin `ssh_enabled` to `false`.
|
||||
- For isolation, use the configured sandbox destination. See the
|
||||
[sandbox guide](../../plugins/_sandboxing/README.md#gvisor-runtime) for runtime requirements.
|
||||
- For a connected host, use the authenticated Connector destination.
|
||||
- For SSH, use the configuration below. The plugin's `auto` setting still selects
|
||||
SSH when the framework is not Dockerized, so set it to `false` for local TTY use.
|
||||
|
||||
## Step 6: Configure SSH and RFC connection
|
||||
- The last step is to configure the local development (VS Code) instance and the dockerized instance to communicate with each other. This is very simple and can be done in the settings in the Web UI of both instances.
|
||||
- In my example the dark themed instance is the VS Code one, the light themed one is the dockerized instance.
|
||||
## Step 6: Configure optional SSH execution
|
||||
|
||||
1. Open the "Settings" page in the Web UI of your dockerized instance and go in the "Development" section.
|
||||
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 Debian GNU/Linux 13 (Trixie).
|
||||
An SSH target can be a host or a container with an SSH server. Configure the
|
||||
**Code Execution** plugin's `ssh_enabled`, `ssh_addr`, `ssh_port`, `ssh_user` and
|
||||
`ssh_pass` fields for that target. Set the address and credentials explicitly for
|
||||
a separate host; an empty `ssh_addr` retains the legacy `rfc_url` hostname fallback,
|
||||
and an empty `ssh_pass` reads the local instance's root password without RFC.
|
||||
|
||||
My Dockerized instance:
|
||||

|
||||
Configure a workdir that exists on the SSH target. Explicit SSH keeps that remote
|
||||
path; it does not use or create the developer's local checkout directory. Project
|
||||
workdirs retain their `/a0/...` paths on SSH, so they must also exist on the target.
|
||||
Local and remote filesystems are not automatically synchronized.
|
||||
|
||||
My VS Code instance:
|
||||

|
||||
|
||||
## RFC Notes (Host IDE + Docker Execution)
|
||||
Agent Zero runs code inside the container by default. If you are running the framework locally in your IDE but want tools (like code execution) to run in Docker, configure RFC in **Settings -> Development** and point it to a running Agent Zero container. This routes execution through SSH/RFC to the container while keeping the UI and agent loop on your host.
|
||||
|
||||
|
||||
# Congratulations!
|
||||
|
||||
You have successfully set up a complete Agent Zero development environment! You now have:
|
||||
|
||||
- A local development instance running in your IDE with full debugging capabilities
|
||||
- A dockerized instance for code execution and system operations
|
||||
- RFC and SSH communication between both instances
|
||||
- The ability to develop, debug, and test Agent Zero features seamlessly
|
||||
|
||||
You're now ready to contribute to Agent Zero, create custom extensions, or modify the framework to suit your needs. Happy coding!
|
||||
Test the selected destination with a terminal command such as `pwd` and `uname -a`.
|
||||
The legacy RFC settings and endpoints remain available for compatibility, but do
|
||||
not route ordinary development file operations or scheduler jobs.
|
||||
|
||||
|
||||
## Next steps
|
||||
|
||||
@@ -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 installs the Whisper, Kokoro, and `soundfile` Python dependencies. Whisper microphone audio is browser-normalized PCM, so the container does not require FFmpeg.
|
||||
- Whisper and Kokoro runtime dependencies install inside their plugin sandboxes on first use. Root `requirements.txt` also includes SoundFile for WAV test fixtures. Whisper microphone audio is browser-normalized PCM, so the outer container does not require FFmpeg or additional system audio packages.
|
||||
- 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.
|
||||
|
||||
@@ -131,7 +131,7 @@ A0_PATH="/opt/${A0_NAME}"
|
||||
mkdir -p ${A0_PATH}
|
||||
mkdir -p ${A0_PATH}/work_dir
|
||||
mkdir -p ${A0_PATH}/memory
|
||||
mkdir -p ${A0_PATH}/logs
|
||||
mkdir -p ${A0_PATH}/usr/logs
|
||||
```
|
||||
|
||||
### Step 2: Create Environment Configuration
|
||||
|
||||
@@ -13,13 +13,19 @@
|
||||
- Migrations must be safe to run repeatedly.
|
||||
- Preserve user data and create backups or reversible paths when changing durable state.
|
||||
- Keep long-running work bounded and observable.
|
||||
- `_05_framework_dependencies.py` applies the Depfix/LiteLLM/OpenAI pins and shared security floors from root `requirements.txt` on Docker startup. Already-current and non-Docker environments skip installation; failures stop startup. Extend its package scope when future core dependency changes need self-update installation.
|
||||
- `_05_framework_dependencies.py` applies the LiteLLM/OpenAI and ONNX/tokenizer/NumPy pins and shared security floors from root `requirements.txt` on Docker startup. Already-current and non-Docker environments skip installation; failures stop startup. Extend its package scope when future core dependency changes need self-update installation.
|
||||
- After changing framework packages, reuse `helpers.process.restart_process()` before serving requests so imported SDK modules are refreshed. Keep installation within 60 seconds to leave startup time within older self-updaters' health-check window; Git rollback does not restore Python packages.
|
||||
- `_21_onnx_embeddings.py` runs after model-config migration (`_10`) and preset bootstrap (`_20`), before preload/chat restoration. It prepares missing immutable ONNX assets in a bounded subprocess, verifies inference before returning, and stops startup on missing/corrupt assets or failed provisioning. Both checks and preparation cover the global configuration, all selectable saved presets and persisted raw chat overrides using their resolved cache/access options through `helpers.local_embeddings.configured_asset_options`; preserve existing cache contents. Ready images need no network. Source upgrades retain previous optional training packages and model cache for declared/private consumers and rollback; only rebuilt images remove this payload. No database/cache identity changes or reindexing belong here.
|
||||
- `_10_self_update_manager.py` may replace `/exe/self_update_manager.py` from the repository copy when the installed runtime updater is stale; it must validate required safety markers and keep a backup before replacement.
|
||||
- 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 through `depfix run` in the background so the fresh process can import application dependencies without needing a second restart.
|
||||
- After synchronizing a stale self-update manager, `_10_self_update_manager.py` starts that manager's best-effort Codex CLI refresh with `sys.executable` in the background.
|
||||
|
||||
- `_25_retire_tunnel_service.py` removes only the legacy run_tunnel_api Supervisor section, retains a backup, and rereads/updates Supervisor without restarting WebUI. Restore the config on failure so startup can retry.
|
||||
|
||||
- `_26_retire_outer_features.py` removes only retired outer Python distributions, browser installer caches and bundled WhatsApp node_modules. It preserves browser profiles, credentials, documents and Office/Editor history. Old active GUI applications defer native-package/service retirement to the next restart to protect unsaved work; Supervisor declaration changes retain a backup and restore on failure. Rebuilt images are required to reclaim lower image layers.
|
||||
- Scraper retirement covers Newspaper, pyreqwest-impersonate and their exclusive dependencies, preserving dependencies (including optional extras) declared by other installed distributions and their closure. It retains shared libraries/security floors. Custom plugins must declare their own scraper dependencies; undeclared implicit availability is no longer supported. Framework dependency upgrades disable uv caching; source updates cannot reclaim old cached image layers.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ from helpers.print_style import PrintStyle
|
||||
_REQUIREMENTS_FILE = Path(files.get_abs_path("requirements.txt"))
|
||||
_PACKAGES = {
|
||||
"litellm", "openai", "python-dotenv", "aiohttp", "anyio", "urllib3",
|
||||
"filelock", "fsspec", "multidict", "depfix",
|
||||
"filelock", "fsspec", "multidict", "onnxruntime", "tokenizers", "numpy", "huggingface-hub",
|
||||
}
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ class FrameworkDependencies(Extension):
|
||||
raise RuntimeError("Framework dependency update requires 'uv'.")
|
||||
PrintStyle.info("Updating framework dependencies:", ", ".join(outdated))
|
||||
subprocess.check_call(
|
||||
[uv, "pip", "install", "--python", sys.executable, *map(str, requirements)],
|
||||
[uv, "pip", "install", "--no-cache", "--python", sys.executable, *map(str, requirements)],
|
||||
timeout=60,
|
||||
)
|
||||
outdated = _outdated(requirements)
|
||||
|
||||
@@ -4,6 +4,7 @@ import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -97,7 +98,7 @@ def ensure_self_update_manager_runtime_current(
|
||||
def start_codex_cli_refresh(manager_path: Path | str) -> str:
|
||||
try:
|
||||
subprocess.Popen(
|
||||
["depfix", "run", str(manager_path), "refresh-codex"],
|
||||
[sys.executable, str(manager_path), "refresh-codex"],
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Provision assets after preset migration/bootstrap and before chat restoration."""
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from helpers import files, runtime
|
||||
from helpers.extension import Extension
|
||||
|
||||
|
||||
class OnnxEmbeddings(Extension):
|
||||
def execute(self, **kwargs):
|
||||
if not runtime.is_dockerized():
|
||||
return
|
||||
from huggingface_hub.errors import LocalEntryNotFoundError
|
||||
from helpers.local_embeddings import configured_asset_options, model_assets
|
||||
|
||||
options = configured_asset_options()
|
||||
try:
|
||||
for entry in options:
|
||||
model_assets(**entry)
|
||||
except LocalEntryNotFoundError:
|
||||
# A subprocess verifies the new runtime without stale imports from before _05.
|
||||
subprocess.run(
|
||||
[sys.executable, "-m", "helpers.local_embeddings"],
|
||||
cwd=files.get_base_dir(), check=True, timeout=180,
|
||||
)
|
||||
for entry in options:
|
||||
model_assets(**entry)
|
||||
# Keep old packages/cache on source upgrades for private consumers and rollback.
|
||||
# Rebuilt images omit the old stack without deleting anything from user installations.
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Retire the image-owned controller on source-only upgrades too."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
from helpers.extension import Extension
|
||||
from helpers import runtime
|
||||
|
||||
|
||||
class RetireTunnelController(Extension):
|
||||
def execute(self, **kwargs):
|
||||
if runtime.is_dockerized():
|
||||
retire()
|
||||
|
||||
|
||||
def retire(config: Path = Path('/etc/supervisor/conf.d/supervisord.conf')) -> bool:
|
||||
control = shutil.which('supervisorctl')
|
||||
if control is None or not config.is_file():
|
||||
return False
|
||||
original = config.read_text()
|
||||
pattern = r'(?ms)^\[program:run_tunnel_api\]\n.*?(?=^\[|\Z)'
|
||||
section = re.search(pattern, original)
|
||||
if not section or 'command=/exe/run_tunnel_api.sh' not in section.group():
|
||||
return False
|
||||
backup = config.with_name(config.name + '.before-tunnel-plugin')
|
||||
if not backup.exists():
|
||||
shutil.copy2(config, backup)
|
||||
temporary = config.with_name(config.name + '.tunnel-migration')
|
||||
temporary.write_text(re.sub(pattern, '', original))
|
||||
shutil.copymode(config, temporary)
|
||||
os.replace(temporary, config)
|
||||
# update stops and removes the old process group without touching WebUI.
|
||||
try:
|
||||
for action in ('reread', 'update'):
|
||||
subprocess.run([control, action], check=True, capture_output=True, text=True, timeout=15)
|
||||
except Exception:
|
||||
temporary.write_text(original)
|
||||
shutil.copymode(config, temporary)
|
||||
os.replace(temporary, config)
|
||||
raise
|
||||
return True
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Retire only replaced runtime dependencies; never touch documents, profiles or login state."""
|
||||
import importlib.metadata
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import psutil
|
||||
from packaging.requirements import Requirement
|
||||
from packaging.utils import canonicalize_name
|
||||
from helpers import files, runtime, system_packages
|
||||
from helpers.extension import Extension
|
||||
from helpers.print_style import PrintStyle
|
||||
|
||||
PYTHON_PACKAGES = ('patchright', 'playwright', 'aiogram', 'imapclient', 'exchangelib')
|
||||
SCRAPER_PACKAGES = {'newspaper3k', 'pyreqwest-impersonate', 'jieba3k', 'feedfinder2',
|
||||
'feedparser', 'feedparser-sgmllib', 'sgmllib3k', 'tinysegmenter',
|
||||
'tldextract', 'requests-file', 'cssselect'}
|
||||
DESKTOP_PACKAGES = ('libreoffice-*', 'python3-uno', 'xpra*', 'xfce4-*', 'xfwm4', 'xfdesktop4',
|
||||
'thunar*', 'coolwsd*', 'collaboraoffice*')
|
||||
|
||||
|
||||
class RetireOuterFeatures(Extension):
|
||||
def execute(self, **kwargs):
|
||||
if runtime.is_dockerized():
|
||||
retire()
|
||||
|
||||
|
||||
def retire():
|
||||
installed = sorted(unused_scrapers())
|
||||
for name in PYTHON_PACKAGES:
|
||||
try:
|
||||
importlib.metadata.version(name)
|
||||
installed.append(name)
|
||||
except importlib.metadata.PackageNotFoundError:
|
||||
pass
|
||||
if installed:
|
||||
subprocess.run(['uv', 'pip', 'uninstall', '--python', sys.executable, *installed], check=True, timeout=60)
|
||||
for relative in ('tmp/playwright', 'usr/plugins/_browser/playwright', 'usr/browser/playwright',
|
||||
'plugins/_whatsapp_integration/whatsapp-bridge/node_modules'):
|
||||
path = Path(files.get_abs_path(relative))
|
||||
if path.is_dir() and not path.is_symlink():
|
||||
shutil.rmtree(path)
|
||||
if os.geteuid() != 0 or not shutil.which('dpkg-query'):
|
||||
return
|
||||
# Existing GUI processes may still hold unsaved work during a source-only update.
|
||||
for process in psutil.process_iter(['name']):
|
||||
if any(part in (process.info.get('name') or '').lower() for part in ('soffice', 'coolwsd', 'xpra', 'xfce', 'xfwm', 'xfdesktop')):
|
||||
PrintStyle.warning('Desktop package retirement deferred until old GUI applications are closed and Agent Zero restarts; user files are preserved.')
|
||||
return
|
||||
result = subprocess.run(['dpkg-query', '-W', '-f=${binary:Package}\t${db:Status-Status}\n', *DESKTOP_PACKAGES],
|
||||
capture_output=True, text=True, timeout=15)
|
||||
packages = [line.split('\t')[0] for line in result.stdout.splitlines() if line.endswith('\tinstalled')]
|
||||
if packages:
|
||||
result = system_packages.run_runtime_apt(['apt-get', 'remove', '-y', *packages], timeout=180)
|
||||
if result.returncode:
|
||||
raise RuntimeError('Retired Desktop packages could not be removed; retry after resolving APT state')
|
||||
# Retain the old owned service declaration as a reversible backup, outside Supervisor's include pattern.
|
||||
retire_service(Path('/etc/supervisor/conf.d/a0_office_collabora.conf'))
|
||||
|
||||
|
||||
def unused_scrapers():
|
||||
distributions = {canonicalize_name(d.metadata['Name']): d for d in importlib.metadata.distributions()}
|
||||
removable = SCRAPER_PACKAGES & distributions.keys()
|
||||
# Installed metadata does not record selected extras; conservatively retain their dependencies too.
|
||||
while True:
|
||||
required = set()
|
||||
for name, distribution in distributions.items():
|
||||
if name in removable:
|
||||
continue
|
||||
for declaration in distribution.requires or ():
|
||||
requirement = Requirement(declaration)
|
||||
required.add(canonicalize_name(requirement.name))
|
||||
remaining = removable - required
|
||||
if remaining == removable:
|
||||
return removable
|
||||
removable = remaining
|
||||
|
||||
|
||||
def retire_service(config):
|
||||
if config.is_file():
|
||||
backup = config.with_suffix('.conf.before-tuxee')
|
||||
if not backup.exists():
|
||||
shutil.copy2(config, backup)
|
||||
config.unlink()
|
||||
control = shutil.which('supervisorctl')
|
||||
if control:
|
||||
try:
|
||||
for action in ('reread', 'update'):
|
||||
subprocess.run([control, action], check=True, capture_output=True, timeout=15)
|
||||
except Exception:
|
||||
shutil.copy2(backup, config)
|
||||
raise
|
||||
+4
-1
@@ -8,7 +8,7 @@
|
||||
## Ownership
|
||||
|
||||
- Helper modules provide reusable services; feature-specific route handlers belong in `api/`, tool behavior in `tools/`, and plugin-local logic inside plugin directories.
|
||||
- Security, auth, settings, file access, plugin discovery, extension dispatch, notifications, state snapshots, scheduler, tunnel, and WebSocket primitives live here.
|
||||
- Security, auth, settings, file access, plugin discovery, extension dispatch, notifications, state snapshots, scheduler, sandbox access, tunnel-origin discovery, and WebSocket primitives live here.
|
||||
|
||||
## Local Contracts
|
||||
|
||||
@@ -31,6 +31,9 @@
|
||||
- When a helper module is added, removed, renamed, or behaviorally changed, update its matching `*.py.dox.md` in the same change.
|
||||
- Do not leave stale file-level DOX after helper deletion or rename.
|
||||
|
||||
- `local_embeddings.py` owns pinned offline MiniLM ONNX assets and inference; its file DOX records accepted model/configuration and parity verification boundaries.
|
||||
- `sandbox_worker.py` owns lazy plugin worker handoff, cancellation and idle cleanup; `native_display.py` owns standard-library XRandR operations reusable inside guests.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
- Prefer cohesive helper modules over adding unrelated utilities to large files.
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
# cli_tunnel.py DOX
|
||||
|
||||
## Purpose
|
||||
|
||||
- Own the `cli_tunnel.py` helper module.
|
||||
- This module provides shared download and install mechanics for CLI-based tunnel providers.
|
||||
- Keep this file-level DOX profile synchronized with `cli_tunnel.py` because this directory is intentionally flat.
|
||||
|
||||
## Ownership
|
||||
|
||||
- `cli_tunnel.py` owns the runtime implementation.
|
||||
- `cli_tunnel.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation.
|
||||
- Classes:
|
||||
- `CliTunnelHelper` (`TunnelHelper`)
|
||||
- `start(self)`
|
||||
- `stop(self)`
|
||||
- Top-level functions:
|
||||
- `executable_name(name)`
|
||||
- `chmod_executable(path)`
|
||||
- `notify_download(notify, message, data=...)`
|
||||
- `notify_download_complete(notify, message, data=...)`
|
||||
- `download_file(url, destination, notify=...)`
|
||||
- `platform_parts()`
|
||||
- `extract_named_members_from_tar(archive_path, destination_dir, member_names)`
|
||||
- `extract_named_members_from_zip(archive_path, destination_dir, member_names)`
|
||||
- Notable constants/configuration names: `RUNTIME_BIN_DIR`.
|
||||
|
||||
## 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: filesystem reads, filesystem writes, filesystem deletion, network calls, subprocess/runtime control, tunnel state.
|
||||
- Imported dependency areas include: `collections`, `flaredantic`, `helpers`, `helpers.tunnel_common`, `os`, `pathlib`, `platform`, `queue`, `shutil`, `subprocess`, `tarfile`, `tempfile`, `threading`, `time`, `urllib.request`, `zipfile`.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `Path`, `files.get_abs_path`, `callable`, `destination.parent.mkdir`, `notify_download`, `tempfile.mkstemp`, `os.close`, `platform.system.lower`, `platform.machine.lower`, `destination_dir.mkdir`, `path.chmod`, `notify`, `temp_path.replace`, `notify_download_complete`, `RuntimeError`, `archive.getmembers`, `zipfile.ZipFile`, `archive.infolist`, `super.__init__`, `self.url_pattern.search`.
|
||||
- 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.
|
||||
- Related tests observed by source search:
|
||||
- `tests/test_tunnel_remote_link.py`
|
||||
|
||||
## Child DOX Index
|
||||
|
||||
No child DOX files.
|
||||
@@ -1,43 +0,0 @@
|
||||
# cloudflare_tunnel.py DOX
|
||||
|
||||
## Purpose
|
||||
|
||||
- Own the `cloudflare_tunnel.py` helper module.
|
||||
- This module implements Cloudflare tunnel provider lifecycle behavior.
|
||||
- Keep this file-level DOX profile synchronized with `cloudflare_tunnel.py` because this directory is intentionally flat.
|
||||
|
||||
## Ownership
|
||||
|
||||
- `cloudflare_tunnel.py` owns the runtime implementation.
|
||||
- `cloudflare_tunnel.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation.
|
||||
- Classes:
|
||||
- `CloudflareTunnel` (`FlaredanticTunnelHelper`)
|
||||
- `build_tunnel(self)`
|
||||
|
||||
## 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: settings/state persistence, tunnel state.
|
||||
- Imported dependency areas include: `flaredantic`, `helpers.tunnel_common`.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `FlareConfig`, `FlareTunnel`.
|
||||
- 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.
|
||||
- Related tests observed by source search:
|
||||
- `tests/test_tunnel_remote_link.py`
|
||||
|
||||
## Child DOX Index
|
||||
|
||||
No child DOX files.
|
||||
@@ -58,7 +58,7 @@
|
||||
|
||||
No child DOX files.
|
||||
|
||||
`read_text` owns bounded local Editor reads. `encode_upload` bounds the development RFC adapter. `prepare_files_download` owns Files routing and policy; a single selected directory downloads as `<folder>.zip` while true multi-selections keep the timestamped `agent-zero-selected-<count>-<stamp>.zip` archive name. `register_files_download` rechecks remote permission at delivery. API handlers do not select byte limits. Generic attachment/Connector downloads remain separate.
|
||||
`read_text` owns bounded local Editor reads. `encode_upload` remains a bounded base64 compatibility adapter; normal uploads stream locally in every mode. `prepare_files_download` owns Files routing and policy; a single selected directory downloads as `<folder>.zip` while true multi-selections keep the timestamped `agent-zero-selected-<count>-<stamp>.zip` archive name. `register_files_download` rechecks remote permission at delivery. API handlers do not select byte limits. Generic attachment/Connector downloads remain separate.
|
||||
|
||||
Destructive entry operations resolve parent directories while preserving the final symlink. Delete/Rename operate on the link itself; empty/root targets are rejected in the shared helper. Local Files downloads stage a bounded snapshot and reject in-place source changes during preparation. Cancelled preparation closes late responses and their temporary descriptors.
|
||||
|
||||
|
||||
+5
-2
@@ -609,8 +609,11 @@ def fix_dev_path(path: str):
|
||||
"On dev environment, convert /a0/... paths to local absolute paths"
|
||||
from helpers.runtime import is_development
|
||||
|
||||
if is_development() and path.startswith("/a0/") and not is_in_base_dir(path):
|
||||
path = path.removeprefix("/a0/")
|
||||
if is_development() and not is_in_base_dir(path):
|
||||
if path == "/a0":
|
||||
return get_base_dir()
|
||||
if path.startswith("/a0/"):
|
||||
path = path.removeprefix("/a0/")
|
||||
return get_abs_path(path)
|
||||
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
|
||||
- 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.
|
||||
- `fix_dev_path` remaps `/a0/...` display paths onto the local base dir, but a path already inside the checkout (a dev instance nested under `/a0`) is used as-is.
|
||||
- `fix_dev_path` remaps `/a0` and `/a0/...` display paths onto the local base dir, but a path already inside the checkout (a dev instance nested under `/a0`) is used as-is. Apply this only at local filesystem boundaries; explicit SSH and provider paths retain their own roots.
|
||||
- Observed side-effect areas: filesystem reads, filesystem writes, filesystem deletion, subprocess/runtime control, plugin state, settings/state persistence, secret handling.
|
||||
- Imported dependency areas include: `abc`, `base64`, `fnmatch`, `glob`, `helpers`, `helpers.strings`, `json`, `mimetypes`, `os`, `re`, `shutil`, `simpleeval`, `tempfile`, `typing`, `zipfile`.
|
||||
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
import time
|
||||
from helpers.task_scheduler import TaskScheduler
|
||||
from helpers.print_style import PrintStyle
|
||||
from helpers import errors
|
||||
from helpers import runtime
|
||||
|
||||
|
||||
SLEEP_TIME = 60
|
||||
@@ -17,13 +15,6 @@ async def run_loop():
|
||||
global pause_time, keep_running
|
||||
|
||||
while True:
|
||||
if runtime.is_development():
|
||||
# Signal to container that the job loop should be paused
|
||||
# if we are runing a development instance to avoid duble-running the jobs
|
||||
try:
|
||||
await runtime.call_development_function(pause_loop)
|
||||
except Exception as e:
|
||||
PrintStyle().error("Failed to pause job loop by development instance: " + errors.error_text(e))
|
||||
if not keep_running and (time.time() - pause_time) > (SLEEP_TIME * 2):
|
||||
resume_loop()
|
||||
if keep_running:
|
||||
|
||||
@@ -19,14 +19,16 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- Development uses the local scheduler and job-loop extensions without pausing itself or contacting a sibling. Explicit `pause_loop`/`resume_loop`, stale-pause recovery, tick error handling and the sleep interval remain intact.
|
||||
|
||||
- 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: scheduler state.
|
||||
- Imported dependency areas include: `asyncio`, `datetime`, `helpers`, `helpers.print_style`, `helpers.task_scheduler`, `time`.
|
||||
- Imported dependency areas include: `asyncio`, `helpers`, `helpers.print_style`, `helpers.task_scheduler`, `time`.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `time.time`, `runtime.is_development`, `scheduler.tick`, `call_extensions_async`, `resume_loop`, `asyncio.sleep`, `runtime.call_development_function`, `PrintStyle.error`, `scheduler_tick`, `errors.format_error`, `PrintStyle`, `errors.error_text`.
|
||||
- Important called helpers/classes observed in the source: `time.time`, `scheduler.tick`, `call_extensions_async`, `resume_loop`, `asyncio.sleep`, `PrintStyle.error`, `scheduler_tick`, `errors.format_error`, `PrintStyle`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
@@ -40,6 +42,7 @@
|
||||
- Run targeted tests for changed helper behavior; run security regressions for auth, filesystem, WebSocket, tunnel, upload, or secret-handling helpers.
|
||||
- Related tests observed by source search:
|
||||
- `tests/test_api_chat_lifetime.py`
|
||||
- `tests/test_local_development_calls.py`
|
||||
|
||||
## Child DOX Index
|
||||
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
"""Pinned, offline MiniLM inference without the training stack."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
MODEL = "sentence-transformers/all-MiniLM-L6-v2"
|
||||
REVISION = "1110a243fdf4706b3f48f1d95db1a4f5529b4d41"
|
||||
# The upstream FP32 graph contains the exact bundled safetensors weights.
|
||||
ASSETS = {
|
||||
"onnx/model.onnx": "6fd5d72fe4589f189f8ebc006442dbb529bb7ce38f8082112682524616046452",
|
||||
"tokenizer.json": "be50c3628f2bf5bb5e3a7f17b1f74611b2561a3a27eeab05e5aa30f411572037",
|
||||
}
|
||||
|
||||
|
||||
def configured_asset_options():
|
||||
"""Prepare bundled-model caches reachable through saved model selections."""
|
||||
from plugins._model_config.helpers.model_config import get_saved_embedding_model_configs
|
||||
|
||||
options = []
|
||||
for config in get_saved_embedding_model_configs():
|
||||
if config.provider != "huggingface" or config.name != MODEL:
|
||||
continue
|
||||
kwargs = config.build_kwargs()
|
||||
entry = {"cache_folder": kwargs.get("cache_folder"), "token": kwargs.get("use_auth_token")}
|
||||
if entry not in options:
|
||||
options.append(entry)
|
||||
return options or [{}]
|
||||
|
||||
|
||||
def model_assets(*, cache_folder=None, token=None, download=False):
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
paths = {}
|
||||
for name, digest in ASSETS.items():
|
||||
path = Path(hf_hub_download(
|
||||
MODEL, name, revision=REVISION, cache_dir=cache_folder,
|
||||
token=token, local_files_only=not download,
|
||||
))
|
||||
with path.open("rb") as stream:
|
||||
actual = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if actual != digest:
|
||||
raise ValueError(f"Embedding asset checksum mismatch: {name}")
|
||||
paths[name] = path
|
||||
return paths
|
||||
|
||||
|
||||
class OnnxSentenceTransformer:
|
||||
"""The validated bundled sentence-transformer pipeline, on CPU in float32."""
|
||||
|
||||
def __init__(self, model, *, device=None, cache_folder=None, use_auth_token=None,
|
||||
revision=None, trust_remote_code=False, model_kwargs=None):
|
||||
if model not in (MODEL, MODEL.removeprefix("sentence-transformers/")):
|
||||
raise ValueError(
|
||||
f"Local ONNX embeddings currently support only {MODEL}. "
|
||||
"Other local models need a separately validated ONNX pipeline; "
|
||||
"no model was substituted and no index was changed."
|
||||
)
|
||||
if revision not in (None, REVISION) or device not in (None, "cpu") or trust_remote_code or model_kwargs:
|
||||
raise ValueError(
|
||||
"Local ONNX embeddings require the bundled revision, CPU, "
|
||||
"trust_remote_code=false and no model_kwargs. "
|
||||
"These options cannot be silently translated to ONNX."
|
||||
)
|
||||
import numpy as np
|
||||
import onnxruntime as ort
|
||||
from tokenizers import Tokenizer
|
||||
|
||||
self.np = np
|
||||
paths = model_assets(cache_folder=cache_folder, token=use_auth_token)
|
||||
self.tokenizer = Tokenizer.from_file(str(paths["tokenizer.json"]))
|
||||
self.tokenizer.enable_truncation(max_length=256, strategy="longest_first")
|
||||
self.tokenizer.enable_padding(pad_id=0, pad_token="[PAD]")
|
||||
options = ort.SessionOptions()
|
||||
# Bound CPU use across concurrent framework requests and avoid oversized thread pools.
|
||||
options.intra_op_num_threads = 4
|
||||
self.session = ort.InferenceSession(str(paths["onnx/model.onnx"]),
|
||||
sess_options=options, providers=["CPUExecutionProvider"])
|
||||
|
||||
def encode(self, inputs, convert_to_tensor=False):
|
||||
if convert_to_tensor:
|
||||
raise ValueError("ONNX embeddings return NumPy arrays, not Torch tensors")
|
||||
if not isinstance(inputs, list) or any(not isinstance(text, str) for text in inputs):
|
||||
raise TypeError("Local embedding inputs must be a list of strings")
|
||||
np = self.np
|
||||
batches = []
|
||||
# Match SentenceTransformer's bounded batches; order is preserved without sorting.
|
||||
for offset in range(0, len(inputs), 32):
|
||||
tokens = self.tokenizer.encode_batch([text.strip() for text in inputs[offset:offset + 32]])
|
||||
feed = {
|
||||
"input_ids": np.asarray([t.ids for t in tokens], dtype=np.int64),
|
||||
"attention_mask": np.asarray([t.attention_mask for t in tokens], dtype=np.int64),
|
||||
"token_type_ids": np.asarray([t.type_ids for t in tokens], dtype=np.int64),
|
||||
}
|
||||
hidden = self.session.run(["last_hidden_state"], feed)[0]
|
||||
mask = feed["attention_mask"].astype(np.float32)[..., None]
|
||||
pooled = (hidden * mask).sum(axis=1) / np.maximum(mask.sum(axis=1), 1e-9)
|
||||
# Normalize is a model module; encode(normalize_embeddings=False) still runs it.
|
||||
pooled /= np.maximum(np.linalg.norm(pooled, axis=1, keepdims=True), 1e-12)
|
||||
batches.append(pooled)
|
||||
return np.concatenate(batches) if batches else np.empty((0, 384), dtype=np.float32)
|
||||
|
||||
|
||||
def prepare_model():
|
||||
"""Provision and verify the bundled model in every configured cache."""
|
||||
from huggingface_hub.errors import LocalEntryNotFoundError
|
||||
|
||||
for options in configured_asset_options():
|
||||
try:
|
||||
model_assets(**options)
|
||||
except LocalEntryNotFoundError:
|
||||
model_assets(download=True, **options)
|
||||
vector = OnnxSentenceTransformer(
|
||||
MODEL, cache_folder=options.get("cache_folder"), use_auth_token=options.get("token"),
|
||||
).encode(["offline readiness"])
|
||||
assert vector.shape == (1, 384)
|
||||
print(f"Prepared {MODEL}@{REVISION} for offline ONNX inference")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from plugins._model_config.extensions.python.startup_migration._10_migrate_model_config import MigrateModelConfig
|
||||
|
||||
MigrateModelConfig(None).execute()
|
||||
prepare_model()
|
||||
@@ -0,0 +1,38 @@
|
||||
# Local ONNX embeddings
|
||||
|
||||
`OnnxSentenceTransformer` implements the validated bundled `all-MiniLM-L6-v2`
|
||||
pipeline: exact revision and SHA-256 assets declared in the module, BERT tokenizer,
|
||||
256 tokens including specials, right padding, attention-mask mean pooling and
|
||||
model-defined L2 normalization, float32 CPU output. Batches are bounded at 32 and
|
||||
retain caller order. `models.py` owns shared instance reuse and rate limits.
|
||||
|
||||
`model_assets()` checks both immutable asset hashes and defaults to local-only
|
||||
Hugging Face cache lookup. Running `python -m helpers.local_embeddings` calls
|
||||
the existing backed-up, idempotent legacy model-config migration, then
|
||||
`prepare_model()` to prepare missing assets and verify inference during build/setup/upgrade.
|
||||
`configured_asset_options()` resolves the global configuration and every saved
|
||||
preset plus persisted raw chat overrides through model-config inheritance,
|
||||
scope resolution and alias normalization. It reads chat metadata without restoring
|
||||
agents or loading indexes. Docker readiness follows config migration and preset
|
||||
bootstrap so newly migrated scope selections are included.
|
||||
For the bundled model it deduplicates cache/access options and passes
|
||||
`cache_folder` and `use_auth_token` to both preparation and readiness checks.
|
||||
When none select the bundled model, default bundled-asset preparation remains.
|
||||
The preparation subprocess reads these settings itself; tokens never go in its
|
||||
command line. Runtime
|
||||
requests never install dependencies or download assets. No Torch weights ship in
|
||||
new images. Tokenizer defaults come from the exact bundled tokenizer JSON.
|
||||
|
||||
Only this model/revision and CPU are validated. Other local models, devices,
|
||||
remote code and nonempty `model_kwargs` fail explicitly before index access;
|
||||
they are never replaced with the default. `cache_folder` and `use_auth_token`
|
||||
retain cache/access meanings. Docker source upgrades prepare all saved selection
|
||||
caches without deleting their old contents; local setup runs the preparation command
|
||||
after configuring a custom cache and before inference.
|
||||
The wrapper keeps its legacy name and logical model identity for existing callers
|
||||
and caches. Remote provider dispatch is unchanged.
|
||||
|
||||
Verify with `test_local_embeddings.py`, `test_embedding_model_preload.py`, and
|
||||
`integration_onnx_compatibility.py` in separate old/new offline runtimes. Numerical
|
||||
parity is specific to the pinned default; never extend the accepted model set
|
||||
without persisted-index compatibility evidence.
|
||||
@@ -1,50 +0,0 @@
|
||||
# microsoft_tunnel.py DOX
|
||||
|
||||
## Purpose
|
||||
|
||||
- Own the `microsoft_tunnel.py` helper module.
|
||||
- This module implements Microsoft Dev Tunnel provider behavior.
|
||||
- Keep this file-level DOX profile synchronized with `microsoft_tunnel.py` because this directory is intentionally flat.
|
||||
|
||||
## Ownership
|
||||
|
||||
- `microsoft_tunnel.py` owns the runtime implementation.
|
||||
- `microsoft_tunnel.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation.
|
||||
- Classes:
|
||||
- `AgentZeroMicrosoftTunnel` (`MicrosoftTunnel`)
|
||||
- `notify(self, event, message, data=...)`
|
||||
- `agent_zero_notifications(self)`
|
||||
- `MicrosoftDevTunnel` (`FlaredanticTunnelHelper`)
|
||||
- `build_tunnel(self)`
|
||||
- `start(self)`
|
||||
- Top-level functions:
|
||||
- `default_microsoft_tunnel_id()`
|
||||
- Notable constants/configuration names: `MICROSOFT_TUNNEL_ID_ENV_KEYS`, `MICROSOFT_TUNNEL_TIMEOUT`.
|
||||
|
||||
## 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: filesystem reads, network calls, settings/state persistence, tunnel state.
|
||||
- Imported dependency areas include: `flaredantic`, `getpass`, `hashlib`, `helpers`, `helpers.tunnel_common`, `os`, `socket`.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `join`, `strip`, `hashlib.sha256.hexdigest`, `self.notify`, `callable`, `self._notify_progress`, `self._run_cmd`, `MicrosoftConfig`, `AgentZeroMicrosoftTunnel`, `getpass.getuser`, `socket.gethostname`, `files.get_abs_path`, `super.notify`, `parent`, `super.start`, `hashlib.sha256`, `MicrosoftTunnelError`, `default_microsoft_tunnel_id`, `RuntimeError`, `seed.encode`.
|
||||
- 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.
|
||||
- Related tests observed by source search:
|
||||
- `tests/test_tunnel_remote_link.py`
|
||||
|
||||
## Child DOX Index
|
||||
|
||||
No child DOX files.
|
||||
@@ -159,7 +159,6 @@ def _cleanup_obsolete() -> None:
|
||||
to_remove = [
|
||||
"knowledge/default",
|
||||
"memory",
|
||||
"logs",
|
||||
]
|
||||
for path in to_remove:
|
||||
if files.exists(path):
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
|
||||
- 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.
|
||||
- Startup cleanup removes obsolete `memory`, `knowledge/default`, and legacy `logs` directories; repeated runs are safe.
|
||||
- Startup cleanup removes obsolete `memory` and `knowledge/default` directories. Legacy top-level `logs` (including symlinks) and new `usr/logs` are preserved in place on every run; no log migration, overwriting, conversion or retention cleanup occurs. Back up historical top-level logs separately from `usr` before replacing an old container.
|
||||
- `prepare.py` calls `migrate_dotenv()` and reloads dotenv before setting the root password, so preparation cannot create a placeholder `usr/.env` ahead of legacy migration. `migrate_user_data()` repeats this check safely.
|
||||
- An existing `usr/.env` is authoritative. Preserve both paths when they alias the same file; warn without printing values when distinct legacy configuration is left in place. With legacy configuration present, an unusable destination stops migration; an unusable legacy source stops migration when no destination exists. Migration errors abort startup before preparation can create a placeholder configuration without the saved credentials.
|
||||
- With no destination, regular legacy files move normally. A valid legacy symlink stays in place and `usr/.env` links to the same target, adjusting relative paths from the destination's actual directory (including a symlinked `usr/`) without resolving intermediate target symlinks. External configuration replacements remain visible. Link creation never replaces an existing destination; failures leave the legacy configuration untouched.
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Standard-library XRandR operations shared by host desktops and guest browsers."""
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Any
|
||||
DEFAULT_WIDTH, DEFAULT_HEIGHT = 1440, 900
|
||||
MAX_WIDTH, MAX_HEIGHT = 1920, 1080
|
||||
MIN_WIDTH, MIN_HEIGHT = 360, 240
|
||||
|
||||
def normalize_size(
|
||||
width: int | float | str,
|
||||
height: int | float | str,
|
||||
*,
|
||||
max_width: int = MAX_WIDTH,
|
||||
max_height: int = MAX_HEIGHT,
|
||||
min_width: int = MIN_WIDTH,
|
||||
min_height: int = MIN_HEIGHT,
|
||||
) -> tuple[int, int]:
|
||||
requested_width = max(1, int(float(width or DEFAULT_WIDTH)))
|
||||
requested_height = max(1, int(float(height or DEFAULT_HEIGHT)))
|
||||
scale = min(max_width / requested_width, max_height / requested_height, 1.0)
|
||||
if scale < 1.0:
|
||||
requested_width = max(1, math.floor(requested_width * scale))
|
||||
requested_height = max(1, math.floor(requested_height * scale))
|
||||
return (
|
||||
max(min_width, min(max_width, requested_width)),
|
||||
max(min_height, min(max_height, requested_height)),
|
||||
)
|
||||
|
||||
|
||||
def resize_display(
|
||||
*,
|
||||
display: int,
|
||||
width: int,
|
||||
height: int,
|
||||
max_width: int = MAX_WIDTH,
|
||||
max_height: int = MAX_HEIGHT,
|
||||
window_class: str = "",
|
||||
keys: tuple[str, ...] = (),
|
||||
xauthority: str = "",
|
||||
home: str = "",
|
||||
settle_seconds: float = 0.15,
|
||||
env: dict[str, str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
target_width, target_height = normalize_size(width, height, max_width=max_width, max_height=max_height)
|
||||
xrandr = shutil.which("xrandr")
|
||||
if not xrandr:
|
||||
return {"ok": False, "error": "xrandr is not installed."}
|
||||
|
||||
env = env or {**os.environ, "DISPLAY": f":{display}"}
|
||||
current_before = current_display_size(display, env=env)
|
||||
if current_before == (target_width, target_height):
|
||||
return {"ok": True, "width": target_width, "height": target_height, "resized": False}
|
||||
|
||||
_ensure_xrandr_mode(env, target_width, target_height)
|
||||
result = _select_xrandr_mode(env, target_width, target_height)
|
||||
if result.returncode != 0:
|
||||
result = subprocess.run(
|
||||
[xrandr, "--fb", f"{target_width}x{target_height}"],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=4,
|
||||
env=env,
|
||||
)
|
||||
if settle_seconds > 0:
|
||||
time.sleep(settle_seconds)
|
||||
current = current_display_size(display, env=env)
|
||||
ok = current == (target_width, target_height)
|
||||
if ok:
|
||||
return {"ok": True, "width": target_width, "height": target_height, "resized": True}
|
||||
detail = (result.stderr or result.stdout or "xrandr resize failed").strip()
|
||||
return {
|
||||
"ok": False,
|
||||
"error": detail,
|
||||
"width": current[0] if current else target_width,
|
||||
"height": current[1] if current else target_height,
|
||||
}
|
||||
|
||||
|
||||
def _ensure_xrandr_mode(env: dict[str, str], width: int, height: int) -> None:
|
||||
xrandr = shutil.which("xrandr")
|
||||
if not xrandr:
|
||||
return
|
||||
output, existing_modes = _xrandr_output_modes(env)
|
||||
if not output:
|
||||
return
|
||||
mode = f"{width}x{height}"
|
||||
if mode not in existing_modes:
|
||||
subprocess.run(
|
||||
[xrandr, "--newmode", mode, "0", str(width), "0", "0", "0", str(height), "0", "0", "0"],
|
||||
check=False,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=2,
|
||||
env=env,
|
||||
)
|
||||
subprocess.run(
|
||||
[xrandr, "--addmode", output, mode],
|
||||
check=False,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=2,
|
||||
env=env,
|
||||
)
|
||||
|
||||
|
||||
def _select_xrandr_mode(env: dict[str, str], width: int, height: int) -> subprocess.CompletedProcess[str]:
|
||||
xrandr = shutil.which("xrandr")
|
||||
if not xrandr:
|
||||
return subprocess.CompletedProcess([], 1, "", "xrandr is not installed.")
|
||||
output, _ = _xrandr_output_modes(env)
|
||||
if not output:
|
||||
return subprocess.CompletedProcess([], 1, "", "No connected XRandR output found.")
|
||||
mode = f"{width}x{height}"
|
||||
return subprocess.run(
|
||||
[xrandr, "--output", output, "--mode", mode],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=4,
|
||||
env=env,
|
||||
)
|
||||
|
||||
|
||||
def _xrandr_output_modes(env: dict[str, str]) -> tuple[str, set[str]]:
|
||||
xrandr = shutil.which("xrandr")
|
||||
if not xrandr:
|
||||
return "", set()
|
||||
result = subprocess.run(
|
||||
[xrandr, "-q"],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=4,
|
||||
env=env,
|
||||
)
|
||||
output = ""
|
||||
modes: set[str] = set()
|
||||
for line in result.stdout.splitlines():
|
||||
output_match = re.match(r"^(\S+)\s+connected\b", line)
|
||||
if output_match:
|
||||
output = output_match.group(1)
|
||||
continue
|
||||
if output:
|
||||
mode_match = re.match(r"^\s+(\d+x\d+)\b", line)
|
||||
if mode_match:
|
||||
modes.add(mode_match.group(1))
|
||||
return output, modes
|
||||
|
||||
|
||||
def current_display_size(display: int, *, env: dict[str, str] | None = None) -> tuple[int, int] | None:
|
||||
xrandr = shutil.which("xrandr")
|
||||
if not xrandr:
|
||||
return None
|
||||
result = subprocess.run(
|
||||
[xrandr, "-q"],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=4,
|
||||
env=env or {**os.environ, "DISPLAY": f":{display}"},
|
||||
)
|
||||
match = re.search(r"\bcurrent\s+(\d+)\s+x\s+(\d+)", result.stdout)
|
||||
if not match:
|
||||
return None
|
||||
return int(match.group(1)), int(match.group(2))
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Native display operations
|
||||
|
||||
Standard-library XRandR size detection, bounded mode selection and resizing.
|
||||
`virtual_desktop` supplies host localization/environment and window fitting;
|
||||
the Browser guest loads this same source for its private X display. No framework
|
||||
imports, state discovery, route registration or package installation occurs here.
|
||||
Verify Desktop resize regression tests and the Browser sandbox viewer smoke test.
|
||||
+9
-2
@@ -123,15 +123,22 @@ def register_watchdogs():
|
||||
|
||||
def on_plugin_change(events: list[WatchItem], frontend_reload: bool = True):
|
||||
plugin_names: list[str] = []
|
||||
changed_paths = []
|
||||
for path, _event in events:
|
||||
path = path.replace("\\", "/")
|
||||
if "/plugins/" not in path:
|
||||
continue
|
||||
plugin_name = path.split("/plugins/", 1)[1].split("/", 1)[0]
|
||||
plugin_name, _, asset = path.split("/plugins/", 1)[1].partition("/")
|
||||
# Guest rootfs packages may also contain hooks.py or extensions/.
|
||||
if not (asset.startswith("extensions/") or asset in {HOOKS_SCRIPT, '.toggle-0', '.toggle-1'}):
|
||||
continue
|
||||
changed_paths.append(path)
|
||||
if plugin_name and plugin_name not in plugin_names:
|
||||
plugin_names.append(plugin_name)
|
||||
if not changed_paths:
|
||||
return
|
||||
print_style.PrintStyle.debug("Plugins watchdog triggered", plugin_names)
|
||||
python_change = any(path.endswith('.py') for path, _event in events)
|
||||
python_change = any(path.endswith('.py') for path in changed_paths)
|
||||
after_plugin_change(
|
||||
plugin_names or None,
|
||||
python_change=python_change,
|
||||
|
||||
@@ -76,6 +76,8 @@
|
||||
- Important called helpers/classes observed in the source: `re.compile`, `Field`, `watchdog.add_watchdog`, `clear_plugin_cache`, `send_frontend_reload_notification`, `DeferredTask.start_task`, `get_plugin_roots`, `get_plugin_name_from_path`, `result.sort`, `cache.add`, `get_enhanced_plugins_list`, `find_plugin_dir`, `files.get_abs_path`, `files.exists`, `call_plugin_hook`, `delete_plugin`, `files.delete_dir`, `after_plugin_change`, `get_enabled_plugins`, `get_plugins_list`, `get_plugin_meta`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
- Plugin watchdog invalidation only admits direct plugin hooks, toggles and extensions; dependency files inside sandbox disk roots must not unload live services.
|
||||
|
||||
## Work Guidance
|
||||
|
||||
- Preserve public helper APIs used by core code and plugins unless every caller is updated.
|
||||
|
||||
+65
-12
@@ -1,6 +1,11 @@
|
||||
import html
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from collections.abc import Mapping
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import webcolors
|
||||
|
||||
@@ -8,6 +13,8 @@ from . import files # Load before strings; helpers.files imports sanitize_strin
|
||||
from .strings import sanitize_string
|
||||
|
||||
_runtime_module = None
|
||||
_ANSI_ESCAPE = re.compile(r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[ -/]*[@-Z\\^_])")
|
||||
_ANSI_PARTIAL = re.compile(r"\x1b(?:\[[0-?]*[ -/]*|\][^\x07\x1b]*(?:\x1b)?|[ -/]*)$")
|
||||
|
||||
|
||||
def _get_runtime():
|
||||
@@ -20,6 +27,9 @@ def _get_runtime():
|
||||
|
||||
class PrintStyle:
|
||||
last_endline = True
|
||||
log_file_path = None
|
||||
_log_escape_tail = ""
|
||||
_output_lock = threading.RLock()
|
||||
|
||||
def __init__(self, bold=False, italic=False, underline=False, font_color="default", background_color="default", padding=False, log_only=False):
|
||||
self.bold = bold
|
||||
@@ -83,8 +93,46 @@ class PrintStyle:
|
||||
if self.padding and not self.padding_added:
|
||||
if not self.log_only:
|
||||
print() # Print an empty line for padding
|
||||
self._log_text("\n")
|
||||
self.padding_added = True
|
||||
|
||||
def _log_text(self, text, *, stream=False, end=""):
|
||||
text = (PrintStyle._log_escape_tail if stream else "") + sanitize_string(text)
|
||||
text = _ANSI_ESCAPE.sub("", text)
|
||||
partial = _ANSI_PARTIAL.search(text)
|
||||
PrintStyle._log_escape_tail = partial.group() if partial and stream else ""
|
||||
if partial:
|
||||
text = text[:partial.start()]
|
||||
# An unfinished payload escape must not consume the record ending.
|
||||
end = _ANSI_ESCAPE.sub("", sanitize_string(end))
|
||||
text += _ANSI_PARTIAL.sub("", end)
|
||||
text = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", text)
|
||||
if text.strip():
|
||||
try:
|
||||
if not hasattr(self, "secrets_mgr"):
|
||||
from helpers.secrets import get_secrets_manager
|
||||
self.secrets_mgr = get_secrets_manager()
|
||||
text = sanitize_string(self.secrets_mgr.mask_values(text))
|
||||
except Exception:
|
||||
text = "[Application log message omitted: secret masking unavailable]\n"
|
||||
try:
|
||||
if PrintStyle.log_file_path is None:
|
||||
logs_dir = files.get_abs_path(files.USER_DIR, "logs")
|
||||
os.makedirs(logs_dir, exist_ok=True)
|
||||
prefix = datetime.now(timezone.utc).strftime("log_%Y%m%d_%H%M%S_")
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w", encoding="utf-8", newline="", dir=logs_dir,
|
||||
prefix=prefix, suffix=".log", delete=False,
|
||||
) as log_file:
|
||||
PrintStyle.log_file_path = log_file.name
|
||||
log_file.write(text)
|
||||
else:
|
||||
with open(PrintStyle.log_file_path, "a", encoding="utf-8", newline="") as log_file:
|
||||
log_file.write(text)
|
||||
except OSError:
|
||||
# File logging must not prevent console output or application startup.
|
||||
print("Warning: Could not write application log under usr/logs.", file=sys.stderr)
|
||||
|
||||
@staticmethod
|
||||
def _format_args(args, sep):
|
||||
if not args:
|
||||
@@ -133,21 +181,26 @@ class PrintStyle:
|
||||
return text, self._get_styled_text(text), self._get_html_styled_text(text)
|
||||
|
||||
def print(self, *args, sep=' ', end='\n', flush=True):
|
||||
self._add_padding_if_needed()
|
||||
if not PrintStyle.last_endline:
|
||||
with PrintStyle._output_lock:
|
||||
self._add_padding_if_needed()
|
||||
if not PrintStyle.last_endline:
|
||||
if not self.log_only:
|
||||
print()
|
||||
self._log_text("\n")
|
||||
plain_text, styled_text, _ = self.get(*args, sep=sep)
|
||||
if not self.log_only:
|
||||
print()
|
||||
_, styled_text, _ = self.get(*args, sep=sep)
|
||||
if not self.log_only:
|
||||
print(styled_text, end=end, flush=flush)
|
||||
PrintStyle.last_endline = end.endswith('\n')
|
||||
print(styled_text, end=end, flush=flush)
|
||||
self._log_text(plain_text, end=end)
|
||||
PrintStyle.last_endline = end.endswith('\n')
|
||||
|
||||
def stream(self, *args, sep=' ', flush=True):
|
||||
self._add_padding_if_needed()
|
||||
_, styled_text, _ = self.get(*args, sep=sep)
|
||||
if not self.log_only:
|
||||
print(styled_text, end='', flush=flush)
|
||||
PrintStyle.last_endline = False
|
||||
with PrintStyle._output_lock:
|
||||
self._add_padding_if_needed()
|
||||
plain_text, styled_text, _ = self.get(*args, sep=sep)
|
||||
if not self.log_only:
|
||||
print(styled_text, end='', flush=flush)
|
||||
self._log_text(plain_text, stream=True)
|
||||
PrintStyle.last_endline = False
|
||||
|
||||
def is_last_line_empty(self):
|
||||
lines = sys.stdin.readlines()
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
## Purpose
|
||||
|
||||
- Own the `print_style.py` helper module.
|
||||
- This module formats console/debug output consistently.
|
||||
- This module formats console/debug output and persists plain application logs.
|
||||
- Keep this file-level DOX profile synchronized with `print_style.py` because this directory is intentionally flat.
|
||||
|
||||
## Ownership
|
||||
@@ -27,9 +27,15 @@
|
||||
|
||||
- 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.
|
||||
- `PrintStyle` emits sanitized, secret-masked console output and does not create filesystem log files.
|
||||
- `get()` preserves its plain-text, ANSI-styled, and HTML-styled return values for existing callers.
|
||||
- Imported dependency areas include: `collections.abc`, `files`, `html`, `strings`, `sys`, `webcolors`.
|
||||
- `print()` and `stream()` append UTF-8 plain text to one uniquely created `log_<UTC timestamp>_<random>.log` per process under `files.get_abs_path(files.USER_DIR, "logs")`. Creation is lazy, uses owner-only file permissions, and never truncates a prior run. The directory follows the native project root or mounted Docker `/a0/usr`.
|
||||
- File output preserves payload whitespace, Unicode, literal markup/entities, prefixes and the console's padding/line boundaries. Streaming appends without inserting chunk separators. CSI/OSC terminal escapes (including split chunks) and non-whitespace control characters are removed only from the file sink; no HTML wrappers or encoding are added.
|
||||
- Incomplete escapes carry only between consecutive stream chunks. A print/padding boundary discards pending control state, and a print's explicit ending is sanitized separately so an unfinished payload escape cannot swallow that ending or later records.
|
||||
- A shared reentrant lock keeps each print/stream operation and its file append ordered across threads. File handles close after each write; there is no retention/deletion policy.
|
||||
- Secret masking remains in `get()` and upstream model streaming filters. The file sink masks again after terminal-control removal and substitutes an omission marker if masking fails; console fallback behavior is unchanged. Callers streaming raw secret fragments still need the existing `StreamingSecretsFilter`, as model stream hooks already do.
|
||||
- `log_only=True` suppresses console output but persists the file output. Filesystem errors report a fixed warning to stderr and leave the application/console running; subsequent writes retry.
|
||||
- Structured chat logs, chat persistence, Supervisor stdout/stderr, self-update and sandbox diagnostic logs retain their existing contracts. User-data mounts/backups include the new application files; historical top-level logs remain untouched.
|
||||
- `get()` preserves its plain-text, ANSI-styled, and HTML-styled return values for existing callers and does not write files.
|
||||
- Imported dependency areas include: `collections.abc`, `datetime`, `files`, `html`, `os`, `re`, `strings`, `sys`, `tempfile`, `threading`, `webcolors`.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
@@ -47,6 +53,9 @@
|
||||
- Run targeted tests for changed helper behavior; run security regressions for auth, filesystem, WebSocket, tunnel, upload, or secret-handling helpers.
|
||||
- Related tests observed by source search:
|
||||
- `tests/test_print_style.py`
|
||||
- `tests/test_plain_response_logging.py`
|
||||
- `tests/test_warning_log_prefixes.py`
|
||||
- `tests/test_persist_chat_log_ids.py`
|
||||
- `tests/test_tool_action_contracts.py`
|
||||
- `tests/test_ws_manager.py`
|
||||
|
||||
|
||||
+4
-11
@@ -1,19 +1,12 @@
|
||||
from helpers import runtime, crypto, dotenv
|
||||
from helpers import crypto, dotenv
|
||||
|
||||
async def get_root_password():
|
||||
if runtime.is_dockerized():
|
||||
pswd = _get_root_password()
|
||||
else:
|
||||
priv = crypto._generate_private_key()
|
||||
pub = crypto._generate_public_key(priv)
|
||||
enc = await runtime.call_development_function(_provide_root_password, pub)
|
||||
pswd = crypto.decrypt_data(enc, priv)
|
||||
return pswd
|
||||
|
||||
return _get_root_password()
|
||||
|
||||
def _provide_root_password(public_key_pem: str):
|
||||
pswd = _get_root_password()
|
||||
enc = crypto.encrypt_data(pswd, public_key_pem)
|
||||
return enc
|
||||
|
||||
def _get_root_password():
|
||||
return dotenv.get_dotenv_value(dotenv.KEY_ROOT_PASSWORD) or ""
|
||||
return dotenv.get_dotenv_value(dotenv.KEY_ROOT_PASSWORD) or ""
|
||||
@@ -17,13 +17,15 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- `get_root_password` reads the local configured root password in every mode, returning an empty string when unset. It does not transmit or log credentials. `_provide_root_password` retains its encrypted-response contract for explicit compatibility callers.
|
||||
|
||||
- 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.
|
||||
- Imported dependency areas include: `helpers`.
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `runtime.is_dockerized`, `_get_root_password`, `crypto.encrypt_data`, `crypto._generate_private_key`, `crypto._generate_public_key`, `crypto.decrypt_data`, `dotenv.get_dotenv_value`, `runtime.call_development_function`.
|
||||
- Important called helpers/classes observed in the source: `_get_root_password`, `crypto.encrypt_data`, `dotenv.get_dotenv_value`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
@@ -35,7 +37,7 @@
|
||||
## 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.
|
||||
- Run `pytest tests/test_local_development_calls.py` for local credentials, empty defaults and unchanged error propagation.
|
||||
|
||||
## Child DOX Index
|
||||
|
||||
|
||||
+19
-65
@@ -4,7 +4,6 @@ import fnmatch
|
||||
import base64
|
||||
import tempfile
|
||||
import zipfile
|
||||
from helpers import runtime
|
||||
|
||||
|
||||
def get_abs_path(*relative_paths):
|
||||
@@ -17,7 +16,7 @@ def get_abs_path(*relative_paths):
|
||||
|
||||
|
||||
# =====================================================
|
||||
# RFC-ENABLED FILESYSTEM OPERATIONS
|
||||
# LOCAL FILESYSTEM OPERATIONS
|
||||
# =====================================================
|
||||
|
||||
def read_file_bin(relative_path: str, backup_dirs=None) -> bytes:
|
||||
@@ -37,10 +36,7 @@ def read_file_bin(relative_path: str, backup_dirs=None) -> bytes:
|
||||
# Find the file in directories
|
||||
absolute_path = find_file_in_dirs(relative_path, backup_dirs)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
b64_content = runtime.call_development_function_sync(
|
||||
_read_file_binary_impl, absolute_path
|
||||
)
|
||||
b64_content = _read_file_binary_impl(absolute_path)
|
||||
return base64.b64decode(b64_content)
|
||||
|
||||
|
||||
@@ -61,10 +57,7 @@ def read_file_base64(relative_path: str, backup_dirs=None) -> str:
|
||||
# Find the file in directories
|
||||
absolute_path = find_file_in_dirs(relative_path, backup_dirs)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_read_file_as_base64_impl, absolute_path
|
||||
)
|
||||
return _read_file_as_base64_impl(absolute_path)
|
||||
|
||||
|
||||
def write_file_binary(relative_path: str, content: bytes) -> bool:
|
||||
@@ -80,11 +73,8 @@ def write_file_binary(relative_path: str, content: bytes) -> bool:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
b64_content = base64.b64encode(content).decode('utf-8')
|
||||
return runtime.call_development_function_sync(
|
||||
_write_file_binary_impl, abs_path, b64_content
|
||||
)
|
||||
return _write_file_binary_impl(abs_path, b64_content)
|
||||
|
||||
|
||||
def write_file_base64(relative_path: str, content: str) -> bool:
|
||||
@@ -100,10 +90,7 @@ def write_file_base64(relative_path: str, content: str) -> bool:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_write_file_from_base64_impl, abs_path, content
|
||||
)
|
||||
return _write_file_from_base64_impl(abs_path, content)
|
||||
|
||||
|
||||
def delete_file(relative_path: str) -> bool:
|
||||
@@ -118,10 +105,7 @@ def delete_file(relative_path: str) -> bool:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_delete_file_impl, abs_path
|
||||
)
|
||||
return _delete_file_impl(abs_path)
|
||||
|
||||
|
||||
def delete_directory(relative_path: str) -> bool:
|
||||
@@ -136,10 +120,7 @@ def delete_directory(relative_path: str) -> bool:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_delete_folder_impl, abs_path
|
||||
)
|
||||
return _delete_folder_impl(abs_path)
|
||||
|
||||
|
||||
def list_directory(relative_path: str, include_hidden: bool = False) -> list:
|
||||
@@ -155,10 +136,7 @@ def list_directory(relative_path: str, include_hidden: bool = False) -> list:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_list_folder_impl, abs_path, include_hidden
|
||||
)
|
||||
return _list_folder_impl(abs_path, include_hidden)
|
||||
|
||||
|
||||
def make_directories(relative_path: str) -> bool:
|
||||
@@ -173,10 +151,7 @@ def make_directories(relative_path: str) -> bool:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_make_dirs_impl, abs_path
|
||||
)
|
||||
return _make_dirs_impl(abs_path)
|
||||
|
||||
|
||||
def path_exists(relative_path: str) -> bool:
|
||||
@@ -191,10 +166,7 @@ def path_exists(relative_path: str) -> bool:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_path_exists_impl, abs_path
|
||||
)
|
||||
return _path_exists_impl(abs_path)
|
||||
|
||||
|
||||
def file_exists(relative_path: str) -> bool:
|
||||
@@ -209,10 +181,7 @@ def file_exists(relative_path: str) -> bool:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_file_exists_impl, abs_path
|
||||
)
|
||||
return _file_exists_impl(abs_path)
|
||||
|
||||
|
||||
def folder_exists(relative_path: str) -> bool:
|
||||
@@ -227,10 +196,7 @@ def folder_exists(relative_path: str) -> bool:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_folder_exists_impl, abs_path
|
||||
)
|
||||
return _folder_exists_impl(abs_path)
|
||||
|
||||
|
||||
def get_subdirectories(relative_path: str, include: str | list[str] = "*", exclude: str | list[str] | None = None) -> list[str]:
|
||||
@@ -247,10 +213,7 @@ def get_subdirectories(relative_path: str, include: str | list[str] = "*", exclu
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_get_subdirectories_impl, abs_path, include, exclude
|
||||
)
|
||||
return _get_subdirectories_impl(abs_path, include, exclude)
|
||||
|
||||
|
||||
def zip_directory(relative_path: str) -> str:
|
||||
@@ -265,10 +228,7 @@ def zip_directory(relative_path: str) -> str:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_zip_dir_impl, abs_path
|
||||
)
|
||||
return _zip_dir_impl(abs_path)
|
||||
|
||||
|
||||
def move_file(source_path: str, destination_path: str) -> bool:
|
||||
@@ -285,10 +245,7 @@ def move_file(source_path: str, destination_path: str) -> bool:
|
||||
source_abs = get_abs_path(source_path)
|
||||
dest_abs = get_abs_path(destination_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
return runtime.call_development_function_sync(
|
||||
_move_file_impl, source_abs, dest_abs
|
||||
)
|
||||
return _move_file_impl(source_abs, dest_abs)
|
||||
|
||||
|
||||
def read_directory_as_zip(relative_path: str) -> bytes:
|
||||
@@ -303,10 +260,7 @@ def read_directory_as_zip(relative_path: str) -> bytes:
|
||||
"""
|
||||
abs_path = get_abs_path(relative_path)
|
||||
|
||||
# Use RFC routing for development mode
|
||||
b64_zip = runtime.call_development_function_sync(
|
||||
_read_directory_impl, abs_path
|
||||
)
|
||||
b64_zip = _read_directory_impl(abs_path)
|
||||
return base64.b64decode(b64_zip)
|
||||
|
||||
|
||||
@@ -326,13 +280,13 @@ def find_file_in_dirs(file_path: str, backup_dirs: list[str]) -> str:
|
||||
"""
|
||||
# Try the main path first
|
||||
main_path = get_abs_path(file_path)
|
||||
if runtime.call_development_function_sync(_file_exists_impl, main_path):
|
||||
if _file_exists_impl(main_path):
|
||||
return main_path
|
||||
|
||||
# Try backup directories
|
||||
for backup_dir in backup_dirs:
|
||||
backup_path = os.path.join(backup_dir, file_path)
|
||||
if runtime.call_development_function_sync(_file_exists_impl, backup_path):
|
||||
if _file_exists_impl(backup_path):
|
||||
return backup_path
|
||||
|
||||
# File not found anywhere
|
||||
@@ -340,7 +294,7 @@ def find_file_in_dirs(file_path: str, backup_dirs: list[str]) -> str:
|
||||
|
||||
|
||||
# =====================================================
|
||||
# IMPLEMENTATION FUNCTIONS (Container Operations)
|
||||
# IMPLEMENTATION FUNCTIONS
|
||||
# =====================================================
|
||||
|
||||
def _read_file_binary_impl(file_path: str) -> str:
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
## Purpose
|
||||
|
||||
- Own the `rfc_files.py` helper module.
|
||||
- This module exposes RFC-safe filesystem operations.
|
||||
- This legacy-named module exposes local synchronous filesystem operations.
|
||||
- Keep this file-level DOX profile synchronized with `rfc_files.py` because this directory is intentionally flat.
|
||||
|
||||
## Ownership
|
||||
@@ -44,6 +44,9 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- Public operations call retained implementation functions directly in every runtime mode. Preserve path resolution, backup-directory lookup, return values and filesystem errors; no dispatcher thread or network is involved.
|
||||
- Binary implementation helpers retain their base64 argument/result contracts for compatibility; public binary operations still return bytes.
|
||||
|
||||
- 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: filesystem reads, filesystem writes, filesystem deletion.
|
||||
@@ -51,7 +54,7 @@
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- Important called helpers/classes observed in the source: `os.path.abspath`, `os.path.join`, `find_file_in_dirs`, `runtime.call_development_function_sync`, `base64.b64decode`, `get_abs_path`, `base64.b64encode.decode`, `FileNotFoundError`, `os.path.exists`, `os.path.basename`, `os.path.isfile`, `Exception`, `os.makedirs`, `os.remove`, `os.path.isdir`, `shutil.rmtree`, `os.listdir`, `items.sort`, `tempfile.NamedTemporaryFile`, `zipfile.ZipFile`.
|
||||
- Important called helpers/classes observed in the source: `os.path.abspath`, `os.path.join`, `find_file_in_dirs`, `base64.b64decode`, `get_abs_path`, `base64.b64encode.decode`, `FileNotFoundError`, `os.path.exists`, `os.path.basename`, `os.path.isfile`, `Exception`, `os.makedirs`, `os.remove`, `os.path.isdir`, `shutil.rmtree`, `os.listdir`, `items.sort`, `tempfile.NamedTemporaryFile`, `zipfile.ZipFile`.
|
||||
- Keep request/response, tool, or helper semantics documented here at the same time as source changes.
|
||||
|
||||
## Work Guidance
|
||||
@@ -63,7 +66,7 @@
|
||||
## 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.
|
||||
- Run `pytest tests/test_local_development_calls.py` for local filesystem contracts and errors with development dispatch disabled.
|
||||
|
||||
## Child DOX Index
|
||||
|
||||
|
||||
@@ -35,6 +35,8 @@
|
||||
|
||||
## Runtime Contracts
|
||||
|
||||
- `call_development_function` and its sync counterpart remain legacy compatibility entry points. First-party callers invoke their target functions locally; explicit RFC handling and transports are unchanged. The sync compatibility wrapper retains its historical thread/queue behavior and is not used for normal filesystem operations.
|
||||
|
||||
- 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: filesystem reads, filesystem writes, subprocess/runtime control, settings/state persistence, secret handling, tunnel state.
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Shared sandbox API and CLI: python -m helpers.sandbox --help."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import dataclasses
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from plugins._sandboxing.helpers.images import SandboxImageError, image_info_dict
|
||||
from plugins._sandboxing.helpers.manager import SandboxError, SandboxManager, SandboxMount, sandbox_info_dict
|
||||
|
||||
|
||||
def get_manager() -> SandboxManager:
|
||||
from plugins._sandboxing.helpers.runtime import get_manager as configured_manager
|
||||
return configured_manager()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest="action", required=True)
|
||||
commands.add_parser("list", help="List this Agent Zero instance's sandboxes")
|
||||
commands.add_parser("restore", help="Restore standalone sandboxes marked as running")
|
||||
image_import = commands.add_parser("import-image", help="Import a docker save archive into the sandbox image cache")
|
||||
image_import.add_argument("archive", type=Path)
|
||||
image_import.add_argument("reference", help="Cache reference, for example agent-zero-sandbox:local")
|
||||
create = commands.add_parser("create")
|
||||
create.add_argument("name")
|
||||
create.add_argument("--image", default="", help="Registry image; defaults to system configuration")
|
||||
create.add_argument("--standalone", action="store_true", help="Run detached; survive the caller and restore on A0 startup")
|
||||
create.add_argument("--network", choices=("host", "none"), default="host", help="host: internet and host loopback; none: offline")
|
||||
create.add_argument("--no-usr", action="store_true", help="Do not share Agent Zero usr/ at /a0/usr")
|
||||
create.add_argument("--host-root", action="store_true", help="Explicitly expose the host root at /host")
|
||||
create.add_argument("--temporary", action="store_true", help="Expire after the configured idle lifetime")
|
||||
create.add_argument("--command", nargs=argparse.REMAINDER, default=[])
|
||||
for action in ("inspect", "disk-usage", "start", "stop", "restart", "delete", "exec"):
|
||||
command = commands.add_parser(action)
|
||||
command.add_argument("name")
|
||||
if action == "exec":
|
||||
command.add_argument("argv", nargs=argparse.REMAINDER)
|
||||
if action == "delete":
|
||||
command.add_argument("--yes", action="store_true", required=True)
|
||||
args = parser.parse_args(argv)
|
||||
from helpers import dotenv
|
||||
dotenv.load_dotenv()
|
||||
try:
|
||||
manager = get_manager()
|
||||
if args.action == "list":
|
||||
result = [sandbox_info_dict(item) for item in manager.list()]
|
||||
elif args.action == "restore":
|
||||
result = manager.restore_standalone()
|
||||
elif args.action == "import-image":
|
||||
result = image_info_dict(manager.images.import_archive(args.archive, args.reference))
|
||||
elif args.action == "create":
|
||||
result = sandbox_info_dict(manager.create(
|
||||
args.name, image=args.image, standalone=args.standalone,
|
||||
sandbox_type="temporary" if args.temporary else "permanent",
|
||||
network=args.network, share_usr=not args.no_usr, host_root=args.host_root,
|
||||
command=args.command,
|
||||
))
|
||||
elif args.action == "exec":
|
||||
result = dataclasses.asdict(manager.exec(args.name, args.argv))
|
||||
elif args.action == "delete":
|
||||
result = {"deleted": manager.delete(args.name)}
|
||||
elif args.action == "disk-usage":
|
||||
result = {"name": args.name, "size_bytes": manager.disk_usage(args.name)}
|
||||
else:
|
||||
result = sandbox_info_dict(getattr(manager, args.action)(args.name))
|
||||
print(json.dumps(result, indent=2), flush=True)
|
||||
if args.action in {"create", "start", "restart"} and not result.get("standalone"):
|
||||
try:
|
||||
while manager.is_running(args.name):
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
manager.stop(args.name)
|
||||
return 130
|
||||
return int(result.get("exit_code", 0)) if isinstance(result, dict) else 0
|
||||
except (SandboxError, SandboxImageError, OSError, ValueError) as exc:
|
||||
print(json.dumps({"error": str(exc)}))
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,18 @@
|
||||
# Sandbox Access
|
||||
|
||||
`get_manager()` returns the configured `_sandboxing` manager for this Agent Zero installation. Its persistent instance ID scopes runtime IDs and state; do not construct a second lifecycle implementation here.
|
||||
|
||||
`python -m helpers.sandbox` provides JSON list/create/inspect/start/stop/restart/delete/exec/restore commands. Registry image selection defaults to plugin configuration. Delete requires `--yes`. Child lifetime is default: create/start/restart stay attached for child sandboxes; Ctrl-C stops the child. Use `--standalone` for services that must remain after the command returns. Python callers retain the creating process while child sandboxes are needed.
|
||||
|
||||
Status/lifecycle commands return `size_bytes: null` without scanning storage;
|
||||
child CLI waiting uses `is_running`. Only the explicit `disk-usage NAME` command
|
||||
waits for a measurement. Async Python callers run `manager.disk_usage(name)`
|
||||
through `asyncio.to_thread`; it holds no lifecycle locks. The UI requests the
|
||||
same operation separately through its authenticated API. Verify with
|
||||
`tests/test_sandbox_storage.py` and `tests/test_sandbox_storage.mjs`.
|
||||
|
||||
New filesystems are disk-backed. `/a0/usr` shares the installation's usr directory unless `--no-usr`; host `/` requires `--host-root`. `--network host` (default) includes internet and host loopback, while `none` is offline. This does not expose a Docker Desktop machine's filesystem or loopback beyond the outer container.
|
||||
|
||||
The helper imports no tunnel provider dependencies. Verify with sandbox service tests and the documented live lifecycle smoke checks.
|
||||
|
||||
`import-image ARCHIVE REFERENCE` imports a local `docker save` archive through the image manager's Skopeo/umoci pipeline and returns public image metadata. It does not contact Docker or change the default image setting. Select the imported reference in Sandboxing settings for new sandboxes; cache-only images must be reimported after cache deletion/expiry. Archive and image errors return JSON with a nonzero exit code.
|
||||
@@ -0,0 +1,251 @@
|
||||
"""On-demand plugin workers using private files, without an outer service or port."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from helpers.sandbox import SandboxError, SandboxMount, get_manager
|
||||
|
||||
|
||||
class SandboxWorker:
|
||||
def __init__(self, plugin: str, *, idle_seconds: float | None = 120):
|
||||
self.plugin = plugin
|
||||
self.name = 'service-' + plugin.lstrip('_').replace('_', '-')
|
||||
self.idle_seconds = idle_seconds
|
||||
self.lock = threading.RLock()
|
||||
self.timer: threading.Timer | None = None
|
||||
self.ready = False
|
||||
self.generation = 0
|
||||
self.busy = False
|
||||
self.mounts: list[SandboxMount] = []
|
||||
self.support_files: dict[str, Path] = {}
|
||||
self._progress_lock = threading.Lock()
|
||||
self._progress = {'state': 'idle', 'stage': 'idle', 'message': 'Not started'}
|
||||
self._progress_manager = None
|
||||
self._boot_id = None
|
||||
self._last_log = None
|
||||
|
||||
def _set_progress(self, state: str, stage: str, message: str):
|
||||
with self._progress_lock:
|
||||
now = time.time()
|
||||
if stage == 'sandbox':
|
||||
self._boot_id = None
|
||||
started = now if stage == 'sandbox' else self._progress.get('started_at', now)
|
||||
self._progress = {'state': state, 'stage': stage, 'message': message,
|
||||
'started_at': started, 'updated_at': now, 'stage_started_at': now}
|
||||
|
||||
def status(self) -> dict:
|
||||
"""Read bounded progress without waiting on the setup/request lock or starting a guest."""
|
||||
with self._progress_lock:
|
||||
if self._progress['state'] == 'starting' and self._progress_manager and self._boot_id:
|
||||
manager = self._progress_manager
|
||||
try:
|
||||
progress = json.loads(manager.read_file(self.name, 'var/lib/a0-worker/progress.json', limit=4096))
|
||||
if isinstance(progress, dict) and progress.get('boot') == self._boot_id:
|
||||
stage, message = progress.get('stage'), progress.get('message')
|
||||
if isinstance(stage, str) and isinstance(message, str) and stage != self._progress['stage']:
|
||||
self._progress.update(stage=stage[:64], message=message[:240],
|
||||
stage_started_at=time.time(), updated_at=time.time())
|
||||
log = manager.read_file(self.name, 'var/lib/a0-worker/install.log', limit=4096)
|
||||
if log != self._last_log:
|
||||
self._last_log = log
|
||||
self._progress['updated_at'] = time.time()
|
||||
except (OSError, ValueError, SandboxError):
|
||||
pass
|
||||
result = dict(self._progress)
|
||||
now = time.time()
|
||||
end = now if result['state'] == 'starting' else result.get('updated_at', now)
|
||||
result['elapsed_seconds'] = max(0, int(end - result.get('started_at', end)))
|
||||
result['stage_seconds'] = max(0, int(end - result.get('stage_started_at', end)))
|
||||
result['quiet_seconds'] = max(0, int(end - result.get('updated_at', end)))
|
||||
return result
|
||||
|
||||
def _paths(self):
|
||||
manager = get_manager()
|
||||
# This directory is masked in usr mounts and never exposed to other guests.
|
||||
request_dir = manager.config.instances_dir / '.worker-inputs' / self.name
|
||||
request_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
return manager, request_dir
|
||||
|
||||
def start(self, cancel: threading.Event | None = None):
|
||||
with self.lock:
|
||||
try:
|
||||
return self._start(cancel)
|
||||
except BaseException:
|
||||
self._set_progress('error', 'error', 'Sandbox setup failed or was cancelled; retry to resume installation')
|
||||
raise
|
||||
|
||||
def _start(self, cancel: threading.Event | None):
|
||||
manager, request_dir = self._paths()
|
||||
if self.timer:
|
||||
self.timer.cancel()
|
||||
if self.ready and manager.is_running(self.name):
|
||||
return manager
|
||||
self.ready = False
|
||||
self._set_progress('starting', 'sandbox', 'Initializing sandbox')
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
plugin_dir = root / 'plugins' / self.plugin
|
||||
command = ['/bin/sh', '/worker/boot.sh']
|
||||
support = request_dir / 'support'
|
||||
support.mkdir(exist_ok=True)
|
||||
for filename, source in self.support_files.items():
|
||||
if Path(filename).name != filename:
|
||||
raise ValueError('Invalid support filename')
|
||||
shutil.copyfile(source, support / filename)
|
||||
mounts = [SandboxMount(plugin_dir, '/plugin'),
|
||||
SandboxMount(root / 'plugins/_sandboxing/sandbox', '/worker'),
|
||||
SandboxMount(request_dir, '/request'),
|
||||
SandboxMount(support, '/support'), *self.mounts]
|
||||
boot_id = uuid.uuid4().hex
|
||||
with self._progress_lock:
|
||||
self._boot_id = boot_id
|
||||
self._progress_manager = manager
|
||||
self._last_log = None
|
||||
self._write_request(request_dir, {'boot': boot_id})
|
||||
if (manager.config.instances_dir / self.name / 'metadata.json').exists():
|
||||
info = manager.inspect(self.name)
|
||||
if not info.service or info.ownership.get('plugin_id') != self.plugin:
|
||||
raise SandboxError('Sandbox name is already owned by another caller')
|
||||
manager.stop(self.name)
|
||||
manager.set_mounts(self.name, mounts)
|
||||
manager.set_command(self.name, command)
|
||||
manager.start(self.name)
|
||||
else:
|
||||
manager.create(
|
||||
self.name, sandbox_type='permanent', service=True,
|
||||
standalone=False, share_usr=False, network='host',
|
||||
ownership={'plugin_id': self.plugin}, command=command,
|
||||
mounts=mounts,
|
||||
)
|
||||
deadline = time.monotonic() + 1800
|
||||
state_check = 0
|
||||
while time.monotonic() < deadline:
|
||||
if cancel and cancel.is_set():
|
||||
manager.stop(self.name)
|
||||
raise SandboxError('Sandbox setup cancelled')
|
||||
try:
|
||||
status = json.loads(manager.read_file(self.name, 'var/lib/a0-worker/ready.json'))
|
||||
if status.get('boot') == boot_id:
|
||||
self.ready = True
|
||||
self.generation += 1
|
||||
self._set_progress('ready', 'ready', 'Sandbox ready')
|
||||
return manager
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if time.monotonic() >= state_check:
|
||||
if not manager.is_running(self.name):
|
||||
raise SandboxError(f'{self.plugin} setup exited; see its sandbox /var/lib/a0-worker/install.log')
|
||||
state_check = time.monotonic() + 1
|
||||
time.sleep(.2)
|
||||
manager.stop(self.name)
|
||||
raise SandboxError(f'{self.plugin} dependency setup timed out')
|
||||
|
||||
@staticmethod
|
||||
def _write_request(directory: Path, payload: dict):
|
||||
fd, path = tempfile.mkstemp(dir=directory)
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
json.dump(payload, stream)
|
||||
os.replace(path, directory / 'request.json')
|
||||
finally:
|
||||
Path(path).unlink(missing_ok=True)
|
||||
|
||||
def call(self, payload: dict, *, timeout: float = 120, cancel: threading.Event | None = None,
|
||||
mounts: list[SandboxMount] | None = None):
|
||||
with self.lock:
|
||||
self.busy = True
|
||||
failed = False
|
||||
request_id = None
|
||||
try:
|
||||
if mounts is not None and self.mounts != mounts:
|
||||
self.stop()
|
||||
self.mounts = mounts
|
||||
manager = self.start(cancel)
|
||||
_, directory = self._paths()
|
||||
request_id = uuid.uuid4().hex
|
||||
self._write_request(directory, {'id': request_id, 'payload': payload})
|
||||
deadline = time.monotonic() + timeout
|
||||
state_check = time.monotonic() + 1
|
||||
while time.monotonic() < deadline:
|
||||
if cancel and cancel.is_set():
|
||||
raise SandboxError('Sandbox request cancelled')
|
||||
try:
|
||||
result = json.loads(manager.read_file(self.name, 'var/lib/a0-worker/response.json', limit=128 * 1024 * 1024))
|
||||
except (OSError, ValueError):
|
||||
result = {}
|
||||
if result.get('id') == request_id:
|
||||
if 'error' in result:
|
||||
raise SandboxError(str(result['error']))
|
||||
return result['result']
|
||||
if time.monotonic() >= state_check:
|
||||
if not manager.is_running(self.name):
|
||||
raise SandboxError(f'{self.plugin} worker exited during the request')
|
||||
state_check = time.monotonic() + 1
|
||||
time.sleep(.05)
|
||||
raise SandboxError(f'{self.plugin} request timed out after {timeout:g}s')
|
||||
except BaseException:
|
||||
failed = True
|
||||
raise
|
||||
finally:
|
||||
self.busy = False
|
||||
_, directory = self._paths()
|
||||
self._write_request(directory, {})
|
||||
if self.ready and request_id:
|
||||
# Let the guest discard speech/document results before stopping.
|
||||
deadline = time.monotonic() + 1
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if json.loads(manager.read_file(self.name, 'var/lib/a0-worker/ack.json')).get('id') == request_id:
|
||||
break
|
||||
except (OSError, ValueError, SandboxError):
|
||||
pass
|
||||
time.sleep(.05)
|
||||
if failed:
|
||||
self.stop()
|
||||
elif self.ready and self.idle_seconds is not None:
|
||||
if self.idle_seconds == 0:
|
||||
self.stop()
|
||||
else:
|
||||
self.timer = threading.Timer(self.idle_seconds, self.stop)
|
||||
self.timer.daemon = True
|
||||
self.timer.start()
|
||||
|
||||
async def acall(self, payload: dict, *, timeout: float = 120, mounts: list[SandboxMount] | None = None):
|
||||
cancel = threading.Event()
|
||||
task = asyncio.create_task(asyncio.to_thread(self.call, payload, timeout=timeout, cancel=cancel, mounts=mounts))
|
||||
try:
|
||||
return await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
cancel.set()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
raise
|
||||
|
||||
async def aprepare(self):
|
||||
"""Keep first-use installation outside a caller's processing deadline."""
|
||||
cancel = threading.Event()
|
||||
task = asyncio.create_task(asyncio.to_thread(self.start, cancel))
|
||||
try:
|
||||
await asyncio.shield(task)
|
||||
except asyncio.CancelledError:
|
||||
cancel.set()
|
||||
await asyncio.gather(task, return_exceptions=True)
|
||||
raise
|
||||
|
||||
def stop(self):
|
||||
with self.lock:
|
||||
if self.timer:
|
||||
self.timer.cancel()
|
||||
self.timer = None
|
||||
manager, _ = self._paths()
|
||||
if (manager.config.instances_dir / self.name / 'metadata.json').exists():
|
||||
manager.stop(self.name)
|
||||
self.ready = False
|
||||
if self._progress['state'] != 'error':
|
||||
self._set_progress('idle', 'idle', 'Sandbox stopped')
|
||||
@@ -0,0 +1,24 @@
|
||||
# Plugin sandbox workers
|
||||
|
||||
`SandboxWorker` owns lazy child sandbox creation, private JSON requests, bounded
|
||||
no-symlink response reads, cancellation, serialization and idle shutdown. Plugin
|
||||
installers and model processes run in the guest; files persist after stopping.
|
||||
It does not create listening ports or expose Agent Zero's usr directory. Inputs
|
||||
live below masked manager state and are mounted read-only. No application secrets
|
||||
or inherited host environment are sent to workers. Plugin lifecycle hooks stop
|
||||
their worker on disable; uninstall may delete the owned sandbox through manager.
|
||||
|
||||
`call` is blocking; `acall` offloads it and propagates cancellation to sandbox stop.
|
||||
First-use setup has a separate 30-minute deadline; request timeout begins after
|
||||
setup. Responses are capped at 128 MiB. `process_command` in the manager supports
|
||||
browser driver pipes whose lifetime is owned by the browser adapter.
|
||||
|
||||
`status()` returns setup state/stage/message, timestamps, elapsed time and output
|
||||
inactivity without acquiring the setup/request lock or launching a guest. It reads
|
||||
at most 4 KiB each of boot-matched progress and the private installation log through
|
||||
the manager's no-symlink reader; raw log text is never returned. Installer fingerprints cover install scripts and read-only support files. Installer stages
|
||||
come from `plugins/_sandboxing/sandbox/progress.py`. Readiness remains boot-scoped;
|
||||
errors survive cleanup until the next attempt. Liveness polling uses `is_running`
|
||||
once per second rather than recursively measuring disk usage.
|
||||
|
||||
Verify with `tests/test_sandbox_workers.py` and real plugin sandbox smoke checks.
|
||||
Loaded 100 of 505 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user