diff --git a/AGENTS.md b/AGENTS.md index 6a3b00c9f..933651d21 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,7 +23,7 @@ - `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 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` warms the `cl100k_base` token counter and constructs the configured local embedding model in worker threads; failures remain independent and best-effort. Image asset preparation bundles the tokenizer cache with a failing-on-error token count. Preload 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._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. Extension hooks let provider plugins finalize runtime credentials without changing saved settings. - `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. - `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. diff --git a/README.md b/README.md index 00dbb86de..1ad1ef763 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,7 @@ It is not a replacement for Git or backups. It is a practical safety layer for t | Manage and curate memories | [Memory guide](./docs/guides/memory.md) | | Learn the everyday chat controls | [Usage guide](./docs/guides/usage.md) | | Configure MCP or external tools | [MCP setup](./docs/guides/mcp-setup.md) | +| Talk to Agent Zero from Telegram | [Telegram setup](./docs/guides/telegram.md) | | Understand the architecture and internals | [DeepWiki for Agent Zero](https://deepwiki.com/agent0ai/agent-zero) | | Build an advanced extension | [Extensions](./docs/developer/extensions.md) | | Contribute to the project | [Contributing](./docs/guides/contribution.md) | diff --git a/docs/AGENTS.md b/docs/AGENTS.md index 9413005cc..d1dfd7d8b 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -21,6 +21,9 @@ - `setup/installation.md` and the root README share the Launcher download release and first-message, model-setup, same-chat sequence with the website Installation page. Keep optional Host access after the first result, persistent storage distinct from backups, and local Docker commands paired with their browser URLs. Reuse the verified kickoff-plan example in installation and quickstart; preserve existing manual-install and upgrade anchors. - The root README recommends Launcher for desktops and keeps A0 Install visible for servers and shell access, followed by shared first-message steps. Its Launcher installation screenshot is `res/usage/launcher/launcher-installation.png`; present Apple Silicon as the primary Mac download and label Intel for Intel Macs only. Keep direct Docker and troubleshooting in the "Other install options" accordion; link to the installation guide for scripted setup. - `guides/onboarding.md` covers provider selection and completion: the final Continue action closes the wizard and keeps the existing chat. Keep its Codex Main/Utility suggestions aligned with OAuth provider metadata. +- `guides/telegram.md` owns private-bot setup, access versus administrator lists, scoped bot ownership, groups, webhooks, and upgrade recovery. Keep it aligned with the website Telegram guide and the bundled plugin; captures under `res/usage/telegram/` show unsaved neutral drafts with complete dialog frames and breathing room, never credentials. +- `guides/cleaner.md` owns A0Cleaner's automatic defaults, notifications, scheduling, manual review, and custom folders. Keep it aligned with the website Cleaner guide and bundled plugin. Captures under `res/usage/cleaner/` retain complete panels; the toast uses a saved maintenance result and the custom-folder example is unsaved. Link the guide from the docs index and Usage. +- `guides/task-scheduler.md` owns end-to-end form and natural-chat task creation, cron fields, dedicated/shared conversations, task controls, and missed runs. Keep it aligned with the website Task Scheduler guide and current controls; do not imply Reset State starts/stops work or that scheduled chats expose the ordinary Stop button. Captures under `res/usage/tasks/` show neutral example tasks with complete forms and dialogs. Link it from the docs index, Usage, and A0Cleaner. - Shared Web UI captures under `res/usage/webui/` must show real, optimized, neutral demo state without personal paths, account identities, or community controls presented as built-in features. ## Local Contracts @@ -28,6 +31,7 @@ - Prefer local docs for practical workflows and direct users to DeepWiki for source-linked internals when appropriate. - Do not document secrets, private deployment details, unreleased credentials, or user-specific runtime state. - Screenshots and assets must be relevant to the documented UI state and should be updated when UI changes make them misleading. +- Frame screenshots with comfortable padding and enough of the window or dialog to orient the reader. Avoid crops that hug text or cut off controls; inspect them at their rendered documentation size. - Keep links relative inside the docs tree unless they intentionally point to external community or reference resources. ## Work Guidance diff --git a/docs/README.md b/docs/README.md index 617cba380..feae47d25 100644 --- a/docs/README.md +++ b/docs/README.md @@ -26,6 +26,7 @@ docs focus on practical setup, screenshots, and user workflows. - **[OpenCode Go and Provider Plugins](guides/opencode.md):** Find a missing provider in the Plugin Hub, install OpenCode Go, and choose Main and Utility models. - **[Migrate Agents](guides/migrate-agents.md):** Move real Pi, Hermes Agent, and Claude Code chats, copy their working files, and continue the project in Agent Zero. - **[Usage Guide](guides/usage.md):** Practical tour of Agent Zero's main workflows. +- **[Scheduled Tasks](guides/task-scheduler.md):** Create a recurring task with the form or a normal chat request, find its conversation, and manage later runs. - **[Agent Zero Launcher](guides/launcher.md):** Fresh-machine setup, Installs, Instances, and workspace folder or Docker volume choices. - **[Use Local Folders With Agent Zero](guides/local-folders.md):** Bind mounts, persistent user data, separate work folders, Docker CLI/Desktop/Compose examples, and Launcher storage links. - **[First-Run Onboarding](guides/onboarding.md):** Set up OpenRouter, our proxy API or another provider with the guided wizard. @@ -37,8 +38,10 @@ docs focus on practical setup, screenshots, and user workflows. - **[Agent Profiles](guides/agent-profiles.md):** Create and manage profiles in Easy or Advanced mode, set project availability, and control Tool, MCP, and Skill access. - **[Model Presets](guides/model-presets.md):** Create simple named shortcuts for model setups. - **[Memory Guide](guides/memory.md):** Search, edit, delete, and curate memories so useful context does not become stale noise. +- **[A0Cleaner](guides/cleaner.md):** Free up space with automatic cleanup, understand its notifications, and review files or custom folders yourself. - **[Projects Tutorial](guides/projects.md):** Learn to create isolated workspaces with dedicated context and memory. - **[API Integration](guides/api-integration.md):** Add external APIs without writing code. +- **[Telegram](guides/telegram.md):** Connect a private bot, choose projects and profiles, use groups or webhooks, and preserve existing settings when upgrading. - **[MCP Setup](guides/mcp-setup.md):** Configure Model Context Protocol servers. - **[A2A Setup](guides/a2a-setup.md):** Enable agent-to-agent communication. - **[Troubleshooting](guides/troubleshooting.md):** Solutions to common issues and FAQs. @@ -127,6 +130,7 @@ docs focus on practical setup, screenshots, and user workflows. - [File Browser](guides/usage.md#file-browser) - [Memory Management](guides/usage.md#memory-management) - [Backup And Restore](guides/usage.md#backup-and-restore) + - [Scheduled Tasks](guides/task-scheduler.md) - [Agent Zero Launcher](guides/launcher.md) - [Workspace Storage](guides/launcher.md#workspace-storage) - [Use Local Folders With Agent Zero](guides/local-folders.md) @@ -138,8 +142,10 @@ docs focus on practical setup, screenshots, and user workflows. - [Agent Profiles](guides/agent-profiles.md) - [Model Presets](guides/model-presets.md) - [Memory Guide](guides/memory.md) + - [A0Cleaner](guides/cleaner.md) - [Projects Tutorial](guides/projects.md) - [API Integration](guides/api-integration.md) + - [Telegram](guides/telegram.md) - [MCP Setup](guides/mcp-setup.md) - [A2A Setup](guides/a2a-setup.md) - [Troubleshooting](guides/troubleshooting.md) diff --git a/docs/guides/cleaner.md b/docs/guides/cleaner.md new file mode 100644 index 000000000..c63baedd5 --- /dev/null +++ b/docs/guides/cleaner.md @@ -0,0 +1,162 @@ +# Free up space with A0Cleaner + +A0Cleaner clears the caches, old screenshots, and browser leftovers that build +up as you use Agent Zero. **Automatic cleanup is on by default**, with a weekly +run on Monday at 09:00 in the task's configured timezone. You can change what +it cleans, adjust the schedule, or review a cleanup yourself. + +- [Open the cleaner](#open-the-cleaner) +- [Choose what runs automatically](#choose-what-runs-automatically) +- [Understand the notification](#understand-the-notification) +- [Change the schedule](#change-the-schedule) +- [Review and clean files yourself](#review-and-clean-files-yourself) +- [Add a custom folder](#add-a-custom-folder) +- [Check results](#check-results) + +## Open the cleaner + +Open **Plugins → Builtin**, search for **A0Cleaner**, and select **Open**. +You can also choose **Config → Open A0Cleaner**. + +![Builtin Plugins filtered to A0Cleaner, with Open and Config buttons](../res/usage/cleaner/plugin-entry.png) + +The cleaner scans when you first open it, or when its previous scan is more +than an hour old. Select **Scan now** whenever you want fresh numbers. +Scanning does not delete anything. + +**Ready to clean** is the total found across the cleanup areas. The amount +beside **Review cleanup** is just your current selection. The disk meter +shows the storage available to your Agent Zero instance. + +## Choose what runs automatically + +The **Automatic cleanup** switch controls whether scheduled runs delete files. +Each area's **Auto** switch lets you keep that category out of future automatic +cleanups. These choices save as you change them. + +![A0Cleaner with the weekly schedule, automatic switches, full cleanup list, and Review cleanup button](../res/usage/cleaner/cleanup-overview.png) + +These are the defaults: + +| Area | Automatic | Files considered | +| --- | --- | --- | +| Python and Node download caches | On | Unchanged for 30 days. Packages can be downloaded again. | +| Installer leftovers | On | Temporary plugin and skill installation files older than 7 days. | +| Retired browser profiles | On | Profiles unchanged for 30 days. Shared and running profiles are kept. | +| Old chat screenshots | On | Screenshots older than 30 days in chats inactive for at least 30 days. Running and paused chats are kept. | +| Temporary captures | On | Browser and desktop captures older than 30 days. | +| Unused browser versions | On | Old Chromium installations unchanged for 30 days. Required and running versions are kept. | +| Embedding cache | Manual only | Cached embeddings older than 30 days. | +| Custom folders | Manual only | Files matching the age you choose for that folder. | + +Clearing a retired browser profile removes its saved sign-ins and tabs. +Clearing screenshots removes those old previews. Turn off the corresponding +**Auto** switch if you want to keep them. + +Expand **Cleanup ages** to change the cutoffs for **Download caches**, +**Installer leftovers**, or **Browser & chat files**. The last setting also +applies to the embedding cache. An age is an eligibility cutoff, not a promise +to delete every file: files in use or recently changed are skipped. + +Built-in cleanup keeps chat text, uploaded files, installed models, and +applications. It cleans specific locations inside `/a0/tmp`; it does not sweep +Linux's separate `/tmp` directory or `/a0/usr/uploads`. Uploads can still be +needed by saved chats or queued messages. Time Travel manages its own retention. + +## Understand the notification + +After a scheduled run, Agent Zero tells you what happened. If files remain for +review, the toast says **A0 found … of unused files** and offers **Clean up**. +If it also cleaned files automatically, that amount appears underneath. + +![Automatic cleanup notification showing 58.5 MB for review, 4.4 GB cleaned automatically, and a Clean up button](../res/usage/cleaner/automatic-toast.png) + +This example uses a saved maintenance result: 4.4 GB had already been cleaned, +and 58.5 MB remained for review. Your amounts will depend on your instance. + +**Clean up opens the cleaner.** You still choose the areas and confirm before +a manual cleanup deletes anything. + +The toast follows the schedule, so it normally appears once a week. It is not +triggered by **Scan now** or by opening the cleaner. Running the A0Cleaner task +manually from Tasks can also show it. A review toast stays until +you dismiss it with **×**; an unread one can reappear after refreshing the page. +When a run only cleans files and leaves nothing to review, the success toast +closes after about six seconds. If it finds and cleans nothing, there is no toast. + +## Change the schedule + +Under **Automatic care**, choose **Daily**, **Weekly**, **Monthly**, or **Off**. +The presets run at 09:00: weekly on Monday, monthly on the first day of the month. + +Select the sliders button, **Schedule details**, to open the **A0Cleaner** task. +Use **Edit** to change its time or cron schedule. For a different timezone, +ask the agent to update the A0Cleaner task. You can also find it in +[Scheduled Tasks](task-scheduler.md). + +- To keep scheduled scans and notifications but decide on every deletion, + turn **Automatic cleanup** off and leave the schedule on. +- To stop scheduled scans as well, set the schedule to **Off**. You can still + open the cleaner and scan manually. + +If the container is off at the scheduled time, an enabled, idle task catches up +once after Agent Zero starts again. Several missed runs become one cleanup, +then the normal schedule resumes. Disabled tasks stay paused; failed or +interrupted runs need attention in Tasks. + +## Review and clean files yourself + +1. Select **Scan now** for an up-to-date list. +2. Use the checkboxes on the **left** to select only the areas you want to clean + this time. Automatic areas with eligible files may already be selected. + These boxes do not change the **Auto** switches on the right. +3. Select **Review cleanup**. Read the effect of each selected area and expand + the file count to inspect the listed paths. +4. Select **Clean up** to permanently remove the selected files, or **Cancel** + to leave them alone. + +![Cleanup confirmation for the embedding cache, with the amount, consequences, file list, Cancel, and Clean up](../res/usage/cleaner/review-cleanup.png) + +The embedding cache always needs your selection and confirmation. Embeddings +will be rebuilt when needed, which can use model credits if you use a remote +embedding provider. + +## Add a custom folder + +Use **Custom folders** for a scratch folder you deliberately want to clear. +Choose an existing subfolder inside A0's workdir, a project, downloads, uploads, +or `/a0/tmp`. Use the container path, such as `/a0/usr/workdir/cleanup-demo`, +rather than a path on your host computer. + +![Custom folders tab with an example folder path and a 30-day cutoff, before adding the rule](../res/usage/cleaner/custom-folder.png) + +1. Enter the **Folder path**. +2. Set **Older than** in days. For example, `30` keeps recently changed files. + `0` includes all eligible files regardless of age. +3. Select **Add folder**. The cleaner scans it and adds a row with its size. +4. Select that folder's checkbox, check your total selection, and use + **Review cleanup**. + +Custom folders are **always manual**, even when automatic cleanup is on. +The **×** beside a folder removes its rule, not its contents. Project roots, +protected configuration, Git history, and managed cleanup locations cannot be +added as custom targets. + +Choose folders whose contents you can discard. Adding an uploads subfolder +does not check whether a chat still references its files. + +## Check results + +**Last run** keeps the latest scheduled result visible, even after you run a +fresh scan. Open **Activity** for the cleanup history, including automatic or +manual runs, space cleaned, file counts, and skipped files. + +| What you see | What to do | +| --- | --- | +| No files found | Check the ages and scan again after more use. A small result is normal after a recent cleanup. | +| An area is in use or could not be inspected | Let the related work finish, then scan again. The cleaner leaves unverified files alone. | +| Some files were skipped | Files may have changed or become active since the scan. Scan again before reviewing another cleanup. | +| A preview is no longer valid | Run **Scan now** and review the new selection. | +| Disk space changed less than the cleanup amount | Sizes are estimates. Docker's image layers and host storage can make reclaimed space differ from the reported file total. | + +For the implementation reference, see the [A0Cleaner README](../../plugins/_a0_cleaner/README.md). diff --git a/docs/guides/task-scheduler.md b/docs/guides/task-scheduler.md new file mode 100644 index 000000000..254656a34 --- /dev/null +++ b/docs/guides/task-scheduler.md @@ -0,0 +1,171 @@ +# Create a scheduled task + +Ask Agent Zero to do something on a schedule, then come back to its results. +You can create a task in **Scheduled Tasks** or describe what you want in a +normal chat. Both methods save it in the same task list. + +This guide uses two examples: Sunday dinner ideas created with the form, and +a weekday writing warm-up created through chat. + +- [Open Scheduled Tasks](#open-scheduled-tasks) +- [Create a task with the form](#create-a-task-with-the-form) +- [Create a task through chat](#create-a-task-through-chat) +- [Find the task and its conversation](#find-the-task-and-its-conversation) +- [Run, pause, edit, or delete a task](#run-pause-edit-or-delete-a-task) +- [Check timing and missed runs](#check-timing-and-missed-runs) + +## Open Scheduled Tasks + +Open **More options**, the dropdown arrow at the top of the sidebar, then +select **Scheduled Tasks**. The modal lists saved tasks and their states. + +![Sidebar dropdown with Scheduled Tasks](../res/usage/tasks/open-scheduled-tasks.png) + +Select **New Task** to open the creation form. + +## Create a task with the form + +Let's set up dinner ideas for Sunday at 18:00. Fill in these fields: + +| Field | What to enter | +| --- | --- | +| **Task Name** | `Sunday meal ideas`, or another name you will recognize. | +| **Type** | **Scheduled (Cron)** for a repeating task. | +| **Project** | **No project** for this example. Choose a project if the task needs its files, instructions, or connections. The form initially uses the active chat's project. | +| **State** | **Idle (ready to run)**. Choose **Disabled** if you want to save it without enabling scheduled runs yet. | +| **Schedule** | Minute `0`, Hour `18`, Day `*`, Month `*`, Weekday `0`. | +| **System Prompt** | Optional guidance for how to respond. For example: “Keep suggestions practical and use everyday ingredients.” | +| **User Prompt** | The work to do each time. Use the dinner request below. | +| **Attachments** | Optional file paths inside Agent Zero or URLs, one per line. Leave empty for this example. | + +For **User Prompt**, enter: + +> Suggest three easy vegetarian dinners for two for the coming week. Keep each +> recipe under 30 minutes and give me one combined shopping list. + +Put the timing in **Schedule** and the work in **User Prompt**. The task's +prompt should ask for the dinners, not ask Agent Zero to create another task. +Use **Expand** beside either prompt if you need more room to write. + +![Completed task form for Sunday meal ideas, including the schedule, prompts, attachments, and Save](../res/usage/tasks/create-recurring-task.png) + +### Read the five schedule fields + +The fields run from left to right: **Minute, Hour, Day, Month, Weekday**. +`*` means every value in that field. Hours use the 24-hour clock, and weekday +`0` means Sunday; `1` through `6` mean Monday through Saturday. + +| When | Minute | Hour | Day | Month | Weekday | +| --- | --- | --- | --- | --- | --- | +| Every day at 09:00 | `0` | `9` | `*` | `*` | `*` | +| Weekdays at 08:30 | `30` | `8` | `*` | `*` | `1-5` | +| Sundays at 18:00 | `0` | `18` | `*` | `*` | `0` | + +**Five asterisks means every minute.** Replace the fields before saving. +New tasks use the timezone in **Settings → Agent → Locale**. With **Automatic +(browser)** selected, that comes from your browser. + +For a one-time job, choose **Planned (Specific Times)**, pick the date and time, +and select **Add Time** before saving. You can add more than one date. +**Ad-hoc (Manual)** saves a task you run on demand, without a repeating schedule. + +### Save and check it + +Select **Save**. The form closes and **Sunday meal ideas** appears in the list. +**Idle** means ready for its next scheduled run; saving it does not run it +immediately. + +![Saved Sunday meal ideas task in the Scheduled Tasks list, with Idle selected in the state filter](../res/usage/tasks/saved-task-list.png) + +Click its row to inspect the saved details. To try it now, select the triangle +button, **Run Task**, or **Run** inside Task Details. Open its conversation from +the sidebar **Tasks** section to watch the work and read the result. + +## Create a task through chat + +You can skip the form and ask in your own words. For example: + +> Every weekday at 8:30 in the morning, give me a quick writing warm-up: a fun +> prompt I can finish in ten minutes and one tip to help me start. Keep these +> in their own chat so I can find them easily. + +Send this in a normal chat. If you want the task to belong to a project, open +a chat in that project first. Mention a timezone if the time should be +different from your Agent Zero setting. + +![A real chat request for a weekday writing warm-up and Agent Zero's confirmation of the saved task](../res/usage/tasks/create-from-chat.png) + +Wait for Agent Zero to confirm that it created the task. Then open +**More options → Scheduled Tasks** and find **Writing warm-up**. Click its row +to check the saved schedule and instructions. In this example, the schedule is +`30 8 * * 1-5`: weekdays at 08:30. + +![Task Details for the chat-created Writing warm-up, with its saved schedule and prompts](../res/usage/tasks/task-details.png) + +The wording of the confirmation can vary. The saved task is what tells you +the automation exists. If Agent Zero asks a follow-up question, answer it and +check the list once creation is confirmed. + +## Find the task and its conversation + +**Scheduled Tasks** is the complete list. Use its **Type** and **State** filters +to narrow it down. If a task seems missing, return to **All Types** and +**All States**. + +Tasks with a **dedicated chat** also appear under **Tasks** in the sidebar. +Expand that section if it is collapsed, then select a task's name to open its +conversation. Both the form and the agent normally create dedicated chats; +each task's results stay together across runs. + +![Sidebar Tasks section containing Writing warm-up and Sunday meal ideas](../res/usage/tasks/sidebar-task-chats.png) + +If you ask Agent Zero to run a task in the current conversation instead, its +results stay in that shared chat under **Chats**. The task still appears in +**Scheduled Tasks**, but it does not get a separate sidebar task entry. + +Plugin tasks such as [A0Cleaner](cleaner.md) can also appear in Scheduled Tasks. +They run the plugin's operation and do not need a task conversation. + +## Run, pause, edit, or delete a task + +Click a task's row for **Task Details**, including its schedule, **Last Run**, +**Last Result**, and saved prompts. For the ongoing conversation, select its +sidebar task entry. + +| What you want | What to use | +| --- | --- | +| Run it now or run it again | **Run Task** (triangle) in the list, or **Run** in Task Details. A disabled task must be enabled first. | +| Pause the agent's current work | Open its conversation and select **Pause Agent**. Use **Resume Agent** to continue. | +| Stop future scheduled runs | **Edit Task** (pencil), choose **Disabled**, then **Save**. This does not cancel work already running. | +| Enable it again | Edit its state to **Idle** and save. | +| Change the prompt or schedule | **Edit Task**, update the fields, then **Save**. The task's type and project cannot be changed in this editor. | +| Make an interrupted task ready again | **Reset State** (circular arrow) returns it to **Idle**. It does not run the task or clear its conversation. | +| Delete it | **Delete Task** (trash), then click the confirmation checkmark. Deleting a dedicated task also removes its task chat. | +| Clear its conversation | **Clear task chat** in the sidebar. This erases the task's chat history while keeping its definition. It is not needed for an ordinary rerun. | + +Scheduled runs currently do not show the regular **Stop agent** button. +Use **Pause Agent** when you need to interrupt the agent without deleting its +conversation. Resetting a state is not a way to stop work that is still running. + +The state badges help you see what needs attention: **Idle** is ready, +**Running** is executing, **Disabled** is switched off, and **Error** needs a +look at the result or chat. Use **Run Task** to start work; selecting a state +label does not start an agent run. + +## Check timing and missed runs + +Agent Zero needs to be running to do the work. If a recurring task misses its +time while the container is off, an enabled, idle task catches up once after +startup. Several missed occurrences become one run, then the normal schedule +resumes. Disabled or failed tasks do not catch up automatically, and a run +interrupted by shutdown needs your attention. + +Changing a recurring schedule or re-enabling a task starts its timing from +that change. Existing tasks keep their saved timezone; changing Locale does +not rewrite them. You can ask in chat, for example, “Change my writing warm-up +to 8:30 London time.” + +Try the work once before relying on it unattended. A scheduled inbox summary +still needs a working email connection, and a task that uses an AI model uses +your normal model account and settings. Its results appear in Agent Zero; +delivery to email or another app needs to be part of the request and configured. diff --git a/docs/guides/telegram.md b/docs/guides/telegram.md new file mode 100644 index 000000000..3489d3df0 --- /dev/null +++ b/docs/guides/telegram.md @@ -0,0 +1,324 @@ +# Use Agent Zero from Telegram + +Connect a Telegram bot, choose who can use it, and talk to Agent Zero from your +phone. Conversations also appear in the Web UI, so you can pick up the same work +at your desk. + +Start with **one private bot using Polling**. You do not need a public website, +an incoming port, or a tunnel. Agent Zero must remain running and able to reach +Telegram; model usage follows your normal Agent Zero configuration. + +If you already have a bot, start with [Upgrading an existing setup](#upgrading-an-existing-setup). +The screenshots use an unsaved example configuration, with no real credentials. + +- [Connect your first bot](#connect-your-first-bot) +- [Choose who can use it](#choose-who-can-use-it) +- [Use commands and attachments](#use-commands-and-attachments) +- [Use projects and agent profiles](#use-projects-and-agent-profiles) +- [Add a bot to a group](#add-a-bot-to-a-group) +- [Use a webhook](#use-a-webhook) +- [Upgrading an existing setup](#upgrading-an-existing-setup) +- [Troubleshooting](#troubleshooting) + +## Connect your first bot + +### 1. Check Agent Zero first + +Send a short message in the Web UI and make sure Agent Zero replies. If model +setup is incomplete, finish [Onboarding](onboarding.md) before connecting +Telegram. A working bot token does not configure an AI model. + +### 2. Create a bot with BotFather + +Open the official [@BotFather](https://t.me/BotFather) in Telegram, send +`/newbot`, and follow its prompts for a display name and a unique bot username. +BotFather gives you a **bot token**. Keep it private: it controls the bot. +You do not need to write code or install another Telegram plugin. + +Your bot's `@username`, your own `@username`, and the token are different things. +The token goes in Agent Zero; your own account goes in **Allowed users**. +See Telegram's [bot creation guide](https://core.telegram.org/bots/features#creating-a-new-bot) +for the BotFather steps. + +### 3. Open Telegram settings + +In Agent Zero, open **Plugins → Builtin**, search for **Telegram**, and click +**Config** on **Telegram Integration**. The welcome screen's **Connect Channels → +Telegram** shortcut opens the same settings when that card is visible. + +![Builtin Plugins filtered to Telegram Integration, with its Config button](../res/usage/telegram/plugin-entry.png) + +For your first bot, leave **Project: Global** and **Agent profile: All profiles** +at the top. Make sure the plugin's **Enabled** toggle is on. If a bot is already +listed, use **Connect another bot** to add a different bot, or open the existing +card to edit it. + +![Telegram settings scope set to Global and All profiles](../res/usage/telegram/settings-scope.png) + +In **Connect your bot**, paste the token into **Bot token**, then click **Next**. +The QR code opens BotFather; it does not sign in to your personal Telegram +account. + +![Connect your bot step with the BotFather QR code and an empty token field](../res/usage/telegram/connect-bot.png) + +### 4. Make it private before saving + +In **Choose who can use it**, use these settings: + +| Setting | First-bot choice | +| --- | --- | +| Bot name | A short internal label, such as `personal_bot`. This does not rename the Telegram account. | +| Delivery mode | **Polling**. | +| Allowed users | Your own exact `@username` from Telegram Settings, or your numeric Telegram user ID. | +| Administrator users | Leave empty to manage settings only from the Web UI. | +| Default project | **No project**, or an existing project where new conversations should start. | +| Turn on this bot | Enable it once the access list is filled in. | + +Replace `@your_username` in the example below with your own account. Do not use +the bot's username, a phone number, or a group chat ID. + +![Example private bot using polling, with one allowed username and no administrators](../res/usage/telegram/private-access.png) + +Click **Next**. In **Shape the conversation**, choose **Ignore group messages** +for a private-message-only bot. Optional **Agent instructions** can ask for +shorter, mobile-friendly replies. Click **Save** when you finish the wizard. + +**Allowed users must not be empty for a private bot.** An empty list lets anyone +who finds the bot reach your Agent Zero and use the capabilities available to +its agent. A hard-to-guess bot username is not an access control. + +### 5. Verify the full conversation + +Use **Check the connection** in the bot card to validate the token. A successful +check means Telegram accepted the credentials; it does **not** prove that +delivery, permissions, or the AI model are working. The **Live** label reflects +the configuration, not a completed message exchange. + +After saving, allow a short time for the bot to start. In Telegram: + +1. Open **your new bot**, not BotFather, and tap **Start** or send `/start`. +2. Send `/status` to check the chat's project, agent profile, and model. +3. Send `Reply with: Telegram is ready.` and wait for the agent's response. +4. Find the Telegram conversation in Agent Zero's Web UI. + +If `/status` works but the normal message fails, check the model configuration +and the conversation's error in the Web UI. If neither arrives, use the +[troubleshooting table](#troubleshooting). + +## Choose who can use it + +**Allowed users** is a comma-separated list, for example +`@your_username, @teammate_username`. Use numeric Telegram **user IDs** when you +know them: they keep the rule tied to the account when a username changes. +If using usernames, copy their spelling exactly and review the list after +account changes. Do not clear the list just to troubleshoot an access problem. + +**Administrator users** is a separate list. Administrators must also pass +**Allowed users**. Leave it empty unless you want trusted users to change +settings from Telegram: + +- `/permissions` changes the current profile's tool permissions in its scope. +- `/plugins` can change plugin activation for the **whole instance**. +- Administrators can attach an otherwise unbound Web UI chat using `/sessions`, + if its project/profile is accessible to the bot. + +This list is unrelated to Telegram group administrators or ownership in +BotFather. Those roles do not automatically grant Agent Zero administration. + +Each sender has a separate conversation binding for that bot and Telegram chat. +Another Telegram user's bound sessions are not available in the session picker. +Group replies are still visible to members of the group. Separate conversations +and scoped routing are not a sandbox for files or tools: give trusted people +access and choose suitable [agent permissions](agent-profiles.md). + +## Use commands and attachments + +Send `/commands` to see the commands available to the current chat. Custom and +project commands can change that list. Common built-in actions include: + +| Command | What it does | +| --- | --- | +| `/status` | Show the current project, agent, model, and queue state. | +| `/new` | Start a new conversation; keep the previous one. | +| `/sessions` | Choose an accessible conversation bound to this bot, user, and chat. | +| `/project`, `/agent`, `/model` | Open a picker; choices must respect the bot's scope and permissions. | +| `/stop` | Stop the current work. | +| `/compact` | Ask for confirmation before summarizing a long conversation. | +| `/copy` | Send the conversation transcript as a text file. | +| `/clear` | Reset the current conversation; use `/new` when you want to retain it. | + +Use Telegram's attachment button for photos, documents, audio, voice messages, +or video. Add a caption explaining what you want. Agent Zero can send files back; +what it can understand or produce depends on your models and enabled tools. + +Under **Advanced**, **Attachment max age** controls cleanup of downloaded +attachments in **hours**. `0` keeps them indefinitely. This setting does not +delete the Telegram message or act as a complete chat-retention policy. + +## Use projects and agent profiles + +A **project** supplies the workspace and project instructions. An **agent +profile** supplies the agent's role and configuration. The **Settings scope** +selectors determine who owns the Telegram configuration: + +| Project selector | Agent profile selector | Bot ownership | +| --- | --- | --- | +| Global | All profiles | General-purpose bot; can use destinations that inherit its configuration and permit Telegram. | +| A project | All profiles | Bot stays in that project; it can use permitted profiles there. | +| Global | A profile | Bot stays on that profile; it can use permitted projects. | +| A project | A profile | Bot stays in that project and on that profile. | + +Create the project/profile first, then select it at the top of Telegram settings. +The chosen profile must be available in the chosen project. See +[Projects](projects.md) and [Agent Profiles](agent-profiles.md). + +### One saved configuration, one set of bot accounts + +**Each explicitly saved scope needs different Telegram bot accounts.** For +example, use one bot for personal work and another for a support project. One +scope can contain several bots, but none of their tokens can also belong to +another saved scope or another running Agent Zero instance. + +To reuse a setup in a new scope: + +1. Create another bot with BotFather's `/newbot`. +2. Select the destination project/profile in Telegram settings. +3. Copy the settings you need, but replace every inherited/copied token with + the token for the new bot before saving. Remove bot entries you do not need. +4. Review Allowed users and Administrator users for this destination. +5. Save, open the new bot in Telegram, and verify `/status` and a normal reply. + +Copying a token does not clone a bot. Rotating a token also keeps the same bot +identity, so it does not solve a duplicate-scope conflict. + +### Inheritance does not need another bot + +If a scope has no saved Telegram configuration, it can inherit an existing one +without starting another connection. A saved scoped configuration replaces the +**whole bot list** for that scope; lists are not merged. Use **Show existing +configurations** to see where overrides exist. + +The **Enabled** toggle also has scopes. Disabling Telegram for a project/profile +blocks delivery there even when the bot is inherited. An explicitly enabled +scoped bot can run while the global plugin is disabled. Use **Review saved +activation overrides** when that button is shown. + +For a global bot, **Default project** and **Advanced → User project mapping** +choose where new conversations start. A mapping looks like +`123456789=support_project`, using the Telegram user ID and the actual project +name. These are starting destinations, **not project access restrictions**. +Use a project-owned bot when it must remain in one project. Changing a default +or mapping does not move an already-bound conversation; use an allowed picker +choice or `/new`. + +To **move** a bot instead of creating another, remove its token from the old +configuration and save before adding it to the new scope. Old chats remain, +but the destination scope starts its own session bindings. Keep an existing +**Bot name** unchanged when you want to preserve its current bindings. + +## Add a bot to a group + +First verify a private conversation. Add the bot to the group, keep Allowed users +limited to the people who should use it, and choose **Group behavior**: + +| Choice | Behavior | +| --- | --- | +| Reply when @mentioned or replied to | Agent Zero handles mentions and replies to the bot among messages Telegram delivers. | +| Reply to every group message | Agent Zero handles every delivered message from allowed users. | +| Ignore group messages | Private conversations only. | + +Telegram has its own **Privacy Mode**, separate from this setting. With privacy +enabled, start with `/start@YourBotUsername` and then **reply to a bot message**. +A plain `@mention` is not a reliable delivery test. If you intentionally need +every group message, change the bot's privacy setting in BotFather and re-add +it to the group so the change takes effect. Do not grant group administration +just to make replies work. See Telegram's +[Privacy Mode explanation](https://core.telegram.org/bots/features#privacy-mode). + +**Welcome new members** and **Welcome message** are optional; `{name}` inserts +the new member's name. Group membership and group-admin status never replace +the Agent Zero access lists. + +## Use a webhook + +Stay with Polling unless you already operate a public HTTPS endpoint. Both modes +support the same Agent Zero conversations; webhooks change how updates arrive. + +1. Set **Delivery mode → Webhook**. +2. Set **Webhook URL** to the public Agent Zero **base URL**, such as + `https://agent.example.com`. Agent Zero appends the webhook route; do not + paste a bot token or manually constructed Telegram API URL here. +3. Under **Advanced**, set **Webhook secret** to a random value of 32–256 letters, + digits, underscores, or hyphens. This is separate from the bot token. One + way to generate a suitable value locally is: + + ```bash + python3 -c 'import secrets; print(secrets.token_urlsafe(32))' + ``` + +4. Save. Ensure Telegram can reach the endpoint through a valid HTTPS setup and + that your reverse proxy forwards the `X-Telegram-Bot-Api-Secret-Token` header. + Keep Web UI authentication in place; a webhook is not a reason to expose the + rest of Agent Zero without protection. +5. Repeat `/status` and the normal-message test. The connection-check button + validates the token, not public webhook reachability. + +Agent Zero rejects missing or incorrect webhook secrets, and rejects webhook +delivery to polling bots. Returning to Polling removes its webhook. Do not run +another polling process or service with the same bot token. Telegram's +[webhook FAQ](https://core.telegram.org/bots/faq#im-having-problems-with-webhooks) +covers its HTTPS requirements. + +## Upgrading an existing setup + +You do not need to recreate working bot settings. Before the first bot lifecycle +pass after this upgrade, Agent Zero automatically backs up existing Telegram +configurations, activation overrides, and session mappings under: + +```text +usr/plugins/_telegram_integration/backups/config-scopes-v1/ +``` + +Existing values and mappings are retained. The one automatic settings change is +to generate a valid secret for a legacy webhook configuration whose secret is +missing or invalid. Valid secrets are kept. No administrator is added, and +access lists are not widened or merged. A pre-existing empty Allowed users list +stays open, so review it after upgrading. + +The backup contains credentials: keep it private and include your persistent +`usr/` data in normal [backups](usage.md#backup-and-restore). It is a migration +snapshot, not a replacement for a complete backup. No manual migration command +is needed. + +**Scoped settings alone no longer pause every bot.** If old configurations reuse +the same bot, all conflicting connections pause until you resolve the duplicate: + +1. Open **Show existing configurations** and inspect each saved scope. +2. Decide which scope should keep the original bot. +3. Remove that bot entry/token from other scopes, or replace it with a newly + created bot. Save each change. Merely turning a duplicate bot off does not + remove its saved ownership. +4. Review activation overrides and test again after the manager reloads. + +No conflicting files are automatically deleted and no scope is silently chosen +over another. Keep bot names stable; deliberately renaming a bot or moving it +to another scope starts new session bindings while retaining the previous chats. + +## Troubleshooting + +| What you see | What to check | +| --- | --- | +| Telegram is missing from the list | Choose **Builtin**, not Browse or Custom. Search for **Telegram Integration**. | +| Token check fails | Copy the token from the correct BotFather bot, remove accidental whitespace, and check outgoing network access. If exposed, revoke it in BotFather and update the owning configuration. | +| Token check passes, but no replies | Save the settings; check both Enabled and Turn on this bot, Allowed users, destination scope, and activation overrides. Open the bot and send `/start`. Check Web UI notifications/logs for startup errors. | +| `/status` works, but normal messages fail | Open the same chat in the Web UI and check its model, credentials, provider availability, and tool errors. | +| Works privately, silent in a group | Check Group behavior, the sender's access entry, and Telegram Privacy Mode. Test with a command addressed to the bot and a reply to its message. | +| Save reports a reused bot, or bots pause after upgrade | Review every saved configuration. Remove or replace duplicate bot accounts, including old/rotated tokens. Check that another instance is not running the same bot. | +| `/project` or `/agent` refuses a choice | The bot must stay within its owning scope; the destination must permit Telegram, inherit the right bot, and make the profile available. | +| `/sessions` does not show a chat | Only accessible sessions belonging to this bot, user, and Telegram chat are listed. An explicit administrator may also attach an unbound Web UI chat. | +| `/plugins` or `/permissions` is unavailable | The sender must pass Allowed users and be listed in Administrator users. An empty administrator list intentionally disables those settings changes. | +| Webhook bot is silent | Check the public base URL, HTTPS, reverse-proxy routing, and secret header. Use a real message to test delivery. | +| Saved settings cannot be read | Review the affected configuration in the Web UI or restore it from your backup. Delivery pauses rather than falling back to more permissive settings. | + +For implementation details, see the [plugin reference](../../plugins/_telegram_integration/README.md) +and [Agent Zero on DeepWiki](https://deepwiki.com/agent0ai/agent-zero). diff --git a/docs/guides/usage.md b/docs/guides/usage.md index dcd8fc9c5..4f55d22f8 100644 --- a/docs/guides/usage.md +++ b/docs/guides/usage.md @@ -109,6 +109,10 @@ when the work should run later or on a schedule. Plugins add integrations, tools, panels, and automation helpers. +For storage housekeeping, use the built-in [A0Cleaner](cleaner.md). Its guide +covers automatic cleanup, weekly notifications, and manual cleanup of selected +areas or custom folders. + Open **Plugins** from the dashboard or sidebar to see what is installed. ![Plugins](../res/usage/plugins/plugins-list-01.png) @@ -323,39 +327,18 @@ See the [Projects guide](projects.md) for the full screenshot walkthrough. Tasks let Agent Zero run work later, repeatedly, or on demand. -Use tasks for: +Open the sidebar's **More options → Scheduled Tasks**, select **New Task**, fill +in the form, and **Save**. You can also ask in a normal chat, for example: -- morning or weekly reports; -- monitoring a source and summarizing changes; -- recurring cleanup or export jobs; -- project-specific checks; -- manual batch jobs you want to run again. +> Every weekday at 8:30 in the morning, give me a quick writing warm-up: a fun +> prompt I can finish in ten minutes and one tip to help me start. Keep these +> in their own chat so I can find them easily. -Open **Tasks** from the dashboard or sidebar. +Both methods save the task in **Scheduled Tasks**. A task with its own chat +also appears under **Tasks** in the sidebar, where you can read its results. -![Task scheduler](../res/usage/tasks/scheduler-1.png) - -When creating a task, focus on four things: - -- **Name:** what you will recognize later. -- **Type:** scheduled, planned, or ad-hoc. -- **Project:** optional, but recommended when the task needs specific context or secrets. -- **Prompt:** the actual work Agent Zero should perform. - -![Edit task](../res/usage/tasks/edit-task.png) - -Example: - -```text -Name: Weekly docs review -Type: Scheduled -Project: Documentation -Prompt: Check the docs project for stale screenshots, broken links, and confusing sections. Summarize what needs attention. -``` - -Project-scoped tasks inherit project instructions, variables, secrets, files, and -memory. That means you can improve task behavior later by improving the project -instead of repeating every rule in every task. +Follow [Create a scheduled task](task-scheduler.md) for both complete +walkthroughs, schedule examples, task controls, and what happens after downtime. ## Secrets And Variables diff --git a/docs/res/usage/cleaner/automatic-toast.png b/docs/res/usage/cleaner/automatic-toast.png new file mode 100644 index 000000000..ce4662a7b Binary files /dev/null and b/docs/res/usage/cleaner/automatic-toast.png differ diff --git a/docs/res/usage/cleaner/cleanup-overview.png b/docs/res/usage/cleaner/cleanup-overview.png new file mode 100644 index 000000000..554a88935 Binary files /dev/null and b/docs/res/usage/cleaner/cleanup-overview.png differ diff --git a/docs/res/usage/cleaner/custom-folder.png b/docs/res/usage/cleaner/custom-folder.png new file mode 100644 index 000000000..f0da90249 Binary files /dev/null and b/docs/res/usage/cleaner/custom-folder.png differ diff --git a/docs/res/usage/cleaner/plugin-entry.png b/docs/res/usage/cleaner/plugin-entry.png new file mode 100644 index 000000000..a9699cdf7 Binary files /dev/null and b/docs/res/usage/cleaner/plugin-entry.png differ diff --git a/docs/res/usage/cleaner/review-cleanup.png b/docs/res/usage/cleaner/review-cleanup.png new file mode 100644 index 000000000..7656e177b Binary files /dev/null and b/docs/res/usage/cleaner/review-cleanup.png differ diff --git a/docs/res/usage/tasks/create-from-chat.png b/docs/res/usage/tasks/create-from-chat.png new file mode 100644 index 000000000..39b388e6d Binary files /dev/null and b/docs/res/usage/tasks/create-from-chat.png differ diff --git a/docs/res/usage/tasks/create-recurring-task.png b/docs/res/usage/tasks/create-recurring-task.png new file mode 100644 index 000000000..d695460b2 Binary files /dev/null and b/docs/res/usage/tasks/create-recurring-task.png differ diff --git a/docs/res/usage/tasks/open-scheduled-tasks.png b/docs/res/usage/tasks/open-scheduled-tasks.png new file mode 100644 index 000000000..57ea90bf4 Binary files /dev/null and b/docs/res/usage/tasks/open-scheduled-tasks.png differ diff --git a/docs/res/usage/tasks/saved-task-list.png b/docs/res/usage/tasks/saved-task-list.png new file mode 100644 index 000000000..bc3453013 Binary files /dev/null and b/docs/res/usage/tasks/saved-task-list.png differ diff --git a/docs/res/usage/tasks/sidebar-task-chats.png b/docs/res/usage/tasks/sidebar-task-chats.png new file mode 100644 index 000000000..429873cb6 Binary files /dev/null and b/docs/res/usage/tasks/sidebar-task-chats.png differ diff --git a/docs/res/usage/tasks/task-details.png b/docs/res/usage/tasks/task-details.png new file mode 100644 index 000000000..20e34636a Binary files /dev/null and b/docs/res/usage/tasks/task-details.png differ diff --git a/docs/res/usage/telegram/connect-bot.png b/docs/res/usage/telegram/connect-bot.png new file mode 100644 index 000000000..13102a707 Binary files /dev/null and b/docs/res/usage/telegram/connect-bot.png differ diff --git a/docs/res/usage/telegram/plugin-entry.png b/docs/res/usage/telegram/plugin-entry.png new file mode 100644 index 000000000..ffea28b69 Binary files /dev/null and b/docs/res/usage/telegram/plugin-entry.png differ diff --git a/docs/res/usage/telegram/private-access.png b/docs/res/usage/telegram/private-access.png new file mode 100644 index 000000000..639af02da Binary files /dev/null and b/docs/res/usage/telegram/private-access.png differ diff --git a/docs/res/usage/telegram/settings-scope.png b/docs/res/usage/telegram/settings-scope.png new file mode 100644 index 000000000..194885597 Binary files /dev/null and b/docs/res/usage/telegram/settings-scope.png differ diff --git a/extensions/python/job_loop/AGENTS.md b/extensions/python/job_loop/AGENTS.md index afa7597a3..84a963337 100644 --- a/extensions/python/job_loop/AGENTS.md +++ b/extensions/python/job_loop/AGENTS.md @@ -7,6 +7,7 @@ ## Ownership - Ordered Python files own cleanup of expired API chats, cache trimming, and future job-loop tasks. +- `_11_scoped_telegram.py` calls Telegram's plugin-owned manager only when global activation is disabled; this preserves scoped activation and stops revoked bot connections even when plugin extension discovery excludes the global hook. ## Local Contracts diff --git a/extensions/python/job_loop/_11_scoped_telegram.py b/extensions/python/job_loop/_11_scoped_telegram.py new file mode 100644 index 000000000..bedb72119 --- /dev/null +++ b/extensions/python/job_loop/_11_scoped_telegram.py @@ -0,0 +1,11 @@ +from helpers import plugins +from helpers.extension import Extension + + +class ScopedTelegramBots(Extension): + async def execute(self, **kwargs): + # Globally disabled plugins do not contribute their own job-loop hook. + if plugins.get_toggle_state("_telegram_integration") == "disabled": + from importlib import import_module + manager = import_module("plugins._telegram_integration.extensions.python.job_loop._10_telegram_bot") + await manager.TelegramBotManager(agent=None).execute() diff --git a/helpers/AGENTS.md b/helpers/AGENTS.md index b8d0dbf7d..b5de55eb5 100644 --- a/helpers/AGENTS.md +++ b/helpers/AGENTS.md @@ -12,6 +12,7 @@ ## Local Contracts +- UI bundle inventory uses directory-entry metadata to avoid repeated host-mount path checks while preserving symlink containment; `ui_bundler.py.dox.md` owns the details. - Preserve public helper APIs used by core code and plugins unless all callers, docs, and tests are updated. - Use structured parsers and serializers for YAML, JSON, paths, and URLs instead of ad hoc string handling. - Keep path handling constrained to intended roots for user files, uploads, downloads, projects, and workdirs. diff --git a/helpers/backup.py b/helpers/backup.py index 51b6abe38..bd443c78e 100644 --- a/helpers/backup.py +++ b/helpers/backup.py @@ -634,6 +634,12 @@ class BackupService: # Use user-edited metadata if provided, otherwise fall back to original backup_metadata = user_edited_metadata if user_edited_metadata else original_backup_metadata + archive_files = [name for name in zipf.namelist() + if name not in ["metadata.json", "checksums.json"]] + # Reject unsafe members before cleanup or extraction changes existing files. + for archive_path in archive_files: + self._translate_restore_path(archive_path, original_backup_metadata) + # Perform clean before restore if requested if clean_before_restore: # Use user-edited metadata for clean operations so patterns from ACE editor are used @@ -656,10 +662,6 @@ class BackupService: "error": f"Failed to delete: {str(e)}" }) - # Get files from archive (excluding metadata files) - archive_files = [name for name in zipf.namelist() - if name not in ["metadata.json", "checksums.json"]] - # Create pathspec for restore patterns if provided restore_spec = None if restore_include_patterns or restore_exclude_patterns: @@ -792,30 +794,36 @@ class BackupService: # If we don't have the backed up root path, use original path with leading slash if not backed_up_agent_root: - return "/" + archive_path.lstrip('/') - - # Ensure paths have consistent trailing slash handling - backed_up_agent_root = backed_up_agent_root.rstrip('/') - current_agent_root = current_agent_root.rstrip('/') - - # Convert archive path to absolute path (add leading slash if missing) - if not archive_path.startswith('/'): - absolute_archive_path = "/" + archive_path + translated_path = "/" + archive_path.lstrip('/') else: - absolute_archive_path = archive_path + # Ensure paths have consistent trailing slash handling + backed_up_agent_root = backed_up_agent_root.rstrip('/') + current_agent_root = current_agent_root.rstrip('/') - # Check if the archive path starts with the backed up agent zero root - if absolute_archive_path.startswith(backed_up_agent_root + '/') or absolute_archive_path == backed_up_agent_root: - # Replace the backed up root with the current root - relative_path = absolute_archive_path[len(backed_up_agent_root):].lstrip('/') - if relative_path: - translated_path = current_agent_root + '/' + relative_path + # Convert archive path to absolute path (add leading slash if missing) + if not archive_path.startswith('/'): + absolute_archive_path = "/" + archive_path else: - translated_path = current_agent_root - return translated_path - else: - # Path doesn't start with backed up agent root, return as-is - return absolute_archive_path + absolute_archive_path = archive_path + + # Check if the archive path starts with the backed up agent zero root + if absolute_archive_path.startswith(backed_up_agent_root + '/') or absolute_archive_path == backed_up_agent_root: + # Replace the backed up root with the current root + relative_path = absolute_archive_path[len(backed_up_agent_root):].lstrip('/') + if relative_path: + translated_path = current_agent_root + '/' + relative_path + else: + translated_path = current_agent_root + else: + # Path doesn't start with backed up agent root, return as-is + translated_path = absolute_archive_path + + translated_path = os.path.abspath(translated_path) + restore_root = os.path.realpath(self.agent_zero_root) + target_path = os.path.realpath(translated_path) + if os.path.commonpath([restore_root, target_path]) != restore_root: + raise ValueError(f"Backup entry escapes the restore root: {archive_path}") + return translated_path async def _find_files_to_clean_with_user_metadata(self, user_metadata: Dict[str, Any], original_metadata: Dict[str, Any]) -> List[Dict[str, Any]]: """Find existing files that match patterns from user-edited metadata for clean operations""" diff --git a/helpers/backup.py.dox.md b/helpers/backup.py.dox.md index a20f68410..4df7d1507 100644 --- a/helpers/backup.py.dox.md +++ b/helpers/backup.py.dox.md @@ -28,6 +28,7 @@ - `test_patterns(..., max_files=None)` is the unlimited scan mode. UI preview and dry-run callers may pass bounded limits, but real backup creation and restore clean-before-restore must use unlimited matching so archives and cleanup are not silently truncated. - Default backup metadata includes persistent `/usr` data but excludes Time Travel shadow history under `usr/.time_travel/**` and Orchestrator state and credentials under `usr/plugins/_orchestrator/data/**`. - Restoring `usr/.env` preserves the destination instance's allowed origins while restoring authentication and other portable configuration from the archive. +- Preview and restore normalize logical archive paths while preserving symlink names for pattern matching, overwrite policies, and `usr/.env` origin preservation. Resolved targets must stay inside the current Agent Zero root. Restore validates every member before cleanup or extraction and rechecks each target before use. ## Key Concepts @@ -44,6 +45,8 @@ - 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_backup_large_archives.py` +- Portable round-trip tests cover inspection, preview, and restore between different installation roots, including symlinked VPS roots, cleanup, skip/overwrite policies, saved OAuth/model configuration, and destination-origin preservation. - `tests/test_download_toast_regressions.py` - `tests/test_office_document_store.py` - `tests/test_self_update_tag_filter.py` diff --git a/helpers/dirty_json.py b/helpers/dirty_json.py index 8e7b21012..691a17575 100644 --- a/helpers/dirty_json.py +++ b/helpers/dirty_json.py @@ -1,4 +1,9 @@ import json +import re + +# A strict JSON escape of a UTF-16 low surrogate (DC00-DFFF): four ASCII hex digits. +_LOW_SURROGATE_ESCAPE = re.compile(r"\\u([dD][c-fC-F][0-9a-fA-F]{2})") + def try_parse(json_string: str): try: @@ -293,7 +298,7 @@ class DirtyJson: unicode_char += self.current_char self._advance() try: - result += chr(int(unicode_char, 16)) + result += self._decode_unicode_escape(int(unicode_char, 16)) except ValueError: # If invalid hex value, treat as literal result += "\\u" + unicode_char @@ -305,6 +310,21 @@ class DirtyJson: self._advance() # Skip closing quote return result + def _decode_unicode_escape(self, code_unit: int) -> str: + """Decode an escaped UTF-16 code unit, joining a surrogate pair like json.loads. + + A lone surrogate cannot be encoded as UTF-8, so it becomes U+FFFD. + """ + if 0xD800 <= code_unit <= 0xDBFF: + low_escape = _LOW_SURROGATE_ESCAPE.match(self.json_string, self.index) + if low_escape: + self._advance(len(low_escape.group())) + low_unit = int(low_escape.group(1), 16) + return chr(0x10000 + ((code_unit - 0xD800) << 10) + (low_unit - 0xDC00)) + if 0xD800 <= code_unit <= 0xDFFF: + return "\ufffd" + return chr(code_unit) + def _is_closing_quote(self, is_key: bool) -> bool: next_index = self._skip_padding_from(self.index + 1) if next_index >= len(self.json_string): diff --git a/helpers/dirty_json.py.dox.md b/helpers/dirty_json.py.dox.md index 030a5c652..c393ee959 100644 --- a/helpers/dirty_json.py.dox.md +++ b/helpers/dirty_json.py.dox.md @@ -25,8 +25,9 @@ - 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. +- `\uXXXX` string escapes decode like `json.loads`, including UTF-16 surrogate pairs (`\ud83c\udf78` becomes U+1F378). A lone surrogate escape becomes U+FFFD, where `json.loads` would keep it, because tools and logs encode parsed strings as UTF-8. - Observed side-effect areas: filesystem writes, settings/state persistence. -- Imported dependency areas include: `json`. +- Imported dependency areas include: `json`, `re`. ## Key Concepts diff --git a/helpers/dotenv.py b/helpers/dotenv.py index ebb027b7a..97f2e6268 100644 --- a/helpers/dotenv.py +++ b/helpers/dotenv.py @@ -40,5 +40,8 @@ def save_dotenv_value(key: str, value: str, reload_env: bool = True): f.seek(0) f.writelines(lines) f.truncate() + # Import here because the secrets manager also reads dotenv configuration. + from helpers.secrets import SecretsManager + SecretsManager._invalidate_all_caches() if reload_env: load_dotenv() diff --git a/helpers/dotenv.py.dox.md b/helpers/dotenv.py.dox.md index 375f5d95d..3287cd91c 100644 --- a/helpers/dotenv.py.dox.md +++ b/helpers/dotenv.py.dox.md @@ -24,6 +24,7 @@ - Observed side-effect areas: filesystem reads, filesystem writes, secret handling. - Imported dependency areas include: `dotenv`, `files`, `os`, `re`, `typing`. - `save_dotenv_value(..., reload_env=False)` updates the persisted file without changing the running process environment. +- Every successful file write invalidates registered `SecretsManager` caches before optional environment reloading, so all credential writers keep alias substitution and masking current. The secrets import is deferred to avoid the dotenv/secrets import cycle. ## Key Concepts diff --git a/helpers/integration_commands.py b/helpers/integration_commands.py index 34eb9fbfa..00dad9a38 100644 --- a/helpers/integration_commands.py +++ b/helpers/integration_commands.py @@ -370,6 +370,7 @@ def _handle_project(context: "AgentContext", args: str) -> str: if _normalize_lookup(desired) in _CLEAR_VALUES: if not current_name: return "No project is active." + _authorize_scope(context, "", context.config.profile) projects.deactivate_project(context.id) return "Cleared the active project." @@ -384,6 +385,7 @@ def _handle_project(context: "AgentContext", args: str) -> str: if match.get("name") == current_name: return f"Already using project {match.get('title') or match.get('name')}." + _authorize_scope(context, match["name"], context.config.profile) projects.activate_project(context.id, match["name"]) return f"Switched project to {match.get('title') or match['name']}." @@ -466,6 +468,7 @@ def _handle_agent(context: "AgentContext", args: str) -> str: if profile == current: return f"Already using agent {match.get('label') or profile}." + _authorize_scope(context, projects.get_context_project_name(context) or "", profile) config = initialize_agent(override_settings={"agent_profile": profile}) context.config = config context.agent0.config = config @@ -474,6 +477,12 @@ def _handle_agent(context: "AgentContext", args: str) -> str: return f"Switched agent to {match.get('label') or profile}." +def _authorize_scope(context, project: str, profile: str) -> None: + if getattr(context, "data", {}).get("telegram_bot"): + from plugins._telegram_integration.helpers.scopes import require_scope + require_scope(context, project, profile) + + def _format_project_entry(item: dict) -> str: title = str(item.get("title", "") or "").strip() name = str(item.get("name", "") or "").strip() diff --git a/helpers/integration_commands.py.dox.md b/helpers/integration_commands.py.dox.md index 86795ec28..0d275a4df 100644 --- a/helpers/integration_commands.py.dox.md +++ b/helpers/integration_commands.py.dox.md @@ -25,6 +25,8 @@ catalog, though status may report an existing chat using the utility profile. - `/model ` stores a per-chat global preset reference, `/model inherit` clears it, and status always reports the effective scoped-or-chat preset. `Default` is a real selectable preset, not an alias for clearing the chat selection. +- Project and profile changes on Telegram-bound contexts call the Telegram scope owner before mutation, including calls from shared command scripts. Other integrations retain their existing behavior. + ## Key Concepts - Important called helpers/classes include `mq.get_queue`, `mq.send_all_aggregated`, `mark_dirty_for_context`, `projects.activate_project`, `initialize_agent`, `model_config.get_effective_preset_name`, `model_config.get_presets`, `context.get_data`, `context.set_data`, and `save_tmp_chat`. diff --git a/helpers/job_loop.py b/helpers/job_loop.py index 76ea22f21..2ffffb4ee 100644 --- a/helpers/job_loop.py +++ b/helpers/job_loop.py @@ -22,7 +22,7 @@ async def run_loop(): await scheduler_tick() except Exception as e: PrintStyle().error(errors.format_error(e)) - await asyncio.sleep(SLEEP_TIME) # TODO! - if we lower it under 1min, it can run a 5min job multiple times in it's target minute + await asyncio.sleep(SLEEP_TIME) async def scheduler_tick(): diff --git a/helpers/job_loop.py.dox.md b/helpers/job_loop.py.dox.md index c191fa332..82da4dfef 100644 --- a/helpers/job_loop.py.dox.md +++ b/helpers/job_loop.py.dox.md @@ -19,7 +19,8 @@ ## 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. +- Development uses the local scheduler and job-loop extensions without pausing itself or contacting a sibling. Explicit `pause_loop`/`resume_loop`, stale-pause recovery and tick error handling remain intact. +- When active, the loop ticks immediately and then sleeps for 60 seconds between ticks. The scheduler owns overdue-run detection and duplicate prevention. - 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. diff --git a/helpers/secrets.py b/helpers/secrets.py index 593b9d9bf..a24801a7a 100644 --- a/helpers/secrets.py +++ b/helpers/secrets.py @@ -1,10 +1,8 @@ import re import threading -import time -import os from io import StringIO from dataclasses import dataclass -from typing import Dict, Optional, List, Literal, Set, Callable, Tuple, TYPE_CHECKING +from typing import Dict, Iterator, Optional, List, Literal, Set, Callable, Tuple, TYPE_CHECKING from dotenv.parser import parse_stream from helpers.errors import RepairableException from helpers import dotenv, files @@ -31,6 +29,24 @@ def alias_for_key(key: str, placeholder: str = "§§secret({key})") -> str: return placeholder.format(key=key) +def _is_api_key(key: str) -> bool: + key = key.upper() + return key.startswith("API_KEY_") or key.endswith(("_API_KEY", "_API_TOKEN")) + + +def _masking_values(key_to_value: Dict[str, str]) -> Iterator[Tuple[str, str]]: + for key, value in key_to_value.items(): + if not isinstance(value, str) or not value: + continue + yield key, value + # Providers select individual keys from these lists; substitution keeps the full value. + if _is_api_key(key) and "," in value: + for member in value.split(","): + member = member.strip() + if member: + yield key, member + + @dataclass class EnvLine: raw: str @@ -38,7 +54,7 @@ class EnvLine: key: Optional[str] = None value: Optional[str] = None inline_comment: Optional[str] = ( - None # preserves trailing inline comment including leading spaces and '#' + None # preserves trailing inline comment starting with '#' ) @@ -47,22 +63,22 @@ class StreamingSecretsFilter: - Replaces full secret values with placeholders §§secret(KEY) when detected. - Holds the longest suffix of the current buffer that matches any secret prefix - (with minimum trigger length of 3) to avoid leaking partial secrets across chunks. - - On finalize(), any unresolved partial is masked with '***'. + to avoid leaking partial secrets across chunks. + - On finalize(), unresolved partials of at least min_trigger are masked with '***'. """ def __init__(self, key_to_value: Dict[str, str], min_trigger: int = 3): self.min_trigger = max(1, int(min_trigger)) # Map value -> key for placeholder construction self.value_to_key: Dict[str, str] = { - v: k for k, v in key_to_value.items() if isinstance(v, str) and v + v: k for k, v in _masking_values(key_to_value) } # Only keep non-empty values self.secret_values: List[str] = [v for v in self.value_to_key.keys() if v] # Precompute all prefixes for quick suffix matching self.prefixes: Set[str] = set() for v in self.secret_values: - for i in range(self.min_trigger, len(v) + 1): + for i in range(1, len(v) + 1): self.prefixes.add(v[:i]) self.max_len: int = max((len(v) for v in self.secret_values), default=0) @@ -82,9 +98,9 @@ class StreamingSecretsFilter: def _longest_suffix_prefix(self, text: str) -> int: """Return length of longest suffix of text that is a known secret prefix. - Returns 0 if none found (or only shorter than min_trigger).""" + Returns 0 if none found.""" max_check = min(len(text), self.max_len) - for length in range(max_check, self.min_trigger - 1, -1): + for length in range(max_check, 0, -1): suffix = text[-length:] if suffix in self.prefixes: return length @@ -119,7 +135,7 @@ class StreamingSecretsFilter: return "" hold_len = self._longest_suffix_prefix(self.pending) - if hold_len > 0: + if hold_len >= self.min_trigger: safe = self.pending[:-hold_len] # Mask unresolved partial result = safe + "***" @@ -135,7 +151,6 @@ class SecretsManager: _instances: Dict[Tuple[str, ...], "SecretsManager"] = {} _secrets_cache: Optional[Dict[str, str]] = None - _last_raw_text: Optional[str] = None @classmethod def get_instance(cls, *secrets_files: str) -> "SecretsManager": @@ -150,35 +165,30 @@ class SecretsManager: self._lock = threading.RLock() # instance-level list of secrets files self._files: Tuple[str, ...] = tuple(files) if files else (DEFAULT_SECRETS_FILE,) - self._raw_snapshots: Dict[str, str] = {} self._secrets_cache = None - self._last_raw_text = None def read_secrets_raw(self) -> str: """Read raw secrets file content from local filesystem (same system).""" parts: List[str] = [] - self._raw_snapshots = {} - for path in self._files: try: content = files.read_file(path) - except Exception: + except FileNotFoundError: content = "" + except Exception as e: + raise RepairableException(f"Failed to read secrets file: {path}") from e - self._raw_snapshots[path] = content if path == dotenv.get_dotenv_file_path(): content = "\n".join( line.raw for line in self.parse_env_lines(content) if line.type != "pair" - or (line.key or "").upper().startswith("API_KEY_") + or _is_api_key(line.key or "") or (line.key or "").upper() in _RUNTIME_CREDENTIAL_KEYS ) parts.append(content) - combined = "\n".join(parts) - self._last_raw_text = combined - return combined + return "\n".join(parts) def _write_secrets_raw(self, content: str): """Write raw secrets file content to local filesystem.""" @@ -199,10 +209,6 @@ class SecretsManager: self.parse_env_content(combined_raw) if combined_raw else {} ) - # Only track the first file's raw text for single-file setups - if len(self._files) != 1: - self._last_raw_text = None - self._secrets_cache = merged_secrets return merged_secrets @@ -227,22 +233,15 @@ class SecretsManager: "Merging secrets is disabled when multiple files are configured" ) with self._lock: - # Prefer in-memory snapshot to avoid disk reads during save - primary_path = self._files[0] - if self._last_raw_text is not None: - existing_text = self._last_raw_text - else: - try: - existing_text = files.read_file(primary_path) - self._raw_snapshots[primary_path] = existing_text - except Exception as e: - # If read fails and submitted contains masked values, abort to avoid losing values/comments - if self.MASK_VALUE in submitted_content: - raise RepairableException( - "Saving secrets failed because existing secrets could not be read to preserve masked values and comments. Please retry." - ) from e - # No masked values, safe to treat as new file - existing_text = "" + # Resolve masks against current values, including rotations since the editor opened. + try: + existing_text = files.read_file(self._files[0]) + except FileNotFoundError: + existing_text = "" + except Exception as e: + raise RepairableException( + "Saving secrets failed because existing secrets could not be read. Please retry." + ) from e merged_lines = self._merge_env(existing_text, submitted_content) merged_text = self._serialize_env_lines(merged_lines) self._write_secrets_raw(merged_text) @@ -254,18 +253,32 @@ class SecretsManager: return list(secrets.keys()) def get_secrets_for_prompt(self) -> str: - """Get formatted string of secret keys for system prompt""" + """Get non-empty secret aliases from their effective last definitions.""" content = self.read_secrets_raw() if not content: return "" - env_lines = self.parse_env_lines(content) + seen: Set[str] = set() + env_lines: List[EnvLine] = [] + for line in reversed(self.parse_env_lines(content)): + if line.type == "pair" and line.key is not None: + key = line.key.upper() + if key in seen: + continue + seen.add(key) + if not line.value: + continue + env_lines.append(line) + + if not any(line.type == "pair" for line in env_lines): + return "" + env_lines.reverse() return self._serialize_env_lines( env_lines, with_values=False, with_comments=True, with_blank=True, - with_other=True, + with_other=False, key_formatter=alias_for_key, ) @@ -322,7 +335,7 @@ class SecretsManager: # Sort by length (longest first) to avoid partial replacements for key, value in sorted( - secrets.items(), key=lambda x: len(x[1]), reverse=True + _masking_values(secrets), key=lambda x: len(x[1]), reverse=True ): if value and len(value.strip()) >= min_length: result = result.replace(value, alias_for_key(key, placeholder)) @@ -335,15 +348,13 @@ class SecretsManager: if not content: return "" - # Parse content for known keys using python-dotenv - secrets_map = self.parse_env_content(content) env_lines = self.parse_env_lines(content) - # Replace values with mask for keys present + # Mask each populated line, including values shadowed by later empty entries. for ln in env_lines: if ln.type == "pair" and ln.key is not None: ln.key = ln.key.upper() - if ln.key in secrets_map and secrets_map[ln.key] != "": + if ln.value: ln.value = self.MASK_VALUE return self._serialize_env_lines(env_lines) @@ -364,8 +375,6 @@ class SecretsManager: """Clear the secrets cache""" with self._lock: self._secrets_cache = None - self._raw_snapshots = {} - self._last_raw_text = None @classmethod def _invalidate_all_caches(cls): @@ -375,45 +384,22 @@ class SecretsManager: # ---------------- Internal helpers for parsing/merging ---------------- def parse_env_lines(self, content: str) -> List[EnvLine]: - """Parse env file into EnvLine objects using python-dotenv, preserving comments and order. - We reconstruct key_part and inline_comment based on the original string. - """ + """Parse env file using python-dotenv, preserving comments and order.""" lines: List[EnvLine] = [] for binding in parse_stream(StringIO(content)): orig = getattr(binding, "original", None) raw = getattr(orig, "string", "") if orig is not None else "" if binding.key and not binding.error: - # Determine key_part and inline_comment from original line line_text = raw.rstrip("\n") - # Fallback to composed key_part if original not available - if "=" in line_text: - left, right = line_text.split("=", 1) - else: - right = "" - # Try to extract inline comment by scanning right side to comment start, respecting quotes - in_single = False - in_double = False - esc = False - comment_index = None - for i, ch in enumerate(right): - if esc: - esc = False - continue - if ch == "\\": - esc = True - continue - if ch == "'" and not in_double: - in_single = not in_single - continue - if ch == '"' and not in_single: - in_double = not in_double - continue - if ch == "#" and not in_single and not in_double: - comment_index = i - break inline_comment = None - if comment_index is not None: - inline_comment = right[comment_index:] + # A comment can be removed without changing the parsed key or value. + for match in re.finditer("#", line_text): + prefix = next(parse_stream(StringIO(line_text[:match.start()])), None) + if prefix and not prefix.error and ( + prefix.key, prefix.value + ) == (binding.key, binding.value): + inline_comment = line_text[match.start():] + break lines.append( EnvLine( raw=line_text, diff --git a/helpers/secrets.py.dox.md b/helpers/secrets.py.dox.md index 20c6815bf..5fcd2788a 100644 --- a/helpers/secrets.py.dox.md +++ b/helpers/secrets.py.dox.md @@ -34,12 +34,19 @@ ## Runtime Contracts - Helper modules own reusable framework APIs and must preserve public callers unless all callers, tests, and docs are updated together. -- The agent-facing `get_secrets_manager` masks and unpacks `API_KEY_*` and login/password credentials from `usr/.env`, every value from the global `usr/secrets.env`, and every value from the active project's `secrets.env`; ordinary runtime settings are not treated as secrets. `get_default_secrets_manager` remains scoped to the single writable `usr/secrets.env` file. +- The agent-facing `get_secrets_manager` masks and unpacks provider credentials (`API_KEY_*`, `*_API_KEY`, `*_API_TOKEN`) and login/password credentials from `usr/.env`, every value from the global `usr/secrets.env`, and every value from the active project's `secrets.env`; ordinary runtime settings are not treated as secrets. `get_default_secrets_manager` remains scoped to the single writable `usr/secrets.env` file. +- `get_secrets_for_prompt` lists only non-empty effective values, once per uppercase key at its last definition, preserving comments and order. Empty overrides still clear earlier values without changing loading, masking, editing, or substitution. Non-empty literals, including quoted whitespace, remain available. An empty inventory returns `""`, so the prompt template omits the secrets section. +- Inline comments must leave the parsed dotenv key and value unchanged when removed; hashes and quotes inside values must not expose value fragments as comments. Malformed lines remain editable but are excluded from the prompt. +- Missing files are empty stores. Other read failures raise `RepairableException` and must not be cached as empty data or presented as an empty editor. Merge-saves read current disk content, preserve current values behind masks, and abort on read errors even for empty or unmasked submissions. +- The masked editor masks each populated line, including values shadowed by later empty entries. Effective last-definition precedence remains unchanged. +- Streaming holds potential secret prefixes from the first character across chunks. `min_trigger` controls only final masking of incomplete prefixes; shorter unfinished tails remain ordinary text. +- Text and streaming masks protect both full provider key lists and each non-empty, trimmed member, matching provider selection. Loading and placeholder substitution retain the original full value. Commas in other secrets do not create separate masking values; text masking retains its minimum-length threshold. +- Successful `helpers.dotenv.save_dotenv_value` writes invalidate registered managers, including when environment reloading is disabled. - Secret serialization escapes backslashes, double quotes, and carriage returns in double-quoted values so global and project saves preserve their parsed values across disk reads and masked edits. Literal line feeds remain multiline; empty values, comments, and deletion semantics are unchanged. - Masked secret merging matches keys using the same uppercase convention as parsing and masking, preserving values from lowercase or mixed-case entries. Explicit empty values still clear a secret, and omitted keys are deleted. - 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, WebSocket state, settings/state persistence, secret handling. -- Imported dependency areas include: `dataclasses`, `dotenv.parser`, `helpers`, `helpers.errors`, `helpers.extension`, `io`, `os`, `re`, `threading`, `time`, `typing`. +- Imported dependency areas include: `dataclasses`, `dotenv.parser`, `helpers`, `helpers.errors`, `helpers.extension`, `io`, `re`, `threading`, `typing`. ## Key Concepts @@ -55,6 +62,7 @@ ## Verification - Run targeted tests for changed helper behavior; run security regressions for auth, filesystem, WebSocket, tunnel, upload, or secret-handling helpers. +- `tests/test_secrets.py` covers empty aliases, overrides, prompt rendering, dotenv comments, malformed lines, failed reads and recovery, current-value merges, duplicate masking, provider key pools, chunk boundaries, and dotenv cache invalidation. `tests/test_settings_api_keys.py` checks unrelated settings access during read failures, safe saves across recovery, and editor error handling. - Related tests observed by source search: - `tests/test_secrets.py` - `tests/test_plugin_scan_prompt.py` diff --git a/helpers/settings.py b/helpers/settings.py index def64b5cc..ba8ca45e4 100644 --- a/helpers/settings.py +++ b/helpers/settings.py @@ -16,6 +16,7 @@ from . import files, dotenv from helpers.print_style import PrintStyle from helpers.providers import get_providers, FieldOption as ProvidersFO from helpers.secrets import get_default_secrets_manager +from helpers.errors import RepairableException from helpers import dirty_json from helpers.notification import NotificationManager, NotificationType, NotificationPriority @@ -71,6 +72,11 @@ class Settings(TypedDict): workdir_max_folders: int workdir_max_lines: int workdir_gitignore: str + remote_tree_inherit: bool + remote_tree_max_depth: int + remote_tree_max_files: int + remote_tree_max_folders: int + remote_tree_max_lines: int file_browser_remember_last_directory: bool file_browser_max_text_size_mb: int file_browser_max_transfer_size_mb: int @@ -100,7 +106,7 @@ class Settings(TypedDict): a2a_server_enabled: bool variables: str - secrets: str + secrets: str | None # LiteLLM global kwargs applied to all model calls litellm_global_kwargs: dict[str, Any] @@ -341,10 +347,7 @@ def convert_out(settings: Settings) -> SettingsOutput: #secrets secrets_manager = get_default_secrets_manager() - try: - out["settings"]["secrets"] = secrets_manager.get_masked_secrets() - except Exception: - out["settings"]["secrets"] = "" + out["settings"]["secrets"] = secrets_manager.get_masked_secrets() # mask API keys before sending to frontend if isinstance(out["settings"].get("api_keys"), dict): @@ -475,6 +478,10 @@ def normalize_settings(settings: Settings) -> Settings: for key, value in default.items(): if key not in copy: copy[key] = value + elif key == "secrets" and copy[key] is None: + continue # Unavailable secrets must not become an empty or literal "None" submission. + elif key.startswith("remote_tree_max_"): + continue else: try: copy[key] = type(value)(copy[key]) # type: ignore @@ -487,6 +494,15 @@ def normalize_settings(settings: Settings) -> Settings: copy["file_browser_max_transfer_size_mb"] = max(1, copy["file_browser_max_transfer_size_mb"]) copy["file_browser_max_extract_size_mb"] = max(1, copy["file_browser_max_extract_size_mb"]) copy["file_browser_max_archive_entries"] = max(1, copy["file_browser_max_archive_entries"]) + copy["remote_tree_inherit"] = settings.get("remote_tree_inherit", default["remote_tree_inherit"]) is not False + for suffix in ("max_depth", "max_files", "max_folders", "max_lines"): + key = f"remote_tree_{suffix}" + raw = settings.get(key, default[key]) + try: + value = int(raw) if type(raw) in (int, str) else -1 + except ValueError: + value = -1 + copy[key] = value if value >= 0 else default[key] if copy["agent_profile"] == "default": copy["agent_profile"] = "agent0" @@ -530,8 +546,8 @@ def _load_sensitive_settings(settings: Settings): secrets_manager = get_default_secrets_manager() try: settings["secrets"] = secrets_manager.read_secrets_raw() - except Exception: - settings["secrets"] = "" + except RepairableException: + settings["secrets"] = None def _read_settings_file() -> Settings | None: @@ -577,9 +593,9 @@ def _write_sensitive_settings(settings: Settings): set_root_password(settings["root_password"]) # Handle secrets separately - merge with existing preserving comments/order and support deletions - secrets_manager = get_default_secrets_manager() submitted_content = settings["secrets"] - secrets_manager.save_secrets_with_merge(submitted_content) + if submitted_content is not None: + get_default_secrets_manager().save_secrets_with_merge(submitted_content) @@ -608,6 +624,11 @@ def get_default_settings() -> Settings: workdir_max_folders=get_default_value("workdir_max_folders", 20), workdir_max_lines=get_default_value("workdir_max_lines", 250), workdir_gitignore=get_default_value("workdir_gitignore", gitignore), + remote_tree_inherit=get_default_value("remote_tree_inherit", True), + remote_tree_max_depth=get_default_value("remote_tree_max_depth", get_default_value("workdir_max_depth", 5)), + remote_tree_max_files=get_default_value("remote_tree_max_files", get_default_value("workdir_max_files", 20)), + remote_tree_max_folders=get_default_value("remote_tree_max_folders", get_default_value("workdir_max_folders", 20)), + remote_tree_max_lines=get_default_value("remote_tree_max_lines", get_default_value("workdir_max_lines", 250)), file_browser_remember_last_directory=get_default_value( "file_browser_remember_last_directory", True, diff --git a/helpers/settings.py.dox.md b/helpers/settings.py.dox.md index ff96be8a1..a5738786f 100644 --- a/helpers/settings.py.dox.md +++ b/helpers/settings.py.dox.md @@ -58,7 +58,9 @@ - `set_root_password` remains a compatibility export of `helpers.runtime.set_root_password`; sensitive-settings writes retain the same Docker guard, checked command and dotenv persistence. +- `remote_tree_inherit` defaults to true, so connected host trees use the default workdir's limits. When false, the connector uses the independently saved `remote_tree_max_depth/files/folders/lines` settings. Zero means unlimited. Invalid overrides fall back to their defaults. - Settings reads use `models.get_api_key_raw()` to preserve complete key lists without advancing runtime rotation or persisting keys synthesized by runtime hooks. Masking, authentication reloads, and intentional clearing retain their existing behavior. +- Ordinary settings reads represent an unreadable secrets file as `None`, preserving unrelated settings access. Normalization retains this transient value, and saves skip secret writes for it even if the file becomes readable in the meantime. Frontend conversion and explicit secret edits still raise on read failures; they must never present a false empty editor or overwrite unreadable data. A missing file remains a valid empty store, and an explicit empty string still clears a readable store. - `ui_control_visibility` accepts dynamic `canvas:` entries as well as built-in controls, normalizes device values to booleans (default shown), and preserves choices for temporarily unavailable plugins. - `file_browser_max_text_size_mb` persists the instance-wide text-editing limit, default 10 MiB and normalized to 1–100. FileBrowser reads it directly so its scoped settings API can update it without restarting or reinitializing agents. diff --git a/helpers/task_scheduler.py b/helpers/task_scheduler.py index 06f7f10c3..8208d8aa0 100644 --- a/helpers/task_scheduler.py +++ b/helpers/task_scheduler.py @@ -159,6 +159,30 @@ class TaskPlan(BaseModel): return None +async def _execute_plugin_task(task) -> str: + from helpers import plugins + + if plugins.get_toggle_state(task.plugin_name) != "enabled": + raise RuntimeError(f"Task plugin '{task.plugin_name}' is disabled or unavailable") + cancel_event = threading.Event() + worker = asyncio.create_task(asyncio.to_thread( + plugins.call_plugin_hook, task.plugin_name, "run_scheduled_task", + task=task, cancel_event=cancel_event, + )) + try: + result = await asyncio.shield(worker) + except asyncio.CancelledError: + cancel_event.set() + try: + await asyncio.shield(worker) + except Exception: + pass # Cooperative hooks may signal their stop by raising. + raise + if not isinstance(result, str): + raise RuntimeError(f"Task plugin '{task.plugin_name}' did not return a result") + return result + + class BaseTask(BaseModel): uuid: str = Field(default_factory=lambda: guids.generate_id()) context_id: Optional[str] = Field(default=None) @@ -166,6 +190,7 @@ class BaseTask(BaseModel): name: str = Field() system_prompt: str prompt: str + plugin_name: str | None = None attachments: list[str] = Field(default_factory=list) project_name: str | None = Field(default=None) project_color: str | None = Field(default=None) @@ -191,6 +216,9 @@ class BaseTask(BaseModel): context_id: str | None = None, **kwargs): with self._lock: + if self.plugin_name and any(value is not None and value != getattr(self, key) + for key, value in (("prompt", prompt), ("system_prompt", system_prompt), ("attachments", attachments))): + raise ValueError("Plugin tasks are configured by their owning plugin.") if name is not None: self.name = name self.updated_at = _now() @@ -330,6 +358,16 @@ class AdHocTask(BaseTask): class ScheduledTask(BaseTask): type: Literal[TaskType.SCHEDULED] = TaskType.SCHEDULED schedule: TaskSchedule + schedule_anchor: datetime | None = None + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if self.schedule_anchor is None: + self.schedule_anchor = max( + _localize_task_datetime(stamp) + for stamp in (self.created_at, self.updated_at, self.last_run) + if stamp is not None + ) @classmethod def create( @@ -370,51 +408,40 @@ class ScheduledTask(BaseTask): context_id: str | None = None, schedule: TaskSchedule | None = None, **kwargs): - super().update(name=name, - state=state, - system_prompt=system_prompt, - prompt=prompt, - attachments=attachments, - last_run=last_run, - last_result=last_result, - context_id=context_id, - schedule=schedule, - **kwargs) + with self._lock: + reset_schedule = ((schedule is not None and schedule != self.schedule) + or (state is not None and state != self.state)) + super().update(name=name, + state=state, + system_prompt=system_prompt, + prompt=prompt, + attachments=attachments, + last_run=last_run, + last_result=last_result, + context_id=context_id, + schedule=schedule, + **kwargs) + if reset_schedule: + # Claiming a run consumes missed slots; re-enabling starts a fresh schedule. + self.schedule_anchor = _now() def check_schedule(self, frequency_seconds: float = 60.0) -> bool: - with self._lock: - crontab = CronTab(crontab=self.schedule.to_crontab()) # type: ignore - - # Get the timezone from the schedule or use UTC as fallback - self.schedule.timezone = normalize_schedule_timezone(self.schedule.timezone) - task_timezone = pytz.timezone(self.schedule.timezone) - - # Get reference time in task's timezone (by default now - frequency_seconds) - reference_time = (_now() - timedelta(seconds=frequency_seconds)).astimezone(task_timezone) - - # Get next run time as seconds until next execution - next_run_seconds: Optional[float] = crontab.next( # type: ignore - now=reference_time, - return_datetime=False - ) # type: ignore - - if next_run_seconds is None: - return False - - return next_run_seconds < frequency_seconds + next_run = self.get_next_run() + return next_run is not None and next_run <= _now() def get_next_run(self) -> datetime | None: with self._lock: crontab = CronTab(crontab=self.schedule.to_crontab()) # type: ignore self.schedule.timezone = normalize_schedule_timezone(self.schedule.timezone) task_timezone = pytz.timezone(self.schedule.timezone) - now_in_task_timezone = datetime.now(timezone.utc).astimezone(task_timezone) - next_run = crontab.next(now=now_in_task_timezone, return_datetime=True) # type: ignore - if next_run is None: + reference = max(_localize_task_datetime(stamp) + for stamp in (self.schedule_anchor, self.last_run) if stamp is not None) + reference = reference.astimezone(task_timezone) + # CronTab's datetime result retains the old UTC offset across DST changes. + delay = crontab.next(now=reference, return_datetime=False) + if delay is None: return None - if next_run.tzinfo is None: - next_run = task_timezone.localize(next_run) - return next_run.astimezone(timezone.utc) + return reference.astimezone(timezone.utc) + timedelta(seconds=delay) class PlannedTask(BaseTask): @@ -649,7 +676,7 @@ class SchedulerTaskList(BaseModel): await self.reload() return [ task for task in self.tasks - if task.check_schedule() and task.state == TaskState.IDLE + if task.state == TaskState.IDLE and task.check_schedule() ] def get_task_by_uuid(self, task_uuid: str) -> Union[ScheduledTask, AdHocTask, PlannedTask] | None: @@ -700,9 +727,12 @@ class TaskScheduler: self._running_tasks_lock = threading.RLock() self._initialized = True - def _register_running_task(self, task_uuid: str, deferred_task: DeferredTask) -> None: + def _register_running_task(self, task_uuid: str, deferred_task: DeferredTask) -> bool: with self._running_tasks_lock: + if task_uuid in self._running_deferred_tasks: + return False self._running_deferred_tasks[task_uuid] = deferred_task + return True def _unregister_running_task(self, task_uuid: str) -> None: with self._running_tasks_lock: @@ -739,7 +769,8 @@ class TaskScheduler: async def add_task(self, task: Union[ScheduledTask, AdHocTask, PlannedTask]) -> "TaskScheduler": await self._tasks.add_task(task) - ctx = await self._get_chat_context(task) # invoke context creation + if not task.plugin_name: + await self._get_chat_context(task) from helpers.state_monitor_integration import mark_dirty_all mark_dirty_all(reason="task_scheduler.TaskScheduler.add_task") return self @@ -767,7 +798,7 @@ class TaskScheduler: async def tick(self): for task in await self._tasks.get_due_tasks(): - await self._run_task(task) + await self._run_task(task, scheduled=True) async def run_task_by_uuid(self, task_uuid: str, task_context: str | None = None): # First reload tasks to ensure we have the latest state @@ -875,7 +906,7 @@ class TaskScheduler: raise ValueError(f"Context ID mismatch for task {task.name}: context {context.id} != task {task.context_id}") save_tmp_chat(context) - async def _run_task(self, task: Union[ScheduledTask, AdHocTask, PlannedTask], task_context: str | None = None): + async def _run_task(self, task: Union[ScheduledTask, AdHocTask, PlannedTask], task_context: str | None = None, *, scheduled: bool = False): async def _run_task_wrapper(task_uuid: str, task_context: str | None = None): @@ -891,7 +922,12 @@ class TaskScheduler: return # Atomically fetch and check the task's current state - current_task = await self.update_task_checked(task_uuid, lambda task: task.state != TaskState.RUNNING, state=TaskState.RUNNING) + current_task = await self.update_task_checked( + task_uuid, + lambda task: (task.state == TaskState.IDLE and task.check_schedule()) if scheduled + else task.state in (TaskState.IDLE, TaskState.ERROR), + state=TaskState.RUNNING, + ) if not current_task: PrintStyle.error(f"Scheduler Task with UUID '{task_uuid}' not found or updated by another process") self._unregister_running_task(task_uuid) @@ -910,6 +946,11 @@ class TaskScheduler: try: PrintStyle.info(f"Scheduler Task '{current_task.name}' started") + if current_task.plugin_name: + result = await _execute_plugin_task(current_task) + await current_task.on_success(result) + return + context = await self._get_chat_context(current_task) context.set_data("scheduler_task_uuid", current_task.uuid) AgentContext.use(context.id) @@ -1025,7 +1066,8 @@ class TaskScheduler: self._unregister_running_task(task_uuid) deferred_task = DeferredTask(thread_name=self.__class__.__name__) - self._register_running_task(task.uuid, deferred_task) + if not self._register_running_task(task.uuid, deferred_task): + return deferred_task.start_task(_run_task_wrapper, task.uuid, task_context) # Ensure background execution doesn't exit immediately on async await, especially in script contexts. @@ -1196,6 +1238,7 @@ def serialize_task(task: Union[ScheduledTask, AdHocTask, PlannedTask]) -> Dict[s "state": task.state, "system_prompt": task.system_prompt, "prompt": task.prompt, + "plugin_name": task.plugin_name, "attachments": task.attachments, "project_name": task.project_name, "project_color": task.project_color, @@ -1216,6 +1259,7 @@ def serialize_task(task: Union[ScheduledTask, AdHocTask, PlannedTask]) -> Dict[s if isinstance(task, ScheduledTask): task_dict['type'] = 'scheduled' task_dict['schedule'] = serialize_task_schedule(task.schedule) # type: ignore + task_dict['schedule_anchor'] = serialize_datetime(task.schedule_anchor) elif isinstance(task, AdHocTask): task_dict['type'] = 'adhoc' adhoc_task = cast(AdHocTask, task) @@ -1268,6 +1312,7 @@ def deserialize_task(task_data: Dict[str, Any], task_class: Optional[Type[T]] = "state": TaskState(task_data.get("state", TaskState.IDLE)), "system_prompt": task_data.get("system_prompt", ""), "prompt": task_data.get("prompt", ""), + "plugin_name": task_data.get("plugin_name"), "attachments": task_data.get("attachments", []), "project_name": task_data.get("project_name"), "project_color": task_data.get("project_color"), @@ -1282,6 +1327,7 @@ def deserialize_task(task_data: Dict[str, Any], task_class: Optional[Type[T]] = if determined_class == ScheduledTask: # type: ignore schedule_data = task_data.get("schedule", {}) common_args["schedule"] = parse_task_schedule(schedule_data) + common_args["schedule_anchor"] = parse_datetime(task_data.get("schedule_anchor")) return ScheduledTask(**common_args) # type: ignore elif determined_class == AdHocTask: # type: ignore common_args["token"] = task_data.get("token", "") diff --git a/helpers/task_scheduler.py.dox.md b/helpers/task_scheduler.py.dox.md index 892a6e8c2..26d2599b1 100644 --- a/helpers/task_scheduler.py.dox.md +++ b/helpers/task_scheduler.py.dox.md @@ -83,6 +83,12 @@ ## Runtime Contracts +- Recurring tasks persist `schedule_anchor`, the timestamp after which to find the next cron occurrence. Idle overdue tasks run once on the next tick, coalescing all missed occurrences. No startup-specific runner or one-minute lookback is used. The displayed `next_run` retains the overdue occurrence until it is claimed. +- Legacy tasks without an anchor use the latest of creation, update and last-run timestamps. JSON/YAML persistence and public serializers preserve the anchor. Cron arithmetic uses the task timezone and a UTC duration so crossing a daylight-saving offset does not shift the scheduled local hour. +- A changed cron/timezone or task-state transition resets the anchor; unchanged editor fields and name/prompt edits preserve it. Claim, completion and cancellation consume intervening occurrences. Re-enabling a disabled task starts from re-enablement, and long-running tasks do not replay slots missed during execution. Errors and tasks left running after interruption require explicit recovery, not automatic replay of potentially completed effects. +- Automatic dispatch rechecks idle/due status against saved state when claiming a task, so deletion, disablement, rescheduling or a completed manual run invalidate a stale selection. A task UUID has at most one registered worker in the scheduler process. Existing single-runtime ownership applies; this is not a distributed scheduler lock. +- `BaseTask.plugin_name` optionally routes a task to that enabled plugin's `run_scheduled_task(task, cancel_event)` hook, in a worker thread, instead of creating a chat or calling a model. The hook returns its result as a string and cooperatively checks `cancel_event`; cancellation waits for the worker before releasing task ownership and remains cancellation if the hook raises while stopping. Missing/disabled plugins and missing handlers fail closed, without agent fallback. Standard scheduling, state, results and persistence remain owned by this engine; serializers preserve the plugin owner and legacy tasks default to agent execution. +- Plugin tasks reject changes to model prompts and attachments; unchanged form values remain compatible with the standard editor. Plugin task creation skips chat initialization, while schedule/name/state editing and result inspection use the normal scheduler UI. - `SchedulerTaskList` keeps `usr/scheduler/tasks.json` as its default and prefers it when both formats exist. An existing `tasks.yaml` is supported when no JSON file exists; saves use the same selection and format. Loading never migrates, renames, or creates a second file. - JSON retains its existing Pydantic parser and `helpers.files` persistence path. Optional YAML uses `helpers.yaml` with the same task models. Invalid data raises before replacing the in-memory task list; YAML comments and formatting are regenerated on save. - Scheduler runs persist their owning task UUID in chat context data as `scheduler_task_uuid`. The `Agent.monologue/end` extension uses this association to atomically change an errored task to idle and persist its recovered result after a successful main-agent chat continuation. Legacy dedicated chats use their context ID as the task UUID; shared chats need the explicit association to avoid updating unrelated tasks. Failed continuations, subordinate results, and tasks no longer in error are ignored. Normal scheduler runs retain their existing callbacks and plan progression. @@ -107,6 +113,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_task_scheduler_timezone.py` + - `tests/test_task_scheduler_catchup.py` - `tests/test_task_scheduler_recovery.py` - `tests/test_scheduler_editor.py` - `tests/test_timezone_regressions.py` diff --git a/helpers/ui_bundler.py b/helpers/ui_bundler.py index a0a38c67c..b889b745c 100644 --- a/helpers/ui_bundler.py +++ b/helpers/ui_bundler.py @@ -3,6 +3,7 @@ from __future__ import annotations import hashlib from html.parser import HTMLParser import json +import os from pathlib import Path import re from typing import TYPE_CHECKING, Iterable @@ -226,15 +227,34 @@ def _iter_root_files( ) -> Iterable[Path]: if not root.is_dir(): return - candidates = root.rglob("*") if recursive else root.glob("*") - for path in sorted(candidates, key=lambda item: item.as_posix()): - if not path.is_file() or (suffixes and path.suffix.lower() not in suffixes): - continue - resolved = path.resolve() + root = root.resolve() + pending = [root] + candidates: list[tuple[Path, Path]] = [] + while pending: + directory = pending.pop() try: - resolved.relative_to(root) - except ValueError: + with os.scandir(directory) as iterator: + entries = list(iterator) + except OSError: continue + for entry in entries: + if entry.is_dir(follow_symlinks=False): + if recursive: + pending.append(Path(entry.path)) + continue + path = Path(entry.path) + if suffixes and path.suffix.lower() not in suffixes: + continue + try: + if not entry.is_file(): + continue + # Parents were traversed without following links; only file links need resolution. + resolved = path.resolve() if entry.is_symlink() else path + except (OSError, RuntimeError): + continue + if resolved.is_relative_to(root): + candidates.append((path, resolved)) + for _, resolved in sorted(candidates, key=lambda item: item[0].as_posix()): yield resolved @@ -264,10 +284,10 @@ def _bundle_signature(roots: list[_AssetRoot], entry_urls: Iterable[str]) -> str def _url_for_path(path: Path, roots: list[_AssetRoot]) -> str | None: - resolved = path.resolve() + # The caller supplies a contained, resolved path from _iter_root_files. for root in roots: try: - relative = resolved.relative_to(root.path).as_posix() + relative = path.relative_to(root.path).as_posix() except ValueError: continue prefix = "" if root.url_prefix == "/" else root.url_prefix diff --git a/helpers/ui_bundler.py.dox.md b/helpers/ui_bundler.py.dox.md index c666260df..b0348b16d 100644 --- a/helpers/ui_bundler.py.dox.md +++ b/helpers/ui_bundler.py.dox.md @@ -18,6 +18,7 @@ - The caller supplies one or more entry URLs. The scanner traverses their union once and adds enabled WebUI extension HTML/JavaScript entries because those paths are injected into the rendered document at runtime. It follows generic HTML links/scripts/components, CSS imports/URLs, JavaScript imports/exports/workers, and relative or root-local quoted asset URLs. - The bundler contains no library-specific path or module-name mappings. References that cannot be derived statically, including runtime-computed URLs, use the service worker's ordinary backend fetch-and-cache fallback. - Asset URLs resolve only inside the WebUI static root or an enabled WebUI extension/plugin root; external URLs, traversal, and symlink escapes are excluded. +- Inventory traversal reuses directory-entry metadata and never descends into directory symlinks. Resolve the root and file symlinks, retaining only contained targets; ordinary files do not need repeated ancestor checks across host mounts. Extension URLs reuse these verified paths. Request-derived asset URLs still undergo full resolution and containment checks. - Valid UTF-8 HTML, CSS, and JavaScript files no larger than 512 KiB each are embedded. Oversized eligible text is still scanned for dependencies but its body is omitted so the browser can request it normally. Images, audio, video, fonts, manifests, and other file types remain under normal browser HTTP caching. - Every entry carries the response content type required by browsers and native ES modules. - Bundle versions cover the caller entries, cache policy, and HTML/CSS/JavaScript path/mtime/size inventory. Policy or eligible-file changes therefore advance the service-worker cache version; the helper cache also participates in normal extension/plugin invalidation. diff --git a/models.py b/models.py index 46e93e16e..c177008a6 100644 --- a/models.py +++ b/models.py @@ -969,6 +969,7 @@ def _adjust_call_args(provider_name: str, model_name: str, kwargs: dict): return provider_name, model_name, kwargs +@extensible def _merge_provider_defaults( provider_type: ProviderModelType, original_provider: str, kwargs: dict ) -> tuple[str, dict]: diff --git a/plugins/AGENTS.md b/plugins/AGENTS.md index 94473ec56..3da2ee86a 100644 --- a/plugins/AGENTS.md +++ b/plugins/AGENTS.md @@ -32,6 +32,7 @@ - Prefer the existing [sandbox/worker facilities](../docs/developer/plugin-sandboxes.md#choosing-dependency-location) for plugin-owned Python, Node and native packages, heavy inference, browser/document/media workers and external integration dependencies. Keep lightweight tools, hooks, configuration and authenticated API/UI adapters in the framework; call the guest without importing guest-only libraries or adding them to root requirements or global pip/npm/apt installs. - Main-environment dependencies are legitimate only for functionality that must execute there. Document the concrete need in the plugin README and keep that dependency set minimal. `hooks.py` still runs in the framework's global Docker Python environment; sandboxing workers does not isolate plugin hooks. - Hooks own install/update/uninstall through framework APIs and may delegate guest provisioning to automatic worker setup. Reuse guest-owned manifests/installers and persistent environments with idempotent setup/retry; provision at first actual use, or at enablement/startup for early-needed features and configured listeners. Disable stops owned workers; uninstall cleans up owned resources while preserving shared dependencies and unrelated user data. +- For scheduled maintenance, register a task with `plugin_name` and implement `run_scheduled_task(task, cancel_event)` in `hooks.py`. Return a result string and cooperate with cancellation. Preserve user changes, disabled schedules, and task deletion. - `execute.py` is only for separate, explicitly requested manual actions unrelated to lifecycle setup, dependency installation, required initialization, updates or removal. Never require it or a user-run post-install command to make a plugin usable. - Plugin routes are `GET /plugins//`, `POST /api/plugins//`, and `POST /api/plugins` for management actions. - Local socket handlers live in `socket/` beside `api/`, derive from `helpers.socket_api.SocketHandler`, and resolve as `plugins//`. Follow [the socket contract](../socket/AGENTS.md); validate operation arguments and any scoped permissions in the handler. @@ -76,6 +77,7 @@ Direct child DOX files: | Child | Scope | | --- | --- | +| [_a0_cleaner/AGENTS.md](_a0_cleaner/AGENTS.md) | Container storage scans, automatic housekeeping, reviewed cleanup and scheduler integration. | | [_a0_connector/AGENTS.md](_a0_connector/AGENTS.md) | HTTP and WebSocket connector integration with remote tools and runtime bridges. | | [_a2a_chat/AGENTS.md](_a2a_chat/AGENTS.md) | FastA2A agent-to-agent chat tool. | | [_agent_editor/AGENTS.md](_agent_editor/AGENTS.md) | Deterministic sparse agent-profile editor API, helpers, and WebUI. | diff --git a/plugins/README.md b/plugins/README.md index 872de436d..cc1153e26 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -70,6 +70,10 @@ Plugins can also include an optional `hooks.py` at the plugin root. The framewor In Docker, `hooks.py` and local Python execution share the official image's global Python environment; sandbox destinations retain their own environments. +For scheduled maintenance, register a `ScheduledTask` with `plugin_name` set to the plugin's name and provide `run_scheduled_task(task, cancel_event)` in `hooks.py`. The scheduler calls the hook in a framework worker thread, without creating an agent chat or calling a model. Return a string for the task's result and check `cancel_event` during long operations. The plugin must be enabled; missing handlers fail rather than falling back to an agent. + +Register tasks idempotently and preserve user edits, disabled schedules and deletion. [A0Cleaner](_a0_cleaner/README.md) is a working example with an editable weekly task, persistent results and an actionable notification. + ### Configuration Hook Context Configuration hooks can distinguish why settings are being read or saved. Pass diff --git a/plugins/_a0_cleaner/AGENTS.md b/plugins/_a0_cleaner/AGENTS.md new file mode 100644 index 000000000..9c553bfc1 --- /dev/null +++ b/plugins/_a0_cleaner/AGENTS.md @@ -0,0 +1,43 @@ +# A0Cleaner DOX + +## Purpose + +- Own default storage housekeeping, user-selected cleanup and the A0Cleaner UI. + +## Ownership + +- `helpers/cleaner.py` owns the bounded inventory, review manifest, guarded deletion and persistent reports. +- `helpers/runtime.py` owns runtime paths, process/chat activity, settings, the scheduler task and notifications. +- `hooks.py` supplies `run_scheduled_task` and validates saved settings. The job-loop extension registers the task; it does not run cleanup itself. +- `api/cleaner.py` owns authenticated scan, review, cleanup, settings and schedule actions. +- `webui/` owns the modal, state, styling, settings entry and 256×256 thumbnail under 20 KB. + +## Local Contracts + +- Automatic cleanup defaults on for aged Python/Node download caches, installer leftovers, retired browser profiles, old inactive-chat screenshots, temporary captures and unused Chromium installations. Preserve explicit per-area and master opt-outs. Embedding cache and custom folders require manual selection; never add them to automatic cleanup. +- Keep source, settings, models, installed apps, uploads and chat text outside built-in cleanup areas. Time Travel owns its own retention; never prune its repositories here. +- Skip required/running browser versions, shared/active/recent profiles, recent/running/paused chats, active process paths, symbolic links, hard links and mounts. Unknown process ownership fails closed for the affected UID; unavailable root/current-UID inspection aborts cleanup. +- Scans are read-only, limited to 250,000 entries and 90 seconds. Inspection errors disable the affected area. Age uses both mtime and ctime, so an old timestamp on a newly copied file cannot qualify it. +- Cleanup requires the current, unexpired scan ID and unchanged settings. Manual cleanup requires explicit confirmation. Validate roots again, walk all parent directories with O_NOFOLLOW, compare file identity/size/timestamps and unlink through directory descriptors. Changed files are skipped and never counted as removed. Consume the manifest after every deletion pass. +- Use a cross-process operation lock. Poll cancellation and plugin activation during work. Persist partial completion before reporting interruption; keep the last 40 cleanup records and the latest scheduled result separately from fresh scans. +- The normal scheduler owns cadence/state/results through the `plugin_name` hook contract. Default Monday 09:00 in the configured timezone. Register once, preserve edited/disabled schedules and respect task deletion. Never create a model chat for housekeeping. +- Custom rules accept only proper subfolders of A0 workdir/projects/downloads/uploads/tmp, with no symlink ancestors, overlapping rules, protected metadata or overlapping managed roots. +- Report allocated file-byte estimates, not guaranteed host block recovery from immutable container image layers. No chat contents or process command lines belong in reports or notifications. +- Use native A0 notifications. The Clean up action opens the cleaner and dismisses its notification as read; toast clicks must never authorize deletion directly. +- Open the cleaner through plugin settings or its notification action; do not add a sidebar dropdown entry. + +## Work Guidance + +- Add a cleanup area only after tracing its producer, readers and lifecycle on the framework runtime. +- Keep policy in the catalog, not in browser-provided filesystem paths. Do not add arbitrary shell cleanup commands. +- Preserve the supplied Agent Zero logo geometry in thumbnail revisions; keep generation provenance in `webui/thumbnail.prompt.txt`. + +## Verification + +- Run `tests/test_a0_cleaner.py`, scheduler plugin-task tests and the cleaner store tests. +- Exercise live scan, opt-outs, preview/cancel/clean, custom rules, scheduled execution and notifications with controlled files before running default cleanup. +- Check desktop/mobile layouts and settings/schedule persistence on the live Docker target. + +## Child DOX Index + +No child DOX files. diff --git a/plugins/_a0_cleaner/README.md b/plugins/_a0_cleaner/README.md new file mode 100644 index 000000000..7c8336c5f --- /dev/null +++ b/plugins/_a0_cleaner/README.md @@ -0,0 +1,38 @@ +# A0Cleaner + +Open the plugin's settings and select **Open A0Cleaner**, or use the **Clean up** notification button, which also dismisses the toast. Opening it scans automatically when the previous scan is older than an hour. Choose areas, review the file list, and select **Clean up**. + +A real **A0Cleaner** task appears in Agent Zero's Scheduled Tasks. It runs weekly, Monday at 09:00 in the configured timezone, with no model call. Change its cadence in the cleaner or edit its cron schedule through **Schedule details**. Deleting or disabling the task is respected. Each run saves its results in the cleaner and sends an A0 notification with a **Clean up** button for remaining files. + +## Defaults + +| Area | Default action | Retention | +| --- | --- | --- | +| Python and Node download caches | Automatic | 30 days | +| Plugin/skill installer staging | Automatic | 7 days | +| Retired browser profiles | Automatic | 30 days, inactive profiles only | +| Old chat screenshots | Automatic | 30 days, inactive chats only | +| Temporary browser/desktop captures | Automatic | 30 days | +| Unused Chromium installations | Automatic | 30 days, required and running versions excluded | +| Embedding cache | Manual selection | 30 days | +| Custom folders | Manual selection | Per-folder age | + +The master switch and each area's **Auto** switch persist explicit choices. Automatic cleanup never includes custom folders or the embedding cache. Clearing retired profiles removes their saved sign-ins; clearing chat screenshots removes those previews while retaining chat text and uploaded images. Embedding cleanup may cause remote model usage when the cache is rebuilt. + +A custom age of 0 includes all eligible files and still requires manual confirmation. Custom folders must be subfolders of A0's workdir, projects, downloads, uploads or tmp. Project roots, configuration, Git repositories, managed browser directories and Time Travel storage are protected. Time Travel keeps its own retention lifecycle; A0Cleaner does not delete its repositories. Installed models and applications, uploads, chat transcripts and arbitrary temporary folders are not treated as disposable caches. + +## Cleanup contract + +Scans inspect metadata and do not delete files. Cleanup uses the reviewed scan ID, verifies each file's identity, size and timestamps, and skips changed files. Symbolic links, hard links and nested mounts are excluded. Deletions walk parent directories with `O_NOFOLLOW` and use directory file descriptors. Active process paths, running package managers, shared browser profiles, the required Chromium revision, and active/recent chats are protected. Files owned by another UID whose open files cannot be inspected are skipped. + +Scans are capped at 250,000 entries and 90 seconds. Failed inspection leaves the affected area untouched. Per-instance locks serialize scans and cleanup; scheduled cancellation and plugin disablement stop further deletion. A scan expires after 24 hours and cannot be replayed after cleanup. Reports, the latest scheduled result and the last 40 cleanup records live under `usr/plugin_data/_a0_cleaner/`. + +Sizes are allocated file-byte estimates. The disk meter reports the filesystem visible to the container; deleting files inherited from an immutable image layer may not free host disk space until that image is replaced. + +## Implementation and verification + +The scheduler owns timing, state and result persistence. A0Cleaner's `run_scheduled_task` hook owns cleanup, and its job-loop extension only registers the task once. The authenticated plugin API performs blocking filesystem work in worker threads. The UI uses the existing A0 modal, icon, toast and scheduler components. + +Run `pytest tests/test_a0_cleaner.py tests/test_scheduler_plugin_tasks.py` and `node --test tests/test_a0_cleaner_store.mjs`. Verify scan, area switches, preview/cancel/clean, custom folders, schedule save/reopen, notifications and narrow/mobile layouts on the live framework runtime. + +The 256 × 256 thumbnail uses the supplied Agent Zero logo, generated with the built-in image tool and optimized to JPEG under 20 KB. Its generation brief is in `webui/thumbnail.prompt.txt`. diff --git a/plugins/_a0_cleaner/api/cleaner.py b/plugins/_a0_cleaner/api/cleaner.py new file mode 100644 index 000000000..64349f0a6 --- /dev/null +++ b/plugins/_a0_cleaner/api/cleaner.py @@ -0,0 +1,33 @@ +import asyncio + +from helpers.api import ApiHandler, Request, Response +from plugins._a0_cleaner.helpers import runtime +from plugins._a0_cleaner.helpers.cleaner import CleanerError, read_json + + +class A0CleanerApi(ApiHandler): + async def process(self, input: dict, request: Request) -> dict | Response: + try: + action = input.get('action', 'status') + cleaner = runtime.service() + if action == 'status': + result = await asyncio.to_thread(cleaner.latest) + result['schedule'] = await runtime.schedule_info() + result['scheduled'] = read_json(cleaner.state/'scheduled.json') + return {'ok': True, **result} + if action == 'scan': + return {'ok': True, 'report': await asyncio.to_thread(cleaner.scan)} + if action == 'preview': + return {'ok': True, 'preview': await asyncio.to_thread(cleaner.preview, input.get('scan_id'), input.get('groups'))} + if action == 'clean': + return {'ok': True, **await asyncio.to_thread(cleaner.clean, input.get('scan_id'), input.get('groups'), confirmed=input.get('confirmed'))} + if action == 'settings': + settings = input.get('settings') + if not isinstance(settings, dict): + raise CleanerError('Invalid cleanup settings.') + return {'ok': True, 'config': await asyncio.to_thread(runtime.save_settings, settings)} + if action == 'schedule': + return {'ok': True, 'schedule': await runtime.set_schedule(input.get('cadence'))} + raise CleanerError('Unknown cleaner action.') + except (CleanerError, OSError) as exc: + return {'ok': False, 'error': str(exc)} diff --git a/plugins/_a0_cleaner/default_config.yaml b/plugins/_a0_cleaner/default_config.yaml new file mode 100644 index 000000000..30c01f60c --- /dev/null +++ b/plugins/_a0_cleaner/default_config.yaml @@ -0,0 +1,6 @@ +automatic: true +automatic_areas: [pip, npm, staging, profiles, screenshots, captures, browser_versions] +cache_days: 30 +staging_days: 7 +review_days: 30 +custom_folders: [] diff --git a/plugins/_a0_cleaner/extensions/python/job_loop/_50_schedule.py b/plugins/_a0_cleaner/extensions/python/job_loop/_50_schedule.py new file mode 100644 index 000000000..3a388c311 --- /dev/null +++ b/plugins/_a0_cleaner/extensions/python/job_loop/_50_schedule.py @@ -0,0 +1,11 @@ +from helpers.extension import Extension +from helpers.print_style import PrintStyle +from plugins._a0_cleaner.helpers.runtime import ensure_task + + +class RegisterCleanerSchedule(Extension): + async def execute(self, **kwargs): + try: + await ensure_task() + except Exception as exc: + PrintStyle.error(f'A0Cleaner schedule: {exc}') diff --git a/plugins/_a0_cleaner/helpers/cleaner.py b/plugins/_a0_cleaner/helpers/cleaner.py new file mode 100644 index 000000000..32d766d9f --- /dev/null +++ b/plugins/_a0_cleaner/helpers/cleaner.py @@ -0,0 +1,434 @@ +"""Inventory and identity-checked cleanup of known disposable container files.""" +from __future__ import annotations + +from contextlib import contextmanager +from dataclasses import dataclass +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import shutil +import stat +import tempfile +import time +import uuid + +from filelock import FileLock, Timeout + + +DAY = 86400 +PROTECTED_NAMES = {'.git', '.a0proj', '.time_travel', '.env', 'repo.git'} +AUTO_AREAS = {'pip', 'npm', 'staging', 'profiles', 'screenshots', 'captures', 'browser_versions'} +DEFAULTS = {'automatic': True, 'automatic_areas': sorted(AUTO_AREAS), 'cache_days': 30, + 'staging_days': 7, 'review_days': 30, 'custom_folders': []} + + +class CleanerError(ValueError): + pass + + +def config_values(values=None): + result = {**DEFAULTS, **(values or {})} + if not isinstance(result['automatic'], bool): + raise CleanerError('Automatic cleanup must be on or off.') + if not isinstance(result['automatic_areas'], list) or any(not isinstance(item, str) or item not in AUTO_AREAS for item in result['automatic_areas']): + raise CleanerError('Choose supported areas for automatic cleanup.') + result['automatic_areas'] = sorted(set(result['automatic_areas'])) + for key in ('cache_days', 'staging_days', 'review_days'): + value = result[key] + if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value <= 3650: + raise CleanerError('File age must be between 1 and 3650 days.') + folders = result['custom_folders'] + if not isinstance(folders, list) or len(folders) > 20: + raise CleanerError('Choose up to 20 custom folders.') + return result + + +def fingerprint(info): + return [info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns] + + +def allocated(info): + return info.st_blocks * 512 + + +def atomic_json(path, value): + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(mode='w', dir=path.parent, delete=False, encoding='utf-8') as handle: + temporary = handle.name + json.dump(value, handle) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + + +def read_json(path, default=None): + try: + return json.loads(path.read_text()) + except FileNotFoundError: + return default + + +@contextmanager +def directory_fd(path: Path): + """Walk from / with O_NOFOLLOW, including every ancestor of a deletion target.""" + path = Path(os.path.abspath(path)) + fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY) + try: + for part in path.parts[1:]: + next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd) + os.close(fd) + fd = next_fd + yield fd + finally: + os.close(fd) + + +@dataclass +class Area: + id: str + title: str + icon: str + automatic: bool + days: int + roots: list[Path] + impact: str + kind: str = 'files' + + +class Cleaner: + def __init__(self, base, home, state, *, config=None, process_inventory=None, chat_activity=None, + enabled=lambda: True, clock=time.time, cancel_event=None, browser_revision=''): + self.base, self.home, self.state = Path(base), Path(home), Path(state) + self.config = config_values(config) + self.process_inventory = process_inventory or (lambda: {'paths': [], 'package_busy': False}) + self.chat_activity = chat_activity or (lambda chat: None) + self.enabled, self.clock, self.cancel_event = enabled, clock, cancel_event + self._last_enabled_check = float('-inf') + self.browser_revision = str(browser_revision) + self._mounts = set() + self.state.mkdir(parents=True, exist_ok=True) + self.lock = FileLock(str(self.state / 'operation.lock'), timeout=0, is_singleton=True) + + def custom_path(self, raw, *, allow_missing=False): + if not isinstance(raw, str) or not raw.strip() or '\0' in raw or not Path(raw).is_absolute(): + raise CleanerError('Choose an absolute folder path.') + path = Path(os.path.abspath(raw)) + if any(part in PROTECTED_NAMES or part.startswith('.env.') for part in path.parts): + raise CleanerError('That folder contains protected configuration or history.') + permitted = [self.base/'usr/workdir', self.base/'usr/downloads', self.base/'usr/uploads', self.base/'tmp'] + allowed = any(path.is_relative_to(root) and path != root for root in permitted) + projects = self.base/'usr/projects' + allowed = allowed or (path.is_relative_to(projects) and len(path.relative_to(projects).parts) >= 2) + if not allowed: + raise CleanerError('Choose a subfolder of workdir, a project, downloads, uploads or A0 tmp.') + managed = [self.base/'tmp/browser', self.base/'tmp/desktop', self.base/'tmp/playwright', + self.base/'tmp/memory', self.state] + managed += [root for area in self.areas(include_custom=False) for root in area.roots] + if any(path.is_relative_to(root) or root.is_relative_to(path) for root in managed): + raise CleanerError('Use the dedicated cleanup area for that folder.') + try: + checked = path + if allow_missing: + while not checked.exists() and not checked.is_symlink(): + checked = checked.parent + with directory_fd(checked): + pass + except OSError as exc: + raise CleanerError('Choose an existing folder without symbolic links.') from exc + return path + + def areas(self, include_custom=True, *, validate_custom=False): + cfg = self.config + areas = [ + Area('pip', 'Python download cache', 'deployed_code', True, cfg['cache_days'], + [self.home/'.cache/pip'], 'Packages may need to be downloaded again.'), + Area('npm', 'Node download cache', 'deployed_code', True, cfg['cache_days'], + [self.home/'.npm/_cacache', self.home/'.npm/_logs'], 'Packages may need to be downloaded again.'), + Area('staging', 'Installer leftovers', 'inventory_2', True, cfg['staging_days'], + [self.base/'tmp'/name for name in ('plugin_uploads', 'plugin_installs', 'plugins_installer', 'skill_imports')], + 'Removes old temporary installation files.'), + Area('profiles', 'Retired browser profiles', 'web', False, cfg['review_days'], + [self.base/'tmp/browser/sessions'], 'Saved sign-ins and tabs in these retired profiles will be removed.', 'profiles'), + Area('screenshots', 'Old chat screenshots', 'photo_library', False, cfg['review_days'], + [self.base/'usr/chats'], 'Old screenshot previews will no longer open. Chat text and uploaded images remain.', 'screenshots'), + Area('captures', 'Temporary captures', 'screenshot_monitor', False, cfg['review_days'], + [self.base/'tmp/browser/screenshots', self.base/'tmp/desktop/screenshots'], + 'Old links to these temporary captures will no longer open.'), + Area('embeddings', 'Embedding cache', 'memory', False, cfg['review_days'], + [self.base/'tmp/memory/embeddings'], 'Embeddings are rebuilt when needed; remote models may incur usage.'), + Area('browser_versions', 'Unused browser versions', 'download_done', False, cfg['review_days'], + [self.base/'tmp/playwright'], 'Older browser installations will be removed. Other tools may download them again.', 'versions'), + ] + for area in areas: + area.automatic = area.id in cfg['automatic_areas'] + if include_custom: + seen = [] + for index, folder in enumerate(cfg['custom_folders']): + if not isinstance(folder, dict) or not isinstance(folder.get('days'), int) or isinstance(folder['days'], bool) or not 0 <= folder['days'] <= 3650: + raise CleanerError('Each custom folder needs a path and a valid file age.') + path = self.custom_path(folder.get('path'), allow_missing=not validate_custom) + if any(path.is_relative_to(other) or other.is_relative_to(path) for other in seen): + raise CleanerError('Custom folders must not overlap.') + seen.append(path) + areas.append(Area(f'custom-{index}', path.name, 'folder', False, folder['days'], [path], + (f'Files older than {folder["days"]} days in this folder will be permanently removed.' + if folder['days'] else 'All eligible files in this folder will be permanently removed.'), 'custom')) + return areas + + def _check(self): + if self.cancel_event and self.cancel_event.is_set(): + raise CleanerError('Cleanup stopped.') + if time.monotonic() - self._last_enabled_check >= .2: + if not self.enabled(): + raise CleanerError('A0Cleaner is disabled.') + self._last_enabled_check = time.monotonic() + + def _walk(self, root, budget): + if not root.exists() and not root.is_symlink(): + return + with directory_fd(root) as fd: + device = os.fstat(fd).st_dev + stack = [root] + while stack: + self._check() + if time.monotonic() > budget['deadline'] or budget['files'] > 250000: + raise CleanerError('Scan limit reached. Select a smaller custom folder and scan again.') + folder = stack.pop() + with directory_fd(folder) as fd, os.scandir(fd) as entries: + for entry in entries: + budget['files'] += 1 + if budget['files'] > 250000 or (budget['files'] % 256 == 0 and time.monotonic() > budget['deadline']): + raise CleanerError('Scan limit reached. Select a smaller custom folder and scan again.') + if entry.name in PROTECTED_NAMES or entry.name.startswith('.env.'): + continue + info = entry.stat(follow_symlinks=False) + if info.st_dev != device or stat.S_ISLNK(info.st_mode): + continue + path = folder/entry.name + if str(path) in self._mounts: + continue + if stat.S_ISDIR(info.st_mode): + stack.append(path) + elif stat.S_ISREG(info.st_mode) and info.st_nlink == 1: + yield path, info + + @staticmethod + def _in_use(root, inventory): + return any(Path(path).is_relative_to(root) for path in inventory['paths']) + + def _roots(self, area, cutoff, inventory): + if area.id in ('pip', 'npm', 'staging') and inventory['package_busy']: + return + for root in area.roots: + if area.kind not in ('profiles', 'screenshots', 'versions'): + if not self._in_use(root, inventory): + yield root, '' + continue + if not root.exists(): + continue + with directory_fd(root) as fd, os.scandir(fd) as entries: + for entry in entries: + if not entry.is_dir(follow_symlinks=False) or entry.is_symlink(): + continue + child = root/entry.name + if area.kind == 'versions': + if not self.browser_revision or not entry.name.startswith(('chromium-', 'chromium_headless_shell-')): + continue + revision = entry.name.rsplit('-', 1)[-1] + if not revision.isdigit() or revision == self.browser_revision or self._in_use(child, inventory): + continue + yield child, '' + continue + if area.kind == 'profiles': + if entry.name in ('shared', 'default', '__shared__') or self._in_use(child, inventory): + continue + yield child, '' + else: + activity = self.chat_activity(entry.name) + if activity is not None and activity < cutoff: + yield child/'screenshots', entry.name + + def _scan(self): + self._check() + now = self.clock() + inventory = self.process_inventory() + self._mounts = set(inventory.get('mounts', [])) + budget = {'files': 0, 'deadline': time.monotonic() + 90} + groups, candidates = [], [] + for area in self.areas(): + items = [] + errors = [] + cutoff = now - area.days*DAY + try: + for root, chat in self._roots(area, cutoff, inventory): + contents = list(self._walk(root, budget)) + # Retired profiles are one unit: a recent file protects the entire profile. + if area.kind in ('profiles', 'versions') and any(max(s.st_mtime, s.st_ctime) >= cutoff for _, s in contents): + continue + for path, info in contents: + if max(info.st_mtime, info.st_ctime) >= cutoff or str(path) in inventory['paths']: + continue + if info.st_uid in inventory.get('opaque_uids', []): + continue + if area.id in ('screenshots', 'captures') and path.suffix.lower() not in ('.png', '.jpg', '.jpeg', '.webp'): + continue + items.append({'path': str(path), 'root': str(root), 'group': area.id, 'chat': chat, + 'stat': fingerprint(info), 'bytes': allocated(info)}) + except OSError: + errors.append('Some files could not be inspected. This area was left untouched.') + items = [] + groups.append({'id': area.id, 'title': area.title, 'icon': area.icon, 'automatic': area.automatic, + 'auto_supported': area.id in AUTO_AREAS, + 'days': area.days, 'kind': area.kind, 'paths': [str(p) for p in area.roots], + 'impact': area.impact, 'files': len(items), 'bytes': sum(p['bytes'] for p in items), + 'blocked': errors[0] if errors else '', + 'busy': area.id in ('pip','npm','staging') and inventory['package_busy']}) + candidates.extend(items) + token = uuid.uuid4().hex + disk = shutil.disk_usage(self.base) + report = {'id': token, 'at': now, 'groups': groups, 'files': len(candidates), + 'bytes': sum(c['bytes'] for c in candidates), + 'automatic_bytes': sum(g['bytes'] for g in groups if g['automatic']), + 'disk': {'total': disk.total, 'used': disk.used, 'free': disk.free}} + atomic_json(self.state/'manifest.json', {'id': token, 'at': now, 'config': self.config, 'files': candidates}) + atomic_json(self.state/'report.json', report) + return report + + @contextmanager + def operation(self, label): + try: + with self.lock: + atomic_json(self.state/'status.json', {'operation': label, 'started': self.clock()}) + try: + yield + finally: + atomic_json(self.state/'status.json', {}) + except Timeout as exc: + raise CleanerError('A0Cleaner is already working.') from exc + + def scan(self): + with self.operation('Scanning'): + return self._scan() + + def latest(self): + status = read_json(self.state/'status.json', {}) + if status: + try: + with self.lock: + status = {} # The previous process stopped before clearing its status. + except Timeout: + pass + return {'report': read_json(self.state/'report.json'), 'status': status, + 'activity': read_json(self.state/'activity.json', []), 'config': self.config} + + def _selection(self, token, groups): + if not isinstance(groups, list) or not groups or any(not isinstance(group, str) for group in groups): + raise CleanerError('Select at least one cleanup area.') + manifest = read_json(self.state/'manifest.json', {}) + report = read_json(self.state/'report.json', {}) + if not token or token != manifest.get('id') or token != report.get('id') or self.clock()-manifest['at'] > DAY: + raise CleanerError('This scan is out of date. Scan again before cleaning.') + if manifest.get('config') != self.config: + raise CleanerError('Cleanup settings changed. Scan again before cleaning.') + selected = [g for g in report['groups'] if g['id'] in groups] + if len(selected) != len(set(groups)) or any(g['blocked'] for g in selected): + raise CleanerError('This cleanup selection is unavailable. Scan again.') + return selected, [f for f in manifest['files'] if f['group'] in groups] + + def preview(self, token, groups): + with self.operation('Preparing cleanup'): + selected, items = self._selection(token, groups) + return {'id': token, 'groups': selected, 'files': len(items), 'bytes': sum(i['bytes'] for i in items), + 'paths': [i['path'] for i in items[:200]], 'more_paths': max(0, len(items)-200)} + + def _delete(self, item, cutoff): + path = Path(item['path']) + with directory_fd(path.parent) as fd: + info = os.stat(path.name, dir_fd=fd, follow_symlinks=False) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or fingerprint(info) != item['stat']: + return False + if max(info.st_mtime, info.st_ctime) >= cutoff: + return False + os.unlink(path.name, dir_fd=fd) + return True + + def _clean(self, token, groups, *, automatic=False): + selected, items = self._selection(token, groups) + allowed = {area.id: area for area in self.areas()} + if automatic and any(not allowed[g['id']].automatic for g in selected): + raise CleanerError('This area requires manual confirmation.') + inventory = self.process_inventory() + self._mounts = set(inventory.get('mounts', [])) + eligible = {} + for group in selected: + area = allowed[group['id']] + cutoff = self.clock()-area.days*DAY + roots = {str(root) for root, _ in self._roots(area, cutoff, inventory)} + if area.kind in ('profiles', 'versions'): + for root in list(roots): + try: + if any(max(info.st_mtime, info.st_ctime) >= cutoff for _, info in self._walk(Path(root), {'files': 0, 'deadline': time.monotonic()+90})): + roots.remove(root) + except OSError: + roots.remove(root) + eligible[area.id] = roots + result = {'at': self.clock(), 'automatic': automatic, 'bytes': 0, 'files': 0, 'skipped': 0, + 'areas': [g['title'] for g in selected], 'stopped': False} + try: + for item in items: + self._check() + area = allowed[item['group']] + root = Path(item['root']) + path = Path(item['path']) + if not any(root.is_relative_to(base) for base in area.roots) or not path.is_relative_to(root) or any(part in PROTECTED_NAMES or part.startswith('.env.') for part in path.parts): + raise CleanerError('Cleanup manifest is invalid. Scan again.') + blocked = str(root) not in eligible[area.id] or any(str(parent) in self._mounts for parent in (path, *path.parents) if parent != root and parent.is_relative_to(root)) + try: + blocked = blocked or path.lstat().st_uid in inventory.get('opaque_uids', []) + except OSError: + blocked = True + if item['chat']: + activity = self.chat_activity(item['chat']) + blocked = blocked or activity is None or activity >= self.clock()-area.days*DAY + if blocked: + result['skipped'] += 1 + continue + try: + if self._delete(item, self.clock()-area.days*DAY): + result['files'] += 1 + result['bytes'] += item['bytes'] + else: + result['skipped'] += 1 + except OSError: + result['skipped'] += 1 + except CleanerError: + result['stopped'] = True + raise + finally: + activity = read_json(self.state/'activity.json', []) + atomic_json(self.state/'activity.json', [result, *activity][:40]) + # A consumed manifest can never authorize a second deletion pass. + atomic_json(self.state/'manifest.json', {}) + return result + + def clean(self, token, groups, *, confirmed=False): + if confirmed is not True: + raise CleanerError('Confirm the selected cleanup areas first.') + with self.operation('Cleaning'): + result = self._clean(token, groups) + report = self._scan() + return {'result': result, 'report': report} + + def scheduled(self): + with self.operation('Scheduled maintenance'): + report = self._scan() + result = None + groups = [g['id'] for g in report['groups'] if g['automatic'] and g['files'] and not g['blocked']] + if self.config['automatic'] and groups: + result = self._clean(report['id'], groups, automatic=True) + report = self._scan() + summary = {'at': self.clock(), 'found_bytes': report['bytes'], 'freed_bytes': result['bytes'] if result else 0, + 'skipped': result['skipped'] if result else 0, 'report_id': report['id']} + atomic_json(self.state/'scheduled.json', summary) + return summary diff --git a/plugins/_a0_cleaner/helpers/runtime.py b/plugins/_a0_cleaner/helpers/runtime.py new file mode 100644 index 000000000..8d7f75357 --- /dev/null +++ b/plugins/_a0_cleaner/helpers/runtime.py @@ -0,0 +1,177 @@ +from __future__ import annotations + +from datetime import datetime +import json +import os +from pathlib import Path + +import psutil +from filelock import FileLock, Timeout + +from helpers import files, plugins +from helpers.localization import Localization +from helpers.notification import NotificationManager, NotificationPriority, NotificationType +from helpers.task_scheduler import TaskScheduler, ScheduledTask, TaskSchedule, TaskState, serialize_task +from plugins._a0_cleaner.helpers.cleaner import Cleaner, CleanerError, atomic_json, read_json + +NAME = '_a0_cleaner' +TASK_ID = 'a0-cleaner-maintenance' +CADENCES = {'daily': ('0', '9', '*', '*', '*'), 'weekly': ('0', '9', '*', '*', '1'), 'monthly': ('0', '9', '1', '*', '*')} + + +def state_dir(): + return Path(files.get_abs_path('usr/plugin_data', NAME)) + + +def process_inventory(): + paths = set() + package_busy = False + opaque_uids = set() + for process in psutil.process_iter(): + try: + args = process.cmdline() + try: + paths.update(item.path for item in process.open_files()) + cwd = process.cwd() + if cwd: + paths.add(cwd) + except psutil.AccessDenied: + uid = process.uids().effective + if uid in (0, os.geteuid()): + raise + opaque_uids.add(uid) + for arg in args: + value = arg.partition('=')[2] if '=' in arg else arg + if value.startswith('/'): + paths.add(value) + if Path(arg).name in ('pip', 'pip3', 'uv', 'npm', 'npm-cli.js', 'npx', 'apt', 'apt-get', 'dpkg'): + package_busy = True + if '-m' in args and 'pip' in args: + package_busy = True + except (psutil.NoSuchProcess, psutil.ZombieProcess): + continue + except psutil.AccessDenied as exc: + raise CleanerError('Running processes could not be checked. Cleanup is paused.') from exc + return {'paths': sorted(paths), 'package_busy': package_busy, 'opaque_uids': sorted(opaque_uids), + 'mounts': [partition.mountpoint for partition in psutil.disk_partitions(all=True)]} + + +def chat_activity(chat_id): + from agent import AgentContext + + context = AgentContext.get(chat_id) + if context: + if context.is_running() or context.paused: + return float('inf') + return context.last_message.timestamp() if context.last_message else None + try: + data = json.loads(Path(files.get_abs_path('usr/chats', chat_id, 'chat.json')).read_text()) + stamp = datetime.fromisoformat(data['last_message']) + if stamp.tzinfo is None: + stamp = Localization.get().localize_naive_datetime(stamp) + return stamp.timestamp() + except (OSError, ValueError, KeyError, TypeError): + return None + + +def service(cancel_event=None, config=None): + from plugins._browser.helpers.playwright import get_playwright_chromium_revision + + return Cleaner(files.get_base_dir(), Path.home(), state_dir(), + config=plugins.get_plugin_config(NAME) if config is None else config, + process_inventory=process_inventory, chat_activity=chat_activity, + enabled=lambda: plugins.get_toggle_state(NAME) == 'enabled', cancel_event=cancel_event, + browser_revision=get_playwright_chromium_revision()) + + +async def ensure_task(*, recreate=False): + state_dir().mkdir(parents=True, exist_ok=True) + try: + with FileLock(str(state_dir()/'schedule.lock'), timeout=0): + return await _ensure_task(recreate=recreate) + except Timeout as exc: + raise CleanerError('The cleaner schedule is being updated. Try again shortly.') from exc + + +async def _ensure_task(*, recreate=False): + scheduler = TaskScheduler.get() + await scheduler.reload() + task = scheduler.get_task_by_uuid(TASK_ID) + if task: + if task.plugin_name != NAME: + raise CleanerError('The cleaner schedule ID is already in use.') + return task + marker = state_dir()/'schedule-installed.json' + if marker.exists() and not recreate: + return None + task = ScheduledTask( + uuid=TASK_ID, name='A0Cleaner', plugin_name=NAME, system_prompt='', + prompt='Scan storage, clean the enabled areas, and report files awaiting review.', + schedule=TaskSchedule(minute='0', hour='9', day='*', month='*', weekday='1', + timezone=Localization.get().get_timezone()), + ) + await scheduler.add_task(task) + atomic_json(marker, {'task_id': TASK_ID}) + return task + + +async def schedule_info(): + task = await ensure_task() + if task is None: + return {'cadence': 'off', 'task': None} + cadence = next((key for key, fields in CADENCES.items() if task.schedule.to_crontab() == ' '.join(fields)), 'custom') + if task.state == TaskState.DISABLED: + cadence = 'off' + return {'cadence': cadence, 'task': serialize_task(task)} + + +async def set_schedule(cadence): + if cadence not in (*CADENCES, 'off'): + raise CleanerError('Choose daily, weekly, monthly or off.') + task = await ensure_task(recreate=True) + scheduler = TaskScheduler.get() + if task.state == TaskState.RUNNING: + raise CleanerError('Wait for the current maintenance run to finish.') + if cadence == 'off': + await scheduler.update_task(TASK_ID, state=TaskState.DISABLED) + else: + fields = CADENCES[cadence] + schedule = TaskSchedule(**dict(zip(('minute','hour','day','month','weekday'), fields)), timezone=task.schedule.timezone) + await scheduler.update_task(TASK_ID, schedule=schedule, state=TaskState.IDLE) + return await schedule_info() + + +def format_bytes(size): + for unit in ('B', 'KB', 'MB', 'GB', 'TB'): + if size < 1024 or unit == 'TB': + return f'{size:.1f} {unit}' if unit != 'B' else f'{size} B' + size /= 1024 + + +def notify(summary): + found, freed = summary['found_bytes'], summary['freed_bytes'] + if not found and not freed: + return + action = (f'
') if found else '' + NotificationManager.send_notification( + type=NotificationType.INFO if found else NotificationType.SUCCESS, + priority=NotificationPriority.NORMAL, title=f'A0 found {format_bytes(found)} of unused files' if found else f'A0 cleaned {format_bytes(freed)}', + message=(f'{format_bytes(freed)} cleaned automatically.' if freed else '') + action, + display_time=0 if found else 6, group='a0_cleaner', id='a0_cleaner_scan', + ) + + +def run_scheduled(cancel_event=None): + summary = service(cancel_event).scheduled() + notify(summary) + return f"Cleaned {format_bytes(summary['freed_bytes'])}. {format_bytes(summary['found_bytes'])} available for review." + + +def save_settings(settings): + cleaner = service(config=settings) + cleaner.areas(validate_custom=True) + with cleaner.operation('Saving settings'): + plugins.save_plugin_config(NAME, '', '', cleaner.config) + return cleaner.config diff --git a/plugins/_a0_cleaner/hooks.py b/plugins/_a0_cleaner/hooks.py new file mode 100644 index 000000000..9c2278fd8 --- /dev/null +++ b/plugins/_a0_cleaner/hooks.py @@ -0,0 +1,11 @@ +from plugins._a0_cleaner.helpers import runtime + + +def run_scheduled_task(task, cancel_event): + return runtime.run_scheduled(cancel_event) + + +def save_plugin_config(settings, **kwargs): + cleaner = runtime.service(config=settings) + cleaner.areas(validate_custom=True) + return cleaner.config diff --git a/plugins/_a0_cleaner/plugin.yaml b/plugins/_a0_cleaner/plugin.yaml new file mode 100644 index 000000000..6e6f77ce0 --- /dev/null +++ b/plugins/_a0_cleaner/plugin.yaml @@ -0,0 +1,9 @@ +name: _a0_cleaner +title: A0Cleaner +description: Automatic storage housekeeping, clear cleanup choices and weekly scans for your Agent Zero instance. +version: 0.1.0 +always_enabled: false +settings_sections: + - agent +per_project_config: false +per_agent_config: false diff --git a/plugins/_a0_cleaner/webui/cleaner-store.js b/plugins/_a0_cleaner/webui/cleaner-store.js new file mode 100644 index 000000000..627fb4f83 --- /dev/null +++ b/plugins/_a0_cleaner/webui/cleaner-store.js @@ -0,0 +1,138 @@ +import { createStore } from '/js/AlpineStore.js'; +import { callJsonApi } from '/js/api.js'; +import { store as schedulerStore } from '/plugins/_scheduler/webui/scheduler/scheduler-store.js'; + +const model = { + report: null, activity: [], scheduled: null, schedule: null, config: null, + selected: [], tab: 'overview', busy: false, operation: '', externalBusy: false, + preview: null, folderPath: '', folderDays: 30, mounted: false, _timer: null, _generation: 0, + + async api(action, data = {}) { + const response = await callJsonApi('/plugins/_a0_cleaner/cleaner', { action, ...data }); + if (!response?.ok) throw new Error(response?.error || 'A0Cleaner could not complete this action.'); + return response; + }, + toast(message, type = 'error') { globalThis.justToast?.(message, type, 5000, 'a0-cleaner'); }, + bytes(value = 0) { + const units = ['B', 'KB', 'MB', 'GB', 'TB']; let i = 0; + while (value >= 1024 && i < units.length - 1) { value /= 1024; i++; } + return `${value.toLocaleString(undefined, { maximumFractionDigits: i ? 1 : 0 })} ${units[i]}`; + }, + date(stamp) { return stamp ? new Date(typeof stamp === 'number' ? stamp * 1000 : stamp).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' }) : 'Not run yet'; }, + fileCount(count = 0) { return `${count.toLocaleString()} ${count === 1 ? 'file' : 'files'}`; }, + groups(automatic = null) { return (this.report?.groups || []).filter(g => g.kind !== 'custom' && (automatic === null || g.auto_supported === automatic)); }, + customGroups() { return (this.report?.groups || []).filter(g => g.kind === 'custom'); }, + selectedBytes() { return (this.report?.groups || []).filter(g => this.selected.includes(g.id)).reduce((sum, g) => sum + g.bytes, 0); }, + selectedFiles() { return (this.report?.groups || []).filter(g => this.selected.includes(g.id)).reduce((sum, g) => sum + g.files, 0); }, + disabled() { return this.busy || this.externalBusy; }, + diskPercent() { return this.report?.disk?.total ? Math.round(this.report.disk.used / this.report.disk.total * 100) : 0; }, + applyReport(report) { + if (!report || this.report?.id === report.id || (this.report && report.at < this.report.at)) return; + this.report = report; + this.selected = report.groups.filter(g => g.automatic && g.files && !g.blocked).map(g => g.id); + this.preview = null; + }, + async mount() { + this.mounted = true; const generation = ++this._generation; + try { + await this.refresh(); + if (this.mounted && generation === this._generation && !this.externalBusy && (!this.report || Date.now()/1000-this.report.at > 3600)) await this.scan(); + } catch (error) { this.toast(error.message); } + this.poll(); + }, + unmount() { this.mounted = false; ++this._generation; clearTimeout(this._timer); this._timer = null; }, + poll() { + clearTimeout(this._timer); + if (!this.mounted) return; + this._timer = setTimeout(async () => { + if (!this.busy) { try { await this.refresh(); } catch (error) { console.warn('A0Cleaner status:', error.message); } } + this.poll(); + }, this.externalBusy ? 2000 : 15000); + }, + async refresh() { + const generation = this._generation; + const state = await this.api('status'); + if (generation !== this._generation) return; + this.applyReport(state.report); this.activity = state.activity; this.scheduled = state.scheduled; + this.schedule = state.schedule; this.config = state.config; + this.externalBusy = Boolean(state.status?.operation); + if (!this.busy) this.operation = state.status?.operation || ''; + }, + async perform(label, action) { + if (this.disabled()) return; + this.busy = true; this.operation = label; + try { await action(); } catch (error) { this.toast(error.message); } + finally { this.busy = false; this.operation = ''; } + }, + async scan() { + await this.perform('Scanning', async () => { + const result = await this.api('scan'); this.applyReport(result.report); await this.refresh(); + }); + }, + async review() { + if (!this.selectedFiles()) return; + await this.perform('Preparing cleanup', async () => { + const response = await this.api('preview', { scan_id: this.report.id, groups: [...this.selected] }); + this.preview = response.preview; + }); + }, + async clean() { + const preview = this.preview; + if (!preview) return; + await this.perform('Cleaning', async () => { + const response = await this.api('clean', { scan_id: preview.id, groups: preview.groups.map(g => g.id), confirmed: true }); + this.preview = null; this.applyReport(response.report); await this.refresh(); + this.toast(`${this.bytes(response.result.bytes)} cleaned${response.result.skipped ? ` · ${response.result.skipped} files skipped` : ''}`, 'success'); + }); + }, + async saveConfig(config) { + const response = await this.api('settings', { settings: config }); this.config = response.config; + this.preview = null; this.selected = []; + const scan = await this.api('scan'); this.applyReport(scan.report); + }, + async automaticChanged(value) { + await this.perform('Saving', async () => { await this.saveConfig({ ...this.config, automatic: value }); }); + }, + async automaticAreaChanged(id, enabled) { + await this.perform('Saving', async () => { + const areas = this.config.automatic_areas.filter(area => area !== id); + if (enabled) areas.push(id); + await this.saveConfig({ ...this.config, automatic_areas: areas }); + }); + }, + async setAge(key, raw) { + await this.perform('Saving', async () => { await this.saveConfig({ ...this.config, [key]: Number(raw) }); }); + }, + async addFolder() { + await this.perform('Adding folder', async () => { + await this.saveConfig({ ...this.config, custom_folders: [...this.config.custom_folders, { path: this.folderPath.trim(), days: Number(this.folderDays) }] }); + this.folderPath = ''; + }); + }, + async removeFolder(index) { + await this.perform('Removing folder', async () => { + await this.saveConfig({ ...this.config, custom_folders: this.config.custom_folders.filter((_, i) => i !== index) }); + }); + }, + async changeSchedule(cadence) { + await this.perform('Saving schedule', async () => { this.schedule = (await this.api('schedule', { cadence })).schedule; }); + }, + async openSchedule() { + if (this.schedule?.task?.uuid) { + await schedulerStore.fetchTasks(); + schedulerStore.showTaskDetail(this.schedule.task.uuid); + } + }, + closePreview() { + if (this.busy) return; + this.preview = null; + globalThis.document?.querySelector('.a0c-clean')?.focus(); + }, + trapFocus(event) { + const buttons = [...event.currentTarget.querySelectorAll('button:not(:disabled), summary')]; + if (!buttons.length) return; + const index = buttons.indexOf(globalThis.document.activeElement); + buttons[(index + (event.shiftKey ? -1 : 1) + buttons.length) % buttons.length].focus(); + }, +}; +export const store = createStore('a0Cleaner', model); diff --git a/plugins/_a0_cleaner/webui/cleaner.css b/plugins/_a0_cleaner/webui/cleaner.css new file mode 100644 index 000000000..83240b37f --- /dev/null +++ b/plugins/_a0_cleaner/webui/cleaner.css @@ -0,0 +1,95 @@ +.modal-inner.a0-cleaner-modal { max-width: 940px; } +.a0c { --a0c-accent: #40bff7; --a0c-muted: color-mix(in srgb, var(--color-text) 62%, var(--color-background)); color: var(--color-text); max-width: 900px; margin: auto; padding: 8px 16px 0; } +.a0c * { box-sizing: border-box; } +.a0c button, .a0c select, .a0c input { font: inherit; } +.a0c button { cursor: pointer; } +.a0c button:disabled { opacity: .45; cursor: default; } +.a0c-header, .a0c-brand, .a0c-auto-title, .a0c-auto-controls, .a0c-section-heading, .a0c-footer, .a0c-confirm-actions { display: flex; align-items: center; justify-content: space-between; gap: 16px; } +.a0c-header { margin-bottom: 24px; } +.a0c-brand { justify-content: flex-start; gap: 14px; } +.a0c-brand img { border-radius: 13px; } +.a0c h1 { margin: 0; font-size: 25px; font-weight: 650; letter-spacing: -.7px; line-height: 1.25; } +.a0c-scan { display: inline-flex; align-items: center; gap: 8px; min-width: 120px; justify-content: center; } +.a0c-hero { display: grid; grid-template-columns: 1.2fr 1fr; gap: 30px; align-items: center; padding: 30px; border: 1px solid color-mix(in srgb, var(--a0c-accent) 20%, var(--color-border)); border-radius: 16px; background: radial-gradient(ellipse at top left, #40bff714, transparent 70%); } +.a0c-label { font-size: 11px; font-weight: 600; letter-spacing: 1.5px; color: var(--a0c-muted); } +.a0c-size { margin: 5px 0 7px; font-size: clamp(38px, 5vw, 54px); font-weight: 600; letter-spacing: -2px; line-height: 1.15; font-variant-numeric: tabular-nums; } +.a0c-scan-date, .a0c-disk { color: var(--a0c-muted); font-size: 12px; } +.a0c-disk > div:first-child { display: flex; justify-content: space-between; gap: 8px; } +.a0c-disk strong { color: var(--color-text); font-weight: 500; } +.a0c-meter { height: 7px; border-radius: 12px; background: color-mix(in srgb, var(--color-text) 9%, transparent); overflow: hidden; margin: 12px 0; } +.a0c-meter span { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #2d7ab3, #57c3ee); transition: width .3s ease; } +.a0c-automation { display: grid; grid-template-columns: 1fr auto; align-items: center; gap: 18px; padding: 22px 4px; } +.a0c-auto-title { justify-content: flex-start; gap: 12px; } +.a0c-auto-title > x-icon { color: var(--a0c-accent); font-size: 24px; } +.a0c-auto-title div, .a0c-area-name, .a0c-footer > div, .a0c-activity > div { display: flex; flex-direction: column; gap: 4px; } +.a0c-auto-title strong { font-size: 14px; font-weight: 600; } +.a0c-auto-title span, .a0c-last-run { font-size: 12px; color: var(--a0c-muted); } +.a0c select, .a0c input[type=text], .a0c input[type=number] { border: 1px solid var(--color-border); border-radius: 7px; background: var(--color-background); color: var(--color-text); padding: 8px 10px; min-height: 36px; } +.a0c select { min-width: 110px; } +.a0c-icon-button { display: inline-grid; place-items: center; border: 0; border-radius: 7px; background: transparent; color: var(--a0c-muted); width: 34px; height: 34px; } +.a0c-icon-button:hover { color: var(--color-text); background: #80808015; } +.a0c-switch-row { display: flex; align-items: center; justify-content: space-between; grid-column: 1 / -1; font-size: 13px; padding-top: 4px; } +.a0c-switch-row .toggle { flex: 0 0 auto; } +.a0c-last-run { display: flex; align-items: center; gap: 7px; grid-column: 1 / -1; padding: 10px 12px; border-radius: 8px; background: #8080800c; } +.a0c-last-run x-icon { color: var(--a0c-accent); font-size: 17px; } +.a0c-tabs { display: flex; gap: 26px; border-bottom: 1px solid var(--color-border); } +.a0c-tabs button { border: 0; border-bottom: 2px solid transparent; background: transparent; padding: 12px 0; font-size: 13px; color: var(--a0c-muted); white-space: nowrap; } +.a0c-tabs button.active { color: var(--color-text); border-bottom-color: var(--a0c-accent); } +.a0c-section { padding: 22px 0 2px; } +.a0c h2 { margin: 0; font-size: 14px; font-weight: 600; } +.a0c-section-heading { margin-bottom: 12px; } +.a0c-section-heading > span { font-size: 11px; color: var(--a0c-muted); } +.a0c-area-list { border: 1px solid var(--color-border); border-radius: 11px; overflow: hidden; } +.a0c-area { display: flex; align-items: center; gap: 14px; padding: 15px 16px; min-width: 0; cursor: pointer; border-bottom: 1px solid color-mix(in srgb, var(--color-border) 65%, transparent); transition: background .15s ease; } +.a0c-area:last-child { border-bottom: 0; } +.a0c-area:hover, .a0c-area.selected { background: color-mix(in srgb, var(--a0c-accent) 5%, transparent); } +.a0c-area.unavailable { opacity: .6; } +.a0c input[type=checkbox] { width: 16px; height: 16px; accent-color: var(--a0c-accent); flex-shrink: 0; } +.a0c-area-icon { display: inline-grid; place-items: center; border-radius: 9px; width: 35px; height: 35px; background: #80808012; color: var(--a0c-muted); flex-shrink: 0; } +.a0c-area-icon x-icon { font-size: 21px; } +.a0c-area.selected .a0c-area-icon { color: var(--a0c-accent); background: #40bff710; } +.a0c-area-name { flex: 1; min-width: 0; } +.a0c-area-name strong { font-size: 13px; font-weight: 550; overflow-wrap: anywhere; } +.a0c-area-name span { font-size: 11px; color: var(--a0c-muted); line-height: 1.4; } +.a0c-area-size { font-size: 13px; font-weight: 500; font-variant-numeric: tabular-nums; white-space: nowrap; } +.a0c-rules { margin: 22px 0; color: var(--a0c-muted); font-size: 12px; } +.a0c summary { cursor: pointer; padding: 8px 0; } +.a0c-rule-fields { display: flex; gap: 20px; margin-top: 10px; flex-wrap: wrap; } +.a0c-rule-fields label { display: flex; flex-direction: column; gap: 8px; } +.a0c-rule-fields label > div, .a0c-days { display: flex; align-items: center; gap: 8px; } +.a0c-rule-fields input, .a0c-days input { width: 76px; } +.a0c-folder-form { display: flex; align-items: flex-end; gap: 12px; margin: 18px 0; } +.a0c-folder-form label { display: flex; flex-direction: column; gap: 8px; font-size: 12px; } +.a0c-folder-path { flex: 1; min-width: 100px; } +.a0c-folder-form button { display: flex; align-items: center; gap: 4px; white-space: nowrap; min-height: 36px; } +.a0c-custom-row { display: flex; align-items: center; border: 1px solid var(--color-border); border-radius: 9px; margin-top: 12px; } +.a0c-custom-row .a0c-area { flex: 1; border: 0; } +.a0c-custom-row > button { margin-right: 8px; } +.a0c-empty { display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 44px 16px; color: var(--a0c-muted); font-size: 13px; } +.a0c-empty x-icon { font-size: 32px; opacity: .6; } +.a0c-activity { display: flex; align-items: center; gap: 14px; padding: 18px 2px; border-bottom: 1px solid var(--color-border); } +.a0c-activity strong { font-size: 14px; font-weight: 550; } +.a0c-activity span { font-size: 12px; color: var(--a0c-muted); } +.a0c-footer { position: sticky; bottom: -16px; padding: 18px 0; margin-top: 16px; border-top: 1px solid var(--color-border); background: var(--color-background); z-index: 2; } +.a0c-footer strong { font-size: 20px; font-weight: 600; } +.a0c-footer span { font-size: 11px; color: var(--a0c-muted); } +.a0c-clean { display: flex; align-items: center; gap: 8px; } +.a0c-confirm-backdrop { position: fixed; inset: 0; z-index: 1100; background: #0009; backdrop-filter: blur(5px); display: flex; align-items: center; justify-content: center; padding: 24px; } +.a0c-confirm { width: min(520px, 100%); max-height: 85vh; overflow-y: auto; border: 1px solid var(--color-border); border-radius: 15px; background: var(--color-background); padding: 26px; box-shadow: 0 25px 80px #0005; } +.a0c-confirm h2 { font-size: 21px; } +.a0c-confirm-size { font-size: 38px; font-weight: 600; margin-top: 20px; letter-spacing: -1px; } +.a0c-confirm p { font-size: 13px; color: var(--a0c-muted); margin-bottom: 20px; } +.a0c-impact { display: flex; flex-direction: column; gap: 5px; margin: 15px 0; } +.a0c-impact strong { font-size: 13px; } +.a0c-impact span { font-size: 12px; line-height: 1.5; color: var(--a0c-muted); } +.a0c-confirm details { font-size: 12px; border-top: 1px solid var(--color-border); padding-top: 6px; } +.a0c-confirm ul { max-height: 170px; overflow-y: auto; padding-left: 18px; overflow-wrap: anywhere; } +.a0c-confirm-actions { justify-content: flex-end; margin-top: 22px; } +@media (max-width: 600px) { .a0c { padding: 4px 0 0; } .a0c-header { gap: 8px; } .a0c h1 { font-size: 21px; } .a0c-brand img { width: 42px; height: 42px; } .a0c-scan { min-width: 0; padding: 8px 12px; white-space: nowrap; gap: 6px; } .a0c-scan x-icon { font-size: 20px; } .a0c-clean { padding: 8px 10px; font-size: 13px; white-space: nowrap; gap: 6px; } .a0c-hero { grid-template-columns: 1fr; padding: 22px; gap: 24px; } .a0c-automation { gap: 16px 8px; } .a0c-auto-title span { max-width: 190px; } .a0c-area { gap: 10px; padding: 13px 10px; } .a0c-area-icon { width: 29px; height: 29px; } .a0c-area-name strong { font-size: 12px; } .a0c-tabs { gap: 20px; } .a0c-folder-form { flex-wrap: wrap; } .a0c-folder-path { flex-basis: 100%; } .a0c-footer { bottom: -12px; } .a0c-confirm-backdrop { padding: 12px; } } +@media (prefers-reduced-motion: reduce) { .a0c * { transition: none !important; animation: none !important; } } +.a0c-auto-switch { display: flex; flex-direction: column; align-items: center; gap: 5px; padding-left: 10px; cursor: pointer; } +.a0c-auto-switch span { font-size: 10px; color: var(--a0c-muted); } +.a0c-auto-switch input[type=checkbox] { appearance: none; position: relative; width: 30px; height: 17px; background: #80808040; border-radius: 12px; border: 0; margin: 0; cursor: pointer; } +.a0c-auto-switch input[type=checkbox]::before { content: ''; position: absolute; top: 3px; left: 3px; width: 11px; height: 11px; background: white; border-radius: 50%; transition: transform .15s; } +.a0c-auto-switch input[type=checkbox]:checked { background: #248ab8; } +.a0c-auto-switch input[type=checkbox]:checked::before { transform: translateX(13px); } diff --git a/plugins/_a0_cleaner/webui/config.html b/plugins/_a0_cleaner/webui/config.html new file mode 100644 index 000000000..dbfe997b7 --- /dev/null +++ b/plugins/_a0_cleaner/webui/config.html @@ -0,0 +1,4 @@ +A0Cleaner
+ + +
diff --git a/plugins/_a0_cleaner/webui/main.html b/plugins/_a0_cleaner/webui/main.html new file mode 100644 index 000000000..24e16c054 --- /dev/null +++ b/plugins/_a0_cleaner/webui/main.html @@ -0,0 +1,71 @@ + + + A0Cleaner + + + + +
+
+

A0Cleaner

+ +
+ +
+
READY TO CLEAN
+
Disk space
+
+ +
+
Automatic care
+
+ +
+
+ + + +
+ +
Cleanup ages
+
+ +
+

Custom folders

Manual cleanup only
+
+
No custom folders
+ +
+ +
+

Cleanup history

No cleanups yet
+ +
+ +
+ +
+ +
+
+ + diff --git a/plugins/_a0_cleaner/webui/thumbnail.jpg b/plugins/_a0_cleaner/webui/thumbnail.jpg new file mode 100644 index 000000000..e155d8681 Binary files /dev/null and b/plugins/_a0_cleaner/webui/thumbnail.jpg differ diff --git a/plugins/_a0_cleaner/webui/thumbnail.prompt.txt b/plugins/_a0_cleaner/webui/thumbnail.prompt.txt new file mode 100644 index 000000000..362075ebd --- /dev/null +++ b/plugins/_a0_cleaner/webui/thumbnail.prompt.txt @@ -0,0 +1,7 @@ +Built-in image_gen, with the user-supplied Agent Zero logo as the authoritative reference. + +Use case: stylized-concept +Asset type: premium square 256 x 256 plugin thumbnail for A0Cleaner, a storage cleanup utility for Agent Zero. +Input image 1 is the authoritative Agent Zero logo reference. Preserve this recognizable logo geometry: an open triangular capital-A shape consisting of two straight legs meeting at an apex and a separate short trapezoidal horizontal bar at the bottom inside the triangle. Do not turn it into an ordinary A, do not add a crossbar, do not use a zero ring. +Primary request: reinterpret the supplied exact symbol as a precise polished silver and frosted white three-dimensional emblem, centered on a midnight navy-black background. A single graceful luminous cyan-blue cleaning sweep glides diagonally across its lower right edge, leaving the emblem immaculate, with just two tiny glints. Sophisticated quiet product render, strong simple silhouette, blue light reflected in chrome bevels. The emblem dominates and remains readable at thumbnail size. Keep comfortable margins and a square composition. +Constraints: no text, no letters other than the actual supplied symbolic logo, no watermark, no busy particles, no additional frame, no rounded app tile. diff --git a/plugins/_a0_connector/AGENTS.md b/plugins/_a0_connector/AGENTS.md index fbdf209a9..a224bad13 100644 --- a/plugins/_a0_connector/AGENTS.md +++ b/plugins/_a0_connector/AGENTS.md @@ -18,6 +18,7 @@ - `tools/text_editor_remote.py` logs `type="text_editor"` through a `get_log_object()` override so the WebUI routes its messages through the `_text_editor` plugin's `get_message_handler` JS extension; keep remote edits visually consistent with local edits. - Remote text editing reuses the shipped `_text_editor` patch and log helpers. Disabling local editor discovery does not remove these Python modules; removing the bundled dependency is unsupported. - Preserve session-auth and `auth.handlers` activation assumptions. +- `helpers/remote_tree.py` resolves instance-wide host map limits from current default-workdir settings unless `remote_tree_inherit` is false. Hello and tree acknowledgements include additive `remote_tree_config` (four non-negative integers; zero unlimited). Updated connectors honor explicit host overrides first and refresh on the existing tree keepalive. Older clients ignore the field. Agent Zero's Working directory settings owns this prompt-map configuration; it is separate from Launcher host access controls. - `v1/chats_list` keeps the normal list response unchanged. An optional string `query` (at most 200 characters) returns read-only `matches` over those loaded contexts, using the bundled `_sidebar_folders.helpers.search` pure helper independently of its UI activation/config. Return only IDs, title flags and bounded literal text parts; blank queries do not scan. Preserve the existing protected route's authentication. CLI search scope/order stays with its original candidate list. - Keep remote tool prompts synchronized with remote tool behavior and disclose them only from connected CLI metadata: no connected CLI hides all remote tool @@ -30,7 +31,9 @@ access, timeout, transfer, and disconnect handling; ordinary model args cannot enable `allow_running`. There is no `runtime=input` or `code` input alias. - `input_remote` requires both its own policy permission and the bundled - `plugin:_a0_connector:code_execution_remote` terminal action. Shared policy resolution + `plugin:_a0_connector:code_execution_remote` terminal action. Both are enabled + by the default policy without an Agent Editor grant. Custom restrictions remain + authoritative. Shared policy resolution applies the dependency to prompts, native schemas, and execution; the input wrapper rechecks that exact capability before rewriting args or dispatching, including when a profile shadows the execution tool name. @@ -115,7 +118,7 @@ ## Verification - Run connector-specific tests or smoke-test HTTP and `/ws` integration when changing runtime behavior. -- Run `tests/test_remote_input_policy.py` for remote-input authorization, zero dispatch on denial, prompt/schema gating, and preserved host access controls. +- Run `tests/test_remote_input_policy.py` for default access without editor grants, remote-input authorization, zero dispatch on denial, prompt/schema gating, and preserved host access controls. - Run `python -m pytest tests/test_a0_connector_chat_search.py plugins/_sidebar_folders/tests/test_search.py -q` for the query branch, unchanged list shape, input validation and shared excerpt behavior. - Cross-platform first-call session startup and no-retry boundaries are covered in the sibling connector's `tests/test_plugin_backend.py`; Core prompt gating remains covered by `tests/test_a0_connector_prompt_gating.py`. - Launcher gateway regression coverage lives in diff --git a/plugins/_a0_connector/README.md b/plugins/_a0_connector/README.md index 586591159..e9f3856e7 100644 --- a/plugins/_a0_connector/README.md +++ b/plugins/_a0_connector/README.md @@ -1,4 +1,12 @@ -# Connector composer controls +# A0 Connector + +## Host workspace maps + +In **Settings → Agent → Working directory → Host workspace**, **Use container settings** makes connected host maps follow the default workdir's depth, file, folder, and line limits. It is enabled by default. Disable it for separate host limits; zero means unlimited. Paths, ignore rules, project settings, and access permissions are unchanged. + +Updated TUI, headless, ACP, and Launcher gateway connectors receive `remote_tree_config` in the existing hello and tree acknowledgements. Saved changes normally apply within a minute without restarting Launcher. Explicit `AGENT_ZERO_REMOTE_TREE_*` settings on the host take precedence. Older connectors need an update to use these controls; older Core remains compatible with updated connectors. + +## Connector composer controls Agent Zero advertises `composer_controls` when the generic composer-control API is available. Compatible connectors render controls supplied by enabled plugins beside the provider/model bar. No optional plugin names or domain rules belong in the connector. diff --git a/plugins/_a0_connector/api/ws_connector.py b/plugins/_a0_connector/api/ws_connector.py index 7ab4b0182..0491c9e38 100644 --- a/plugins/_a0_connector/api/ws_connector.py +++ b/plugins/_a0_connector/api/ws_connector.py @@ -11,6 +11,7 @@ from helpers.ws_limits import A0_WS_MAX_PAYLOAD_BYTES from helpers.ws_manager import WsPayloadTooLargeError, WsResult from plugins._a0_connector.helpers.exec_config import build_exec_config +from plugins._a0_connector.helpers.remote_tree import build_remote_tree_config from plugins._a0_connector.helpers.event_bridge import ( get_context_log_entries, get_context_log_entry_count, @@ -228,6 +229,7 @@ class WsConnector(WsHandler): "transfer_protocol": TRANSFER_PROTOCOL_VERSION, }, "exec_config": build_exec_config(), + "remote_tree_config": build_remote_tree_config(), "remote_tools": self._remote_tool_state(sid), } @@ -952,6 +954,7 @@ class WsConnector(WsHandler): "sid": sid, "tree_hash": tree_hash, "updated_at": snapshot.updated_at, + "remote_tree_config": build_remote_tree_config(), } def _handle_exec_op_result( diff --git a/plugins/_a0_connector/helpers/remote_tree.py b/plugins/_a0_connector/helpers/remote_tree.py new file mode 100644 index 000000000..419f2f926 --- /dev/null +++ b/plugins/_a0_connector/helpers/remote_tree.py @@ -0,0 +1,13 @@ +"""Instance-owned limits for connected host workspace trees.""" + + +def build_remote_tree_config() -> dict[str, int]: + from helpers import settings + + config = settings.get_settings() + prefix = "workdir" if config.get("remote_tree_inherit", True) else "remote_tree" + limits = {} + for key, default in (("max_depth", 5), ("max_files", 20), ("max_folders", 20), ("max_lines", 250)): + value = config.get(f"{prefix}_{key}", default) + limits[key] = value if type(value) is int and value >= 0 else default + return limits diff --git a/plugins/_a0_connector/prompts/agent.system.tool.input_remote.md b/plugins/_a0_connector/prompts/agent.system.tool.input_remote.md index 8cc33ed76..eca93396d 100644 --- a/plugins/_a0_connector/prompts/agent.system.tool.input_remote.md +++ b/plugins/_a0_connector/prompts/agent.system.tool.input_remote.md @@ -1,7 +1,7 @@ ### input_remote send keyboard input to an interactive program on the connected CLI host args: `keyboard`, optional `session` (default `0`) -requires permission for `input_remote` and the `terminal` action of `code_execution_remote`; keyboard input can run shell commands +enabled by default; explicit tool policies must allow `input_remote` and the `terminal` action of `code_execution_remote`, because keyboard input can run shell commands uses the same connection and Read&Write gates as `code_execution_remote` for Agent Zero's own terminal, use `input`; for host browser actions, use `browser` usage: diff --git a/plugins/_a0_connector/skills/host-code-execution/SKILL.md b/plugins/_a0_connector/skills/host-code-execution/SKILL.md index 19cd20c08..021a4e3b4 100644 --- a/plugins/_a0_connector/skills/host-code-execution/SKILL.md +++ b/plugins/_a0_connector/skills/host-code-execution/SKILL.md @@ -16,7 +16,7 @@ Browser boundary: do not use shell launchers such as `xdg-open`, `sensible-brows ## Access Modes - Remote execution can be disabled locally in the CLI. If the tool returns a disabled/no-client error, explain the required CLI toggle instead of falling back to the server runtime. -- `input_remote` requires its own tool permission and the `terminal` action of `code_execution_remote`. Keyboard input can execute shell commands; allowing only output or other remote runtimes does not permit this tool. +- `input_remote` and remote terminal execution are enabled by default in Agent Editor; no editor change is needed with the default policy. Custom policies must permit both `input_remote` and the `terminal` action of `code_execution_remote`. Keyboard input can execute shell commands, so a terminal block also blocks input. - Read&Write local file access allows mutating runtimes such as `terminal`, `python`, and `nodejs`. - Read only local file access blocks mutating runtimes. `runtime=output` and `runtime=reset` remain available for existing sessions. diff --git a/plugins/_a2a_chat/AGENTS.md b/plugins/_a2a_chat/AGENTS.md index 3c6378a95..b69393cc7 100644 --- a/plugins/_a2a_chat/AGENTS.md +++ b/plugins/_a2a_chat/AGENTS.md @@ -29,6 +29,7 @@ ## Verification - Import the tool in the framework runtime and run the a2a tool contract tests after changes. +- `tests/test_a2a_chat_tool.py` exercises discovery, message send, and conversation reuse through the real server auth/router with token URLs, project URLs, explicit header credentials, and public peers. ## Child DOX Index diff --git a/plugins/_a2a_chat/README.md b/plugins/_a2a_chat/README.md index 7852c635c..d2067b20f 100644 --- a/plugins/_a2a_chat/README.md +++ b/plugins/_a2a_chat/README.md @@ -1,3 +1,5 @@ # A2A Chat Provides the `a2a_chat` tool, which communicates with remote FastA2A-compatible agents. Conversation context is preserved automatically per `agent_url`; pass `reset: true` to start a fresh conversation with the same agent. + +Unauthenticated agents work without extra configuration. To connect to a protected Agent Zero peer, use its token-bearing connection URL from **Settings → A2A → Connection URL**. Credentials are never copied automatically from the ambient `A2A_TOKEN` environment variable to a model-selected destination. diff --git a/plugins/_a2a_chat/helpers/fasta2a_client.py b/plugins/_a2a_chat/helpers/fasta2a_client.py index 2a8752b55..4c1e3e802 100644 --- a/plugins/_a2a_chat/helpers/fasta2a_client.py +++ b/plugins/_a2a_chat/helpers/fasta2a_client.py @@ -32,10 +32,7 @@ class AgentConnection: self.agent_url = agent_url.rstrip('/') self.timeout = timeout - # Auth headers - if token is None: - import os - token = os.getenv("A2A_TOKEN") + # Only send credentials explicitly supplied for this connection. headers = {} if token: headers["Authorization"] = f"Bearer {token}" diff --git a/plugins/_a2a_chat/helpers/fasta2a_client.py.dox.md b/plugins/_a2a_chat/helpers/fasta2a_client.py.dox.md index 8c55961ff..3c7f435ef 100644 --- a/plugins/_a2a_chat/helpers/fasta2a_client.py.dox.md +++ b/plugins/_a2a_chat/helpers/fasta2a_client.py.dox.md @@ -27,6 +27,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. - Observed side-effect areas: filesystem writes, network calls, WebSocket state, settings/state persistence, secret handling, scheduler state. +- Connections send authentication headers only when a caller explicitly supplies `token`; the ambient `A2A_TOKEN` environment variable is never attached automatically to a model-selected URL. Agent Zero peers can instead use the token-bearing `/a2a/t-` connection URL already provided in Settings. - Imported dependency areas include: `helpers.print_style`, `typing`, `uuid`. ## Key Concepts diff --git a/plugins/_code_execution/AGENTS.md b/plugins/_code_execution/AGENTS.md index a71f52764..caf9f3177 100644 --- a/plugins/_code_execution/AGENTS.md +++ b/plugins/_code_execution/AGENTS.md @@ -17,8 +17,10 @@ - `extensions/webui/get_process_step_types/code-exe-types.js` registers `code_exe` as a process-step type so raw-log grouping matches the plugin's message renderer. - Keep command previews compact in rendered execution output. `code-exe-handler.js` restores a matching command prefix from the already-masked `kvps.code` for Copy Output and step details, preserving command whitespace and the output body. Existing log size limits remain; copying cannot recover text already discarded by those limits. +- Normalize logged `code` to display text before title and copy operations. Rejected malformed arguments can remain in stored logs; streaming and replay must render them without changing the original arguments. - Keep session concurrency, timeout, streaming, and reset behavior predictable. +- Execution runtimes (`terminal`, `python`, `nodejs`) require a string `code` argument. Reject missing or non-string code with `RepairableException` before configuring or resetting shells; output polling and reset do not require code. Verify with `tests/test_code_execution_arguments.py`. - A direct parallel code job retains its worker and loop-bound shell until the command ends or is cancelled. Output timeouts publish model-facing progress to the registered job and continue polling; callers use parallel job IDs. Close parallel shells explicitly on that worker loop on completion or cancellation, including partially connected shells. Top-level sessions retain their ordinary timeout/output/reset behavior. - Execute multi-line terminal input as one current-shell compound so intermediate prompts cannot mark queued work complete; preserve `cd`, exports, and other shell state. - Treat local process exit and SSH channel termination as definitive command completion even when no final prompt is emitted; recreate terminated sessions before their next command. diff --git a/plugins/_code_execution/extensions/webui/get_message_handler/code-exe-handler.js b/plugins/_code_execution/extensions/webui/get_message_handler/code-exe-handler.js index 63ed3c41f..496fa1571 100644 --- a/plugins/_code_execution/extensions/webui/get_message_handler/code-exe-handler.js +++ b/plugins/_code_execution/extensions/webui/get_message_handler/code-exe-handler.js @@ -26,11 +26,12 @@ function drawMessageCodeExe({ agentno = 0, ...additional }) { + const commandText = String(kvps?.code ?? ""); let title = "Code Execution"; // show command at the start and end - if (kvps?.code && /done_all|code_execution_tool/.test(heading || "")) { + if (commandText && /done_all|code_execution_tool/.test(heading || "")) { const s = kvps.session; - title = `${s != null ? `[${s}] ` : ""}${kvps.runtime || "bash"}> ${kvps.code.trim()}`; + title = `${s != null ? `[${s}] ` : ""}${kvps.runtime || "bash"}> ${commandText.trim()}`; } else { // during execution show the original heading (current step) title = cleanStepTitle(heading); @@ -46,7 +47,6 @@ function drawMessageCodeExe({ }, ].filter(Boolean); - const commandText = String(kvps?.code ?? ""); let outputText = String(content ?? ""); // Expand only the command preview for copying; keep the rendered log compact. const commandLine = outputText.match(/^(bash>|PS>|python> |node> )([^\n]+)\n\n/); diff --git a/plugins/_code_execution/prompts/agent.system.tool.code_exe.md b/plugins/_code_execution/prompts/agent.system.tool.code_exe.md index 51115fd43..4188480c7 100644 --- a/plugins/_code_execution/prompts/agent.system.tool.code_exe.md +++ b/plugins/_code_execution/prompts/agent.system.tool.code_exe.md @@ -3,7 +3,7 @@ run terminal, python, or nodejs commands args: - `runtime`: `terminal`, `python`, `nodejs`, or `output` - `destination`: execution target from EXTRAS; default `default` -- `code`: command or script code +- `code`: command or script code as a single string, required for `terminal`, `python`, and `nodejs` - `session`: terminal session id; default `0` - `reset`: kill a session before running; `true` or `false` rules: diff --git a/plugins/_code_execution/tools/code_execution_tool.py b/plugins/_code_execution/tools/code_execution_tool.py index a990a66eb..a6a5a9a2c 100644 --- a/plugins/_code_execution/tools/code_execution_tool.py +++ b/plugins/_code_execution/tools/code_execution_tool.py @@ -8,6 +8,7 @@ import time from typing import Any from helpers.tool import Tool, Response, coerce_bool +from helpers.errors import RepairableException from helpers import files, rfc_exchange, projects, runtime, secrets, settings from helpers.print_style import PrintStyle from helpers.strings import truncate_text as truncate_text_string @@ -74,6 +75,11 @@ class CodeExecution(Tool): await self.agent.handle_intervention() # wait for intervention and handle it, if paused runtime_arg = str(self.args.get("runtime", "")).lower().strip() + if runtime_arg in {"terminal", "python", "nodejs"} and not isinstance(self.args.get("code"), str): + received = type(self.args["code"]).__name__ if "code" in self.args else "missing" + raise RepairableException( + f"code_execution_tool requires code to be a string for runtime {runtime_arg}; received {received}" + ) session = int(self.args.get("session", 0)) self.allow_running = coerce_bool(self.args.get("allow_running", False), False) reset = coerce_bool(self.args.get("reset", False), False) or runtime_arg == "reset" diff --git a/plugins/_oauth/AGENTS.md b/plugins/_oauth/AGENTS.md index 5b4ec68ab..0c1554903 100644 --- a/plugins/_oauth/AGENTS.md +++ b/plugins/_oauth/AGENTS.md @@ -17,6 +17,7 @@ - `helpers/routes.py` owns local OAuth callback and OpenAI-compatible proxy routes mounted by the route bootstrap extension. - `webui/config.html` and `webui/oauth-config-store.js` own the OAuth Connections settings UI. - `extensions/python/_functions/models/get_api_key/end/` owns the dummy API-key extension used by OAuth model providers. +- `extensions/python/_functions/models/_merge_provider_defaults/end/` supplies internal proxy credentials after model-slot and provider defaults are merged, including legacy inline keys. - `tests/test_oauth_*.py` and `tests/test_oauth_reconnect.mjs` own provider contract, security, UI, and compatibility regressions. ## Local Contracts @@ -38,7 +39,7 @@ - `helpers/providers/registry.py` is the source of truth for connectable OAuth providers. - The models API must preserve the legacy plain `models` slug list and may add `model_metadata` entries for richer provider catalogs. - Codex metadata recommends `gpt-6.1-terra` for Main and `gpt-6-luna` for Utility during onboarding. An explicit configured model list keeps its own ordering; these recommendations do not replace or restrict the live account catalog. -- OAuth provider config must not expose the dummy `oauth` API key in `conf/model_providers.yaml`; the dummy key is a runtime-only shim supplied by the `get_api_key` extension after the account provider reports connected. +- OAuth provider config must not expose the dummy `oauth` API key in `conf/model_providers.yaml`; `get_api_key` supplies a runtime credential after the account provider reports connected. OAuth model calls to this process's loopback WebUI port and provider proxy path receive the internal credential after defaults are merged, replacing legacy keys and auth headers only in runtime kwargs. Saved settings and explicit credentials for other endpoints stay intact. - Usage-plan metadata belongs only to connectable providers. Do not add metadata-only subscription families for providers this plugin cannot connect. - API handlers should remain provider-aware. Missing or blank `provider_id` defaults to Codex only for existing backward compatibility; falsey non-string IDs must not silently default. - Codex success contracts must preserve legacy fields such as `account_id` while allowing newer fields such as `account_label`. @@ -46,7 +47,8 @@ - Token files are password-equivalent credentials. Store them under plugin-owned `usr/plugins/_oauth//auth.json` paths with private permissions, and do not share rotating refresh-token files with external CLIs. - Stored upstream base URLs and OAuth token endpoints must be validated against provider-owned allowlists before sending bearer or refresh tokens. - Browser callback providers must support manual callback paste when the browser cannot reach the local callback route. -- Local proxy routes must remain loopback or token protected and must not add broad CORS access. +- Local proxy routes require the process-generated internal credential supplied automatically to Agent Zero model calls or an explicitly configured proxy token, regardless of source address. Loopback alone is never sufficient authorization, and routes must not add broad CORS access. +- Keep the internal proxy credential in the stable framework runtime module so bundled-plugin reloads preserve existing model clients; restarting the process generates a new credential automatically. - Codex Responses proxy requests must include Codex client metadata and compatibility headers such as `client_metadata`, `x-codex-installation-id`, `originator`, `session-id`, and `thread-id`, and must forward `input` as a list for upstream Codex compatibility. - `chat_model_call_before/_20_codex_session.py` gives Codex main-model turns stable per-chat, per-agent session/thread IDs for cache routing. Preserve explicit caller session/thread IDs through both proxy routes, including Chat Completions conversion, while keeping installation/window metadata plugin-owned. - Default `prompt_cache_key` to a caller-supplied session ID (hash IDs longer than 64 characters); preserve explicit keys and do not derive keys from randomly generated fallback metadata. Codex provider defaults use local Responses state because its backend requires `store: false`. @@ -78,6 +80,8 @@ ## Verification - Run `pytest tests/test_oauth_*.py` after backend provider, route, token, or UI contract changes. +- Proxy security tests must isolate extension discovery and provider state; passing must not depend on a saved account connection or plugin toggles in `usr/`. +- `tests/test_oauth_vps_compatibility.py` covers forwarded/public-host requests, installed-SDK HTTP streaming for all account providers, and existing clients across bundled-plugin reloads. - Run `node tests/test_oauth_reconnect.mjs` after changing reconnect, pending-auth controls, or cancellation. - Run `pytest tests/test_plugin_scan_prompt.py` after plugin structure, extension, or docs changes. - Run onboarding or model-config tests when provider metadata, `api_key_mode`, or model-provider config changes. diff --git a/plugins/_oauth/README.md b/plugins/_oauth/README.md index 73308115b..5fab382b4 100644 --- a/plugins/_oauth/README.md +++ b/plugins/_oauth/README.md @@ -10,6 +10,10 @@ Each model slot has its own provider selector. The selector lists connected OAut OAuth-backed model providers do not require users to enter API keys. Agent Zero supplies a local dummy key only at runtime after the selected account provider is connected, so unconnected providers stay blank in API-key surfaces. +Existing account connections and model settings continue to work without signing in again or entering a new key. Local model calls authenticate automatically, including when older settings contain a placeholder API key. External clients must use the proxy token configured in OAuth Connections. + +On a VPS, browser access through a reverse proxy or tunnel keeps the same OAuth connection and model setup. Agent Zero authenticates its server-side model calls automatically. The proxy routes do not trust loopback addresses because public requests forwarded by a local reverse proxy can also arrive from loopback. External clients that previously relied on tokenless loopback access must supply the configured proxy token. + ## Providers ### Codex/ChatGPT (`codex_oauth`) diff --git a/plugins/_oauth/default_config.yaml b/plugins/_oauth/default_config.yaml index 5064192b6..8c72ad75c 100644 --- a/plugins/_oauth/default_config.yaml +++ b/plugins/_oauth/default_config.yaml @@ -31,7 +31,8 @@ codex: text_verbosity: "medium" # The OpenAI-compatible wrapper is mounted at /oauth/codex/v1. - # It is loopback-only by default and does not emit CORS headers. + # Agent Zero authenticates its internal calls automatically; external clients must supply a token. + # The legacy require_proxy_token setting is retained for saved-config compatibility; loopback is never sufficient authorization. proxy_base_path: "/oauth/codex" callback_path: "/auth/callback" require_proxy_token: false diff --git a/plugins/_oauth/extensions/python/_functions/models/_merge_provider_defaults/end/_20_oauth_proxy_key.py b/plugins/_oauth/extensions/python/_functions/models/_merge_provider_defaults/end/_20_oauth_proxy_key.py new file mode 100644 index 000000000..91576d0cb --- /dev/null +++ b/plugins/_oauth/extensions/python/_functions/models/_merge_provider_defaults/end/_20_oauth_proxy_key.py @@ -0,0 +1,32 @@ +from urllib.parse import urlsplit + +from helpers import runtime +from helpers.extension import Extension +from plugins._oauth.helpers.providers import DUMMY_API_KEY, get_provider, oauth_provider_ids + + +class OAuthProxyKey(Extension): + def execute(self, data: dict, **kwargs): + args = data.get("args", ()) + provider_id = args[1] if len(args) > 1 else data.get("kwargs", {}).get("original_provider", "") + if provider_id not in oauth_provider_ids(): + return + result = data.get("result") + if not isinstance(result, tuple): + return + + _, call_kwargs = result + base = urlsplit(call_kwargs.get("api_base") or "") + proxy_path = get_provider(provider_id).metadata().proxy_base_path + if ( + base.scheme in {"http", "https"} + and base.hostname in {"127.0.0.1", "localhost", "::1"} + and (base.port or (443 if base.scheme == "https" else 80)) == runtime.get_web_ui_port() + and base.path.rstrip("/") == f"{proxy_path}/v1" + ): + call_kwargs["api_key"] = DUMMY_API_KEY + if isinstance(call_kwargs.get("extra_headers"), dict): + call_kwargs["extra_headers"] = { + key: value for key, value in call_kwargs["extra_headers"].items() + if key.lower() not in {"authorization", "x-api-key"} + } diff --git a/plugins/_oauth/extensions/python/_functions/models/get_api_key/end/_20_oauth_account_dummy_key.py b/plugins/_oauth/extensions/python/_functions/models/get_api_key/end/_20_oauth_account_dummy_key.py index 35680303a..c42b37e44 100644 --- a/plugins/_oauth/extensions/python/_functions/models/get_api_key/end/_20_oauth_account_dummy_key.py +++ b/plugins/_oauth/extensions/python/_functions/models/get_api_key/end/_20_oauth_account_dummy_key.py @@ -21,8 +21,9 @@ class OAuthAccountDummyKey(Extension): if service.lower() not in oauth_provider_ids(): return - result = str(data.get("result") or "").strip() - if (not result or result == "None") and oauth_provider_is_connected(service): + if oauth_provider_is_connected(service): + # Account-backed models authenticate to the local proxy with its + # process credential, regardless of legacy stored API-key values. data["result"] = DUMMY_API_KEY diff --git a/plugins/_oauth/helpers/providers/base.py b/plugins/_oauth/helpers/providers/base.py index 622d340ef..84cef9422 100644 --- a/plugins/_oauth/helpers/providers/base.py +++ b/plugins/_oauth/helpers/providers/base.py @@ -2,18 +2,22 @@ from __future__ import annotations import json import os +import secrets import tempfile import importlib from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Any, Protocol +from helpers import runtime + CODEX_PROVIDER_ID = "codex_oauth" GITHUB_COPILOT_PROVIDER_ID = "github_copilot_oauth" GEMINI_API_PROVIDER_ID = "gemini_api_oauth" XAI_GROK_PROVIDER_ID = "xai_grok_oauth" -DUMMY_API_KEY = "oauth" +# Keep existing clients authorized when plugin modules are purged during a reload. +DUMMY_API_KEY = vars(runtime).setdefault("_oauth_proxy_key", secrets.token_urlsafe(32)) class ProviderError(Exception): diff --git a/plugins/_oauth/helpers/routes.py b/plugins/_oauth/helpers/routes.py index 7313d82f9..cfae25eba 100644 --- a/plugins/_oauth/helpers/routes.py +++ b/plugins/_oauth/helpers/routes.py @@ -597,14 +597,14 @@ def _proxy_denied_response() -> Response | None: def _proxy_authorized() -> bool: - cfg = codex_config() - token = cfg["proxy_token"] + from plugins._oauth.helpers.providers import DUMMY_API_KEY + supplied = _supplied_proxy_token() - if token and supplied == token: - return True - if cfg["require_proxy_token"]: - return False - return _remote_is_loopback(request.remote_addr) + configured_token = codex_config()["proxy_token"] + return bool( + supplied + and supplied in {DUMMY_API_KEY, configured_token} + ) def _supplied_proxy_token() -> str: @@ -634,13 +634,6 @@ def _host_is_local(host: str) -> bool: return False -def _remote_is_loopback(addr: str | None) -> bool: - try: - return ipaddress.ip_address(addr or "").is_loopback - except ValueError: - return False - - def _json_error(message: str, *, status: int = 400, code: str = "invalid_request") -> Response: return jsonify({"error": {"message": message, "type": code, "code": code}}), status diff --git a/plugins/_oauth/webui/config.html b/plugins/_oauth/webui/config.html index a060d7b5c..5273fb855 100644 --- a/plugins/_oauth/webui/config.html +++ b/plugins/_oauth/webui/config.html @@ -369,13 +369,10 @@ Codex version - diff --git a/plugins/_scheduler/AGENTS.md b/plugins/_scheduler/AGENTS.md index 3631a6ef3..e53612396 100644 --- a/plugins/_scheduler/AGENTS.md +++ b/plugins/_scheduler/AGENTS.md @@ -24,11 +24,14 @@ ## Local Contracts - The tool and API endpoints delegate to the shared `helpers.task_scheduler` engine, which stays in core and is also used by `api/scheduler_tick.py`, `helpers/job_loop.py`, chat lifecycle endpoints, and `_chat_naming`. +- Recurring tasks catch up once after missed schedules on the next engine tick. Changes to cron/timezone or re-enabling a disabled task start a new schedule from that moment; ordinary edits preserve an overdue run. Keep timing in the engine and preserve its serialized `schedule_anchor` during full-task round trips. - The plugin declares `always_enabled: true`: the core scheduling engine keeps running tasks it created even when plugin code is absent, so the plugin must not be disableable into a state where tasks run without any way to manage them. - Plugin API routes resolve as `/api/plugins/_scheduler/` via the standard plugin API resolution in `helpers/api.py`. - Core snapshot and chat-selection consumers import the always-enabled plugin's tasks store directly, ensuring it exists before the first snapshot even when the sidebar has not mounted. - Timezone aliases (local/user/default/current/current_timezone) resolve via `helpers.localization`; cron validation rejects malformed expressions before task creation. - `wait_for_task` polls task state until completion, failure, or idempotent runs. +- Plugin-owned tasks carry `plugin_name` and run through the engine's deterministic hook. Their schedule, name and state remain editable; the editor hides model prompts/attachments and detail shows the operation. The engine rejects changing those inapplicable inputs and creates no chat for these tasks. +- Close task detail by its modal path and await closure before opening its editor, so asynchronous close hooks cannot remove the new modal from the stack. ## Work Guidance diff --git a/plugins/_scheduler/README.md b/plugins/_scheduler/README.md index 831078fbf..928a972b8 100644 --- a/plugins/_scheduler/README.md +++ b/plugins/_scheduler/README.md @@ -3,3 +3,9 @@ Provides the `scheduler` agent tool for managing saved tasks and schedules: listing, finding by name, showing, running, updating, deleting, and creating scheduled, ad-hoc, and planned tasks. The Scheduled Tasks modal, welcome card, sidebar navigation entry and tasks list, and scheduler CRUD API endpoints live in this plugin; the shared `TaskScheduler` scheduling engine stays in core (used by the job loop, tick API, chat lifecycle, and other plugins). + +If Agent Zero is offline when a recurring task is due, the task runs once on the next scheduler tick after startup. Several missed occurrences produce one run, followed by the normal schedule. The same behavior covers delayed ticks and applies to both agent tasks and plugin maintenance. The scheduler ticks at startup and then every minute. + +Disabled tasks stay disabled. Changing the cron/timezone or re-enabling a task starts its schedule from that moment; renaming it or editing its prompt preserves a pending run. Manual runs, cancellation and completion consume intervening occurrences, so they are not immediately replayed. Errored tasks and tasks interrupted while running require explicit recovery. + +Saved recurring tasks include `schedule_anchor`. Older task files derive it from their saved creation, update and last-run timestamps. When changing a schedule directly in a task file, set its anchor to the time the new schedule takes effect. Existing overdue tasks can run once when upgrading. diff --git a/plugins/_scheduler/webui/scheduler/scheduler-store.js b/plugins/_scheduler/webui/scheduler/scheduler-store.js index f4c6d9653..dab8c668b 100644 --- a/plugins/_scheduler/webui/scheduler/scheduler-store.js +++ b/plugins/_scheduler/webui/scheduler/scheduler-store.js @@ -742,7 +742,7 @@ const schedulerStoreModel = { this.tasks = this.tasks.filter((task) => task.uuid !== taskId); this.hasNoTasks = this.tasks.length === 0; if (this.selectedTaskForDetail?.uuid === taskId) { - this.closeTaskDetail(); + await this.closeTaskDetail(); } } catch (error) { this.notifyError(`Failed to delete task: ${error.message}`); @@ -1008,13 +1008,13 @@ const schedulerStoreModel = { closeTaskDetail() { this.selectedTaskForDetail = null; - window.closeModal(); + return closeModal("/plugins/_scheduler/webui/scheduler/scheduler-task-detail.html"); }, async editFromDetail() { const taskId = this.selectedTaskForDetail?.uuid; if (!taskId) return; - this.closeTaskDetail(); + await this.closeTaskDetail(); await this.startEditTask(taskId); // Open main scheduler modal to show the editor window.openModal("/plugins/_scheduler/webui/scheduler/scheduler-modal.html"); diff --git a/plugins/_scheduler/webui/scheduler/scheduler-task-detail.html b/plugins/_scheduler/webui/scheduler/scheduler-task-detail.html index 4fb0a531b..6d2f659c9 100644 --- a/plugins/_scheduler/webui/scheduler/scheduler-task-detail.html +++ b/plugins/_scheduler/webui/scheduler/scheduler-task-detail.html @@ -113,11 +113,12 @@
-
System Prompt:
+
System Prompt:
-
User Prompt:
+
diff --git a/plugins/_scheduler/webui/scheduler/scheduler-task-editor.html b/plugins/_scheduler/webui/scheduler/scheduler-task-editor.html index 23e952a86..ff8485ad9 100644 --- a/plugins/_scheduler/webui/scheduler/scheduler-task-editor.html +++ b/plugins/_scheduler/webui/scheduler/scheduler-task-editor.html @@ -159,7 +159,7 @@ -
+
@@ -175,7 +175,7 @@ aria-label="System Prompt" placeholder="System instructions for the AI">
-
+
@@ -191,7 +191,7 @@ aria-label="User Prompt" placeholder="User message for the AI">
-
+
Container file paths or URLs, one per line
@@ -366,7 +366,7 @@
-
+
@@ -382,7 +382,7 @@ aria-label="System Prompt" placeholder="System instructions for the AI">
-
+
@@ -398,7 +398,7 @@ aria-label="User Prompt" placeholder="User message for the AI">
-
+
Container file paths or URLs, one per line
diff --git a/plugins/_telegram_integration/AGENTS.md b/plugins/_telegram_integration/AGENTS.md index 7fd8ba6a3..2c5d97c15 100644 --- a/plugins/_telegram_integration/AGENTS.md +++ b/plugins/_telegram_integration/AGENTS.md @@ -7,20 +7,21 @@ ## Ownership - `helpers/bot_manager.py` owns bot lifecycle. +- `helpers/scopes.py` owns configured-scope discovery, unique bot identities, activation, current authorization, session access, and secret-free context snapshots. +- `helpers/migration.py` snapshots existing configuration, activation, and session mappings privately before the first lifecycle pass, then upgrades missing/invalid legacy webhook secrets. Original settings and valid secrets remain unchanged; partial upgrades retry without replacing the original backup. - `helpers/handler.py` and `helpers/telegram_client.py` own message routing, replies, and Telegram API interaction. - `helpers/slash_commands.py` adapts the shared Commands resolver and effects to Telegram replies, menus, session bindings, exports, and compaction confirmation. - `helpers/settings_ui.py` owns Telegram plugin toggles and tool-permission menus, delegating writes to the existing plugin and Agent Editor owners. -- `hooks.py` normalizes saved/read bot configurations, supplies stable names for unnamed bots, and rejects duplicate names on save. -- `helpers/sandbox.py` owns thin request/event adapters; `sandbox/` owns aiogram, polling, webhook parsing and file transport in a persistent guest. +- `hooks.py` normalizes configurations, supplies stable names, and rejects unsafe/duplicate names, reused Telegram bot identities, and routing outside the owning project on save. +- `helpers/sandbox.py` owns request and event adapters. The persistent guest under `sandbox/` owns aiogram, polling, webhook parsing, and file transport. - `api/`, `prompts/`, `extensions/`, `default_config.yaml`, `plugin.yaml`, `README.md`, and `webui/` own tests/webhook endpoints, prompt fragments, hooks, settings, metadata, docs, and UI. - `webui/config.html` is the sole plugin WebUI, including bot setup and connection checks. +- `docs/guides/telegram.md` in the repository root owns the user setup walkthrough; keep its UI labels, scope examples, access guidance, and migration claims aligned with this plugin. ## Local Contracts -- New worker environments reuse the sandbox image Python; existing worker environments remain intact. - - Treat bot tokens, chat IDs, attachments, and user data as sensitive. -- Clean the complete generated attachment filename with `helpers.security.safe_filename` before joining `usr/uploads`; use the same cleaner for bot cleanup prefixes. No sender filename may select a subdirectory. +- Clean the entire generated attachment filename with `helpers.security.safe_filename` before joining `usr/uploads`. Use the same cleaner for bot cleanup prefixes. - Keep allowed-user, group-mode, project, model, and `/send` controls enforced. - Resolve raw commands before adding the Telegram message envelope; its closing marker prevents queued/rendered text from being interpreted as a second postfix command. Custom/project definitions override bundled commands; keep Telegram's existing integration aliases and pickers for unoverridden commands. - `/commands` discovers the current chat's effective commands on each use. The native Telegram menu registers global commands at startup, maps hyphens to underscores, and obeys Telegram's name/description/count limits. @@ -30,9 +31,13 @@ - `/new` creates and binds a fresh context without resetting the previous chat. `/clear` retains Telegram's existing reset behavior. Compaction confirms the current idle context and uses the existing backup-producing compactor. - Restart bots when their token, delivery mode, group mode, webhook URL, or webhook secret changes. Polling may start on the next job-loop tick after saving settings. - Webhook dispatch requires an active webhook and a matching nonempty secret header. Setup requires a random 32–256 character secret using letters, digits, `_` or `-`; polling and webhook removal revoke HTTP delivery. -- Provision the guest on connection test or configured bot enablement/job-loop startup, never unconditional boot. Guest restart generations recreate registered bots; disabling stops workers without deleting configuration. Keep SDK errors sanitized and request secrets out of logs. Polling tasks and webhook deliveries retain current authorization checks in the outer control layer. -- Bot configuration and activation are global; project/profile scopes are unsupported and backend writes must reject them. Project binding routes chats, not bot settings. -- Legacy scoped configs or activation overrides pause all bots and block each incoming event until reviewed and removed. Preserve those files for manual migration and notify the operator. Every event requires a currently enabled global bot; never fall back to captured settings after removal or disablement. +- Provision the guest on connection test or when an enabled bot needs it. Recreate registered bots after a guest restart. Stop the worker when the last bot stops. Keep SDK errors sanitized and request secrets out of logs. +- Support global, project, profile, and combined configurations and activation using framework precedence. Each explicitly saved configuration owns separate Telegram bots; inherited configuration does not create another connection. Reusing a Telegram bot ID (including a rotated token) across configurations is rejected on save and pauses all conflicting connections on read, preserving files for review. +- Global runtime keys remain bot names. Scoped keys include a stable scope digest; state mappings, webhooks, attachments, and replies use those keys. Project/profile-owned bots stay inside their owning scope; new contexts start in that project/profile. Global bots retain default-project and per-user routing. +- Preserve existing names, including spaces and Unicode, so global session keys do not change on upgrade. Reject path separators/control characters and pause runtime-key collisions. Never infer administrators, merge allowlists, drop scoped overrides, or silently choose between duplicate bot tokens during migration. +- Every event resolves the current owning and destination configuration, activation, allowlist, and group policy before dispatch. Never fall back to captured settings after removal, disablement, or connection rotation. Scope selection commands and callbacks validate the destination before changing it. Outbound replies, streams, and heartbeats recheck authorization too. +- Session lists and selection enforce bot/user/chat ownership and destination access. Only explicitly configured administrators may attach an unbound WebUI session; another Telegram user's session is never selectable. Context config snapshots exclude tokens and webhook secrets. +- The core `_11_scoped_telegram` job-loop bridge runs the manager when the global plugin is disabled, so explicitly enabled scoped bots can start and revoked connections can stop. - Agent profile picker actions change the top-level chat profile and must preserve existing subordinate agent profiles. Picker rows and direct matches use the shared presentation catalog while current status may still report an @@ -47,7 +52,8 @@ ## Verification - Smoke-test connection checks, polling or webhook delivery, per-user context reuse, attachments, and replies when practical. -- Run `tests/test_telegram_config_scope.py` for scope rejection, legacy-settings shutdown, current authorization and disable/removal handling. +- Run `tests/test_telegram_config_scope.py` for all scopes, duplicate-token shutdown, inherited activation, current authorization, revocation, and session isolation. +- Run `tests/test_telegram_migration.py` for exact configuration/state preservation, private backups, webhook-secret upgrades, symlink preservation, and retry after interrupted or failed writes. - Run `python -m pytest -q tests/test_telegram_commands.py tests/test_telegram_webhook_security.py` for command routing, menu bounds, configuration normalization, bot lifecycle, and administrator-only policy persistence and revocation regressions. ## Child DOX Index diff --git a/plugins/_telegram_integration/README.md b/plugins/_telegram_integration/README.md index b1a801bfd..b524009fa 100644 --- a/plugins/_telegram_integration/README.md +++ b/plugins/_telegram_integration/README.md @@ -2,6 +2,10 @@ Communicate with Agent Zero via Telegram. Supports polling and webhook modes with per-user chat sessions, group mentions, inline keyboards, and file exchange. +**Setting up your first bot?** Follow the [Telegram setup guide](../../docs/guides/telegram.md) +for a screenshot-led walkthrough, private access, project/profile scopes, and +upgrade troubleshooting. This reference describes the plugin's capabilities and implementation. + ## What It Does This plugin connects one or more Telegram bots to Agent Zero. Each bot runs independently with its own token, mode (polling or webhook), access control list, and project binding. Users message the bot on Telegram, and Agent Zero processes the conversation just like a WebUI chat — including tool use, sub-agents, and file attachments. @@ -9,19 +13,19 @@ This plugin connects one or more Telegram bots to Agent Zero. Each bot runs inde ## Main Behavior - **Dependency management** - - Keeps `aiogram` in the plugin-local `requirements.txt` instead of the global root requirements. - - Active code paths call `helpers/dependencies.py::ensure_dependencies()` to install `aiogram` into the framework runtime on first use via `uv pip install --python -r plugins/_telegram_integration/requirements.txt`. + - A persistent plugin sandbox runs the Telegram SDK and starts on connection tests or when an enabled bot needs to connect. - **Bot lifecycle** - Managed by a `job_loop` extension that starts, restarts, or stops bots whenever plugin settings change. - - Supports both long-polling and webhook delivery modes. Webhook mode requires a random secret of 32–256 letters, digits, underscores or hyphens; generate one with `python -c 'import secrets; print(secrets.token_urlsafe(32))'`. Existing webhook configurations without a valid secret must be updated before starting the bot. + - Supports both long-polling and webhook delivery modes. Webhook mode requires a random secret of 32–256 letters, digits, underscores or hyphens; generate one with `python -c 'import secrets; print(secrets.token_urlsafe(32))'`. The upgrade migration supplies a secure secret for legacy webhook configurations that lack one. - The webhook endpoint rejects polling bots and requires a matching `X-Telegram-Bot-Api-Secret-Token` header before dispatch. - - Bot names are generated automatically if left empty. Each bot needs a unique name; saving a new token or webhook connection restarts that bot on the next maintenance tick (up to about a minute). + - Bot names are generated automatically if left empty. Existing names, including spaces and Unicode, are retained. Names must be unique within their configuration, fit within 128 characters, and exclude path separators and control characters. Saving a new token or webhook connection restarts that bot on the next maintenance tick (up to about a minute); events from the old connection are rejected immediately. - **Per-user chat sessions** - Each Telegram user gets a dedicated `AgentContext`, persisted across restarts via a JSON state file. - `/start` creates a context; `/new` starts fresh; `/clear` resets the current context. - `/commands` shows the shared integration command menu (`/help` is an alias). - `/commands` also provides a paginated menu of Agent Zero's built-in, enabled-plugin, global, and active-project commands. Custom commands use the same templates, scripts, and scope precedence as the WebUI, including prefix and postfix syntax. - `/stop`, `/goal`, and `/rename` execute their existing Agent Zero commands. `/compact` offers confirmation before summarizing, preserving the existing conversation backup. `/copy` sends the transcript as a text file; `/attach` explains Telegram's native attachment control. + - Session selection is limited to that Telegram bot, user, and chat, within an allowed project/profile. Explicit bot administrators can also attach an unbound WebUI chat in an allowed scope. Another Telegram user's chats remain inaccessible. - `/models` and `/presets` open the model preset picker; `/chats` opens the session picker, and `/chat ` switches sessions. `/browser` offers runtime buttons. - For users listed separately as bot administrators, `/plugins` provides paginated instance-wide plugin toggles and `/permissions` edits the current profile's tool permissions, including Allow/Block/Default per tool, separate Tools/MCP defaults, and inherited policy. An empty administrator list disables these settings changes from Telegram. Always-required tools and the Telegram connection remain protected. Computer Use permissions stay with A0 Launcher/CLI. - Telegram's native command menu includes global commands at bot startup. Hyphenated commands also accept an underscore spelling, such as `/computer_use`; use `/commands` for freshly added or project-specific commands. @@ -39,7 +43,6 @@ This plugin connects one or more Telegram bots to Agent Zero. Each bot runs inde - **Message handling** - Extracts text, captions, locations, contacts, stickers, and attachment indicators. - Downloads photos, documents, audio, voice, and video into `usr/uploads/` with configurable auto-cleanup. - - Cleans attachment filenames with the shared upload-name sanitizer so sender-supplied paths cannot escape the upload directory. - **Reply delivery** - Streams tool progress and response text through real Telegram messages updated with `editMessageText`. - Tool progress and the AI response are separate messages; only the AI response replies to the user message. @@ -60,6 +63,7 @@ This plugin connects one or more Telegram bots to Agent Zero. Each bot runs inde - **Access control** - Per-bot allow-list by Telegram user ID or @username. Empty list = open to all. - A separate `admin_users` list grants access to plugin and tool-permission settings. Administrators must also pass `allowed_users`; an omitted or empty administrator list grants nobody settings access. Each message and callback uses the current bot configuration, so removing an administrator also revokes existing menu buttons. + - Replies, streamed progress, and heartbeats also check current access. New context snapshots omit bot tokens and webhook secrets. - **Project binding** - Map individual Telegram users to specific Agent Zero projects; supports a default-project fallback. - Inherits model overrides from sibling contexts in the same project. @@ -94,13 +98,21 @@ This plugin connects one or more Telegram bots to Agent Zero. Each bot runs inde ## Configuration Scope -- **Settings section**: `external` -- **Per-project config**: `false` -- **Per-agent config**: `false` +All four scopes are supported: global, project, agent profile, and project plus profile. A bot configured in a project starts conversations there and cannot switch out of that project. A profile-scoped bot starts with that profile and cannot switch to another profile. A combined scope enforces both. Global bots retain default-project and per-user project routing. -Bot settings, allowed users, administrators, and activation apply globally. Use each bot's default project and user project mapping to route conversations. +Each explicitly saved configuration needs its own Telegram bot token. Create another bot with **@BotFather**, copy the desired settings, and replace the token before saving in another scope. Telegram bot accounts are not cloned by copying their tokens. To move an existing bot instead, remove its token from the old configuration before saving it in the new scope; previous chats are retained, while the new scope starts its own session bindings. -If an older version saved project- or profile-specific settings or activation overrides, Telegram delivery pauses until those copies are reviewed and removed. In Telegram settings, use **Show existing configurations** and, when shown, **Review saved activation overrides** to inspect them. Reopen Telegram settings and apply the intended access rules globally before deleting scoped copies. Existing files are preserved and are never merged automatically. Removing or disabling a global bot, or disabling the plugin globally, blocks new updates immediately, before the next lifecycle tick. +Where no scoped configuration exists, normal configuration inheritance applies without starting another bot. Scoped activation overrides still apply to inherited bots: disabling Telegram in a destination project/profile blocks events there. An explicitly enabled scoped bot can run while global activation is disabled. Configurations replace the inherited bot list rather than merging lists. + +Existing scoped settings no longer pause every bot just because they exist. If multiple saved configurations contain the same Telegram bot identity, all conflicting connections remain paused until those tokens are separated or moved. This also detects old and rotated tokens for the same bot. Unreadable settings pause delivery rather than falling back to permissive rules. Use **Show existing configurations** to review saved copies; files are never deleted automatically. + +## Upgrading Existing Installations + +Before starting bots for the first time after this upgrade, Agent Zero saves an exact snapshot of existing Telegram configuration files, activation overrides, and session mappings in `usr/plugins/_telegram_integration/backups/config-scopes-v1/`. The manifest records each original path and checksum. The directory is private (`0700`) and backup files are private (`0600`), since configurations contain credentials. + +Existing tokens, bot names, allowlists, administrator lists, project mappings, instructions, and other settings are retained. Existing global bots keep their chat bindings. The only automatic configuration edit supplies a random secret for an old webhook configuration with a missing or invalid secret; valid secrets remain unchanged. The migration preserves symlinks and can resume after an interrupted write without rotating an already upgraded secret or replacing the original backup. It never grants administrator access or merges conflicting access rules. + +No manual migration command is required. Token conflicts stay preserved for review through the settings UI, as described above. ## Plugin Metadata diff --git a/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py b/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py index e8e7a387e..b462bfdfe 100644 --- a/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py +++ b/plugins/_telegram_integration/extensions/python/job_loop/_10_telegram_bot.py @@ -5,36 +5,33 @@ from helpers.extension import Extension from helpers.errors import format_error from helpers.print_style import PrintStyle from helpers.notification import NotificationManager, NotificationPriority, NotificationType -from helpers import plugins - - -PLUGIN_NAME: str = "_telegram_integration" +from plugins._telegram_integration.helpers.sandbox import worker +from plugins._telegram_integration.helpers import scopes class TelegramBotManager(Extension): async def execute(self, **kwargs: Any) -> None: - if _has_scoped_settings(): - config = {} + try: + from plugins._telegram_integration.helpers.migration import prepare_upgrade + prepare_upgrade() + configured, conflicts = scopes.available_bots() + except Exception: + configured, conflicts = {}, ["Unreadable Telegram configuration"] + if conflicts: NotificationManager.send_notification( type=NotificationType.ERROR, priority=NotificationPriority.HIGH, title="Telegram settings need review", message=( - "Telegram delivery is paused because project or agent-profile settings exist. " - "Review those settings and activation overrides, apply the intended access rules " - "in global Telegram settings, then remove the scoped copies." + "Conflicting or unreadable Telegram settings were found. Each configured scope " + "needs a separate bot token from @BotFather. Affected bots are paused; " + "existing settings are retained. Review the saved configurations and the " + "upgrade backup under usr/plugins/_telegram_integration/backups/config-scopes-v1." ), - id="telegram-unsupported-scopes", + id="telegram-scope-conflicts", ) - elif plugins.get_toggle_state(PLUGIN_NAME) == "enabled": - config = plugins.get_plugin_config(PLUGIN_NAME) or {} - else: - config = {} - bots_cfg = config.get("bots", []) - enabled_names = { - b["name"] for b in bots_cfg if b.get("enabled") and b.get("name") and b.get("token") - } + enabled_names = set(configured) from plugins._telegram_integration.helpers.bot_manager import ( get_all_bots, @@ -53,8 +50,8 @@ class TelegramBotManager(Extension): cleanup_old_attachments, ) - if bots_cfg: - cleanup_old_attachments() + if configured: + cleanup_old_attachments({key: bot.config for key, bot in configured.items()}) running = get_all_bots() @@ -64,10 +61,8 @@ class TelegramBotManager(Extension): await stop_bot(name) # Start new bots - for bot_cfg in bots_cfg: - name = bot_cfg.get("name", "") - if not name or not bot_cfg.get("enabled") or not bot_cfg.get("token"): - continue + for name, scoped_bot in configured.items(): + bot_cfg = scoped_bot.config if name in running: inst = running[name] current_mode = bot_cfg.get("mode", "polling") @@ -82,8 +77,9 @@ class TelegramBotManager(Extension): ) if current_mode == running_mode and current_group_mode == inst.group_mode and same_connection: # Same mode and still alive → skip - from plugins._telegram_integration.helpers.sandbox import worker - if worker.ready and inst.generation == worker.generation and ((inst.task and not inst.task.done()) or inst.webhook_active): + if worker.ready and inst.generation == worker.generation and ( + (inst.task and not inst.task.done()) or inst.webhook_active + ): continue # Mode changed or instance died — stop and recreate await stop_bot(name) @@ -130,34 +126,73 @@ class TelegramBotManager(Extension): f"Telegram ({name}): failed to start: {format_error(e)}" ) -# Wrapper functions for aiogram handlers +# Authorization for events forwarded by the Telegram worker -def _has_scoped_settings() -> bool: - return any( - entry.get("project_name") or entry.get("agent_profile") - for pattern in (plugins.CONFIG_FILE_NAME, plugins.TOGGLE_FILE_PATTERN) - for entry in plugins.find_plugin_assets( - pattern, plugin_name=PLUGIN_NAME, - project_name="*", agent_profile="*", only_first=False, - ) - ) - - -def _get_current_bot_cfg(bot_name: str) -> dict: - """Fetch the latest bot config by name, so handlers always use fresh settings.""" - if _has_scoped_settings() or plugins.get_toggle_state(PLUGIN_NAME) != "enabled": +def _get_current_bot_cfg(bot_name: str, event, captured: dict) -> dict: + from plugins._telegram_integration.helpers import handler + bots, _ = scopes.available_bots() + bot = bots.get(bot_name) + if not bot: return {} - config = plugins.get_plugin_config(PLUGIN_NAME) or {} - for b in config.get("bots", []): - if b.get("name") == bot_name and b.get("enabled"): - return b - return {} + mode = bot.config.get("mode", "polling") + if bot.config["token"] != captured.get("token") or mode != captured.get("mode", "polling"): + return {} + if mode == "webhook" and ( + bot.config.get("webhook_url", "").rstrip("/") != captured.get("webhook_url", "").rstrip("/") + or bot.config.get("webhook_secret", "") != captured.get("webhook_secret", "") + ): + return {} + user = event.from_user + message = getattr(event, "message", None) or event + if not user or not getattr(message, "chat", None): + return {} + context = handler.get_bound_context(bot_name, user.id, message.chat.id) + if context: + project = handler.projects.get_context_project_name(context) or "" + profile = context.config.profile + else: + project, profile = scopes.initial_scope(bot, user.id) + config = scopes.resolve(bot, project, profile) + if not config or not handler._is_allowed(config, user.id, user.username): + return {} + if config.get("group_mode") == "off" and message.chat.type != "private": + return {} + return {**config, "_initial_scope": (project, profile)} def _make_handler(handler_fn): """Create a wrapper that resolves fresh bot config on every call.""" async def _wrapped(event, bot_name: str, bot_cfg: dict): - current = _get_current_bot_cfg(bot_name) + try: + current = _get_current_bot_cfg(bot_name, event, bot_cfg) + except Exception: + PrintStyle.error("Telegram: could not resolve current access rules; update rejected") + return if current: + message = getattr(event, "message", None) or event + # A live policy change can narrow the guest's filter before it restarts. + if ( + current.get("group_mode", "mention") == "mention" + and bot_cfg.get("group_mode", "mention") == "all" + and message.chat.type != "private" + and getattr(handler_fn, "__name__", "") == "handle_message" + and not (message.text or message.caption or "").startswith("/") + and not _mentions_bot(message, bot_name) + ): + return await handler_fn(event, bot_name, current) return _wrapped + + +def _mentions_bot(message, bot_name: str) -> bool: + from plugins._telegram_integration.helpers.bot_manager import get_bot + + instance = get_bot(bot_name) + info = instance.bot_info if instance else None + if not info: + return False + reply = message.reply_to_message + if reply and reply.from_user and reply.from_user.id == info.id: + return True + text = message.text or message.caption or "" + return bool(info.username and f"@{info.username.lower()}" in text.lower()) diff --git a/plugins/_telegram_integration/helpers/bot_manager.py b/plugins/_telegram_integration/helpers/bot_manager.py index dba03a993..28ec7094f 100644 --- a/plugins/_telegram_integration/helpers/bot_manager.py +++ b/plugins/_telegram_integration/helpers/bot_manager.py @@ -2,6 +2,7 @@ import asyncio import re from dataclasses import dataclass, field from typing import Callable, Awaitable +from urllib.parse import urlencode from plugins._telegram_integration.helpers.sandbox import Bot, TelegramEvent, worker, decode, rpc from helpers import integration_commands @@ -136,7 +137,7 @@ async def setup_webhook(instance: BotInstance, webhook_url: str, secret: str = " if not isinstance(secret, str) or not re.fullmatch(r"[A-Za-z0-9_-]{32,256}", secret): raise ValueError("webhook_secret must contain 32–256 letters, digits, underscores or hyphens") - full_url = f"{webhook_url.rstrip('/')}/api/plugins/_telegram_integration/webhook?bot={instance.name}" + full_url = f"{webhook_url.rstrip('/')}/api/plugins/_telegram_integration/webhook?{urlencode({'bot': instance.name})}" await instance.bot.set_webhook( url=full_url, diff --git a/plugins/_telegram_integration/helpers/command_ui.py b/plugins/_telegram_integration/helpers/command_ui.py index 48b7e367e..4a3b2e330 100644 --- a/plugins/_telegram_integration/helpers/command_ui.py +++ b/plugins/_telegram_integration/helpers/command_ui.py @@ -10,6 +10,7 @@ from helpers.persist_chat import save_tmp_chat from helpers.state_monitor_integration import mark_dirty_for_context from plugins._model_config.helpers import model_config from plugins._telegram_integration.helpers import telegram_client as tc +from plugins._telegram_integration.helpers import scopes from plugins._telegram_integration.helpers.constants import ( CTX_TG_STREAM_ENABLED, CTX_TG_TOOLS_ENABLED, @@ -351,7 +352,7 @@ def _session_view( *, selected: bool = False, ) -> tuple[str, dict | None]: - items = _session_items() + items = _session_items(context) current_label = _session_label(context) status = f"Current session: {_html(current_label)}" if context.is_running(): @@ -403,12 +404,15 @@ async def _select_model(context: AgentContext, index: int, *, clear: bool = Fals async def _select_project(context: AgentContext, index: int, *, clear: bool = False) -> None: if clear: + scopes.require_scope(context, "", context.config.profile) projects.deactivate_project(context.id) return items = [item for item in projects.get_active_projects_list() or [] if item.get("name")] if index < 0 or index >= len(items): return - projects.activate_project(context.id, str(items[index]["name"])) + project = str(items[index]["name"]) + scopes.require_scope(context, project, context.config.profile) + projects.activate_project(context.id, project) async def _select_agent(context: AgentContext, index: int) -> None: @@ -420,6 +424,7 @@ async def _select_agent(context: AgentContext, index: int) -> None: if index < 0 or index >= len(items): return profile = str(items[index]["key"]) + scopes.require_scope(context, projects.get_context_project_name(context) or "", profile) config = initialize_agent(override_settings={"agent_profile": profile}) context.config = config context.agent0.config = config @@ -430,11 +435,11 @@ async def _select_agent(context: AgentContext, index: int) -> None: async def _select_session(context: AgentContext, index: int) -> AgentContext | None: if context.is_running(): return None - items = _session_items() + items = _session_items(context) if index < 0 or index >= len(items): return None target = items[index].context - if target.is_running(): + if target.is_running() or not scopes.can_select_session(context, target): return None _copy_telegram_binding(context, target) @@ -445,7 +450,7 @@ async def _select_session(context: AgentContext, index: int) -> AgentContext | N return target -def _session_items() -> list[SessionItem]: +def _session_items(context) -> list[SessionItem]: contexts = sorted( AgentContext.all(), key=lambda item: str(item.output().get("last_message") or ""), @@ -459,6 +464,7 @@ def _session_items() -> list[SessionItem]: running=item.is_running(), ) for item in contexts + if scopes.can_select_session(context, item) ] diff --git a/plugins/_telegram_integration/helpers/draft_stream.py b/plugins/_telegram_integration/helpers/draft_stream.py index 22390fdff..1e2806547 100644 --- a/plugins/_telegram_integration/helpers/draft_stream.py +++ b/plugins/_telegram_integration/helpers/draft_stream.py @@ -6,9 +6,8 @@ import time from agent import AgentContext from helpers.print_style import PrintStyle from plugins._telegram_integration.helpers import telegram_client as tc -from plugins._telegram_integration.helpers.bot_manager import get_bot +from plugins._telegram_integration.helpers import scopes from plugins._telegram_integration.helpers.constants import ( - CTX_TG_BOT, CTX_TG_CHAT_ID, CTX_TG_PROGRESS_LINES, CTX_TG_PROGRESS_MESSAGE_ID, @@ -278,8 +277,7 @@ def _mark_tool_failed(context: AgentContext, tool_name: str) -> None: def _bot_instance(context: AgentContext): - bot_name = context.data.get(CTX_TG_BOT) - return get_bot(bot_name) if bot_name else None + return scopes.authorized_bot(context) def _reply_to(context: AgentContext) -> int | None: diff --git a/plugins/_telegram_integration/helpers/handler.py b/plugins/_telegram_integration/helpers/handler.py index 9f09ac7b9..5d116162a 100644 --- a/plugins/_telegram_integration/helpers/handler.py +++ b/plugins/_telegram_integration/helpers/handler.py @@ -8,7 +8,7 @@ from contextlib import asynccontextmanager, suppress from plugins._telegram_integration.helpers.sandbox import Bot, TelegramEvent as TgMessage, TelegramEvent as CallbackQuery from agent import AgentContext, UserMessage -from helpers import plugins, files, projects +from helpers import files, projects, subagents from helpers import message_queue as mq from helpers.notification import NotificationManager, NotificationType, NotificationPriority from helpers.persist_chat import save_tmp_chat @@ -20,13 +20,12 @@ from initialize import initialize_agent from plugins._telegram_integration.helpers import telegram_client as tc from plugins._telegram_integration.helpers import command_ui from plugins._telegram_integration.helpers import slash_commands +from plugins._telegram_integration.helpers import scopes from plugins._telegram_integration.helpers.bot_manager import get_bot from plugins._telegram_integration.helpers.constants import ( - PLUGIN_NAME, DOWNLOAD_FOLDER, STATE_FILE, CTX_TG_BOT, - CTX_TG_BOT_CFG, CTX_TG_CHAT_ID, CTX_TG_CHAT_TYPE, CTX_TG_USER_ID, @@ -62,16 +61,13 @@ def _map_key(bot_name: str, user_id: int, chat_id: int) -> str: return f"{bot_name}:{user_id}:{chat_id}" -def cleanup_old_attachments(): +def cleanup_old_attachments(bots_cfg: dict): """Remove downloaded attachment files older than per-bot max age. 0 = keep forever.""" - config = plugins.get_plugin_config(PLUGIN_NAME) or {} - bots_cfg = config.get("bots") or [] total_removed = 0 upload_dir = files.get_abs_path(DOWNLOAD_FOLDER) if not os.path.isdir(upload_dir): return - for bot_cfg in bots_cfg: - bot_name = bot_cfg.get("name", "") + for bot_name, bot_cfg in bots_cfg.items(): if not bot_name: continue max_age_hours = bot_cfg.get("attachment_max_age_hours", 0) @@ -129,7 +125,7 @@ def _get_project(bot_cfg: dict, user_id: int) -> str: project = bot_cfg.get("default_project", "") return project -# Message handlers (registered with aiogram by bot_manager) +# Message handlers for events forwarded by the Telegram worker async def handle_start(message: TgMessage, bot_name: str, bot_cfg: dict): """Handle /start command.""" @@ -193,6 +189,8 @@ async def handle_message(message: TgMessage, bot_name: str, bot_cfg: dict): ) if text is None: return + if not scopes.context_config(context): + return # Use temp bot for downloads (cross-event-loop safe) async with _temp_bot(instance.bot.token) as dl_bot: @@ -306,12 +304,16 @@ async def handle_callback_query(query: CallbackQuery, bot_name: str, bot_cfg: di text = _normalize_bot_command(text, instance) if text is None: return + text = await slash_commands.handle(context, instance.bot.token, query.message.chat.id, query.message.message_id, text, is_admin=_is_admin(bot_cfg, user.id, user.username)) if text is None: return + if not scopes.context_config(context): + return + agent = context.agent0 user_msg = agent.read_prompt( "fw.telegram.user_message.md", @@ -358,6 +360,15 @@ async def handle_new_members(message: TgMessage, bot_name: str, bot_cfg: dict): # Context management +def get_bound_context(bot_name: str, user_id: int, chat_id: int): + ctx_id = _load_state().get("chats", {}).get(_map_key(bot_name, user_id, chat_id)) + context = AgentContext.get(ctx_id) if ctx_id else None + if context and all(context.data.get(key) == value for key, value in ( + (CTX_TG_BOT, bot_name), (CTX_TG_USER_ID, user_id), (CTX_TG_CHAT_ID, chat_id), + )): + return context + return None + async def _get_or_create_context( bot_name: str, bot_cfg: dict, @@ -384,35 +395,37 @@ async def _get_or_create_context_from_user( with _chat_map_lock: state = _load_state() chats = state.setdefault("chats", {}) - ctx_id = chats.get(key) - # Check if existing context is still alive - if ctx_id: - ctx = AgentContext.get(ctx_id) - if ctx: - ctx.data[CTX_TG_CHAT_TYPE] = chat_type or ctx.data.get(CTX_TG_CHAT_TYPE, "") - ctx.data[CTX_TG_BOT_CFG] = bot_cfg - return ctx - # Context was garbage collected, remove stale mapping - chats.pop(key, None) + ctx = get_bound_context(bot_name, user_id, chat_id) + if ctx: + ctx.data[CTX_TG_CHAT_TYPE] = chat_type or ctx.data.get(CTX_TG_CHAT_TYPE, "") + ctx.data[CTX_TG_USERNAME] = username or "" + scopes.remember_config(ctx, bot_cfg) + return ctx + chats.pop(key, None) # Create new context try: - config = initialize_agent() + project, profile = bot_cfg.get("_initial_scope", (_get_project(bot_cfg, user_id), "")) + if profile and profile not in subagents.get_available_agents_dict(project or None): + raise ValueError("The configured Telegram agent profile is unavailable in its project.") + config = initialize_agent(override_settings={"agent_profile": profile}) if profile else initialize_agent() display_name = f"@{username}" if username else str(user_id) ctx = AgentContext(config, name=f"Telegram: {display_name}") ctx.data[CTX_TG_BOT] = bot_name - ctx.data[CTX_TG_BOT_CFG] = bot_cfg + scopes.remember_config(ctx, bot_cfg) ctx.data[CTX_TG_CHAT_ID] = chat_id ctx.data[CTX_TG_CHAT_TYPE] = chat_type ctx.data[CTX_TG_USER_ID] = user_id ctx.data[CTX_TG_USERNAME] = username or "" - project = _get_project(bot_cfg, user_id) if project: projects.activate_project(ctx.id, project) + if not scopes.context_config(ctx): + return None + # Inherit model override from an existing context in the same project _inherit_model_override(ctx) @@ -528,9 +541,9 @@ async def send_telegram_reply( if not bot_name: return "No Telegram bot configured on context" - instance = get_bot(bot_name) + instance = scopes.authorized_bot(context) if not instance: - return f"Bot '{bot_name}' not running" + return "Telegram delivery is disabled or no longer authorized for this chat" chat_id = context.data.get(CTX_TG_CHAT_ID) if not chat_id: diff --git a/plugins/_telegram_integration/helpers/heartbeat.py b/plugins/_telegram_integration/helpers/heartbeat.py index 188127e41..8564c8e50 100644 --- a/plugins/_telegram_integration/helpers/heartbeat.py +++ b/plugins/_telegram_integration/helpers/heartbeat.py @@ -8,9 +8,8 @@ from contextlib import suppress from agent import AgentContext from helpers.print_style import PrintStyle from plugins._telegram_integration.helpers import telegram_client as tc -from plugins._telegram_integration.helpers.bot_manager import get_bot +from plugins._telegram_integration.helpers import scopes from plugins._telegram_integration.helpers.constants import ( - CTX_TG_BOT, CTX_TG_CHAT_ID, CTX_TG_HEARTBEAT_STOP, CTX_TG_HEARTBEAT_TASK, @@ -63,9 +62,8 @@ async def _heartbeat_loop( async def _send_heartbeat(context: AgentContext, elapsed_seconds: float) -> bool: - bot_name = context.data.get(CTX_TG_BOT) chat_id = context.data.get(CTX_TG_CHAT_ID) - bot = get_bot(bot_name) if bot_name else None + bot = scopes.authorized_bot(context) if not bot or not chat_id: return False diff --git a/plugins/_telegram_integration/helpers/migration.py b/plugins/_telegram_integration/helpers/migration.py new file mode 100644 index 000000000..3728fb1d1 --- /dev/null +++ b/plugins/_telegram_integration/helpers/migration.py @@ -0,0 +1,72 @@ +"""Preserve pre-scope Telegram settings before the new lifecycle reads them.""" +import hashlib +import json +import os +from pathlib import Path +import re +import secrets +import tempfile + +from helpers import files, plugins +from plugins._telegram_integration.helpers.constants import PLUGIN_NAME, STATE_FILE + +BACKUP_DIR = "usr/plugins/_telegram_integration/backups/config-scopes-v1" + + +def prepare_upgrade() -> None: + """Back up old settings and upgrade legacy webhook secrets without resetting bots.""" + root = Path(files.get_abs_path(BACKUP_DIR)) + manifest = root / "manifest.json" + completed = root / "complete.json" + if completed.is_file(): + return + sources = {entry["path"] for pattern in (plugins.CONFIG_FILE_NAME, plugins.TOGGLE_FILE_PATTERN) + for entry in plugins.find_plugin_assets(pattern, plugin_name=PLUGIN_NAME)} + state = files.get_abs_path(STATE_FILE) + if Path(state).is_file(): + sources.add(state) + if not sources: + return + root.mkdir(parents=True, exist_ok=True, mode=0o700) + root.chmod(0o700) + if not manifest.is_file(): + entries = [] + for source in sorted(sources): + path = Path(source) + data = path.read_bytes() + relative = files.deabsolute_path(str(path)) + digest = hashlib.sha256(data).hexdigest() + filename = hashlib.sha256(relative.encode()).hexdigest() + ".backup" + _write_private(root / filename, data) + entries.append({"path": relative, "backup": filename, "sha256": digest}) + _write_private(manifest, json.dumps({"version": 1, "files": entries}, indent=2).encode()) + backed_up = {entry["path"] for entry in json.loads(manifest.read_text())["files"]} + for source in sorted(sources): + path = Path(source) + if path.name != plugins.CONFIG_FILE_NAME or files.deabsolute_path(source) not in backed_up: + continue + config = json.loads(path.read_bytes()) + changed = False + for bot in config.get("bots", []): + secret = bot.get("webhook_secret", "") + if bot.get("mode") == "webhook" and (not isinstance(secret, str) or not re.fullmatch(r"[A-Za-z0-9_-]{32,256}", secret)): + bot["webhook_secret"] = secrets.token_urlsafe(32) + changed = True + if changed: + # Resolve a symlink so upgrading its contents preserves the user's link. + _write_private(path.resolve(), json.dumps(config, indent=2).encode()) + # Partial migrations retry without rotating a secret that was already upgraded. + _write_private(completed, b'{"version": 1}\n') + + +def _write_private(path: Path, data: bytes) -> None: + fd, temp = tempfile.mkstemp(dir=path.parent, prefix=".upgrade-") + try: + with os.fdopen(fd, "wb") as handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temp, path) + finally: + if os.path.exists(temp): + os.unlink(temp) diff --git a/plugins/_telegram_integration/helpers/scopes.py b/plugins/_telegram_integration/helpers/scopes.py new file mode 100644 index 000000000..f5aa73046 --- /dev/null +++ b/plugins/_telegram_integration/helpers/scopes.py @@ -0,0 +1,146 @@ +"""Resolve Telegram connection ownership and current scoped access rules.""" +from dataclasses import dataclass +from hashlib import sha256 +import json +import re +from pathlib import Path + +from helpers import plugins, projects, settings +from plugins._telegram_integration.helpers.constants import ( + PLUGIN_NAME, CTX_TG_BOT, CTX_TG_BOT_CFG, CTX_TG_CHAT_ID, + CTX_TG_CHAT_TYPE, CTX_TG_USER_ID, CTX_TG_USERNAME, +) + + +@dataclass(frozen=True) +class BotConfig: + project: str + profile: str + config: dict + + @property + def key(self) -> str: + name = self.config["name"] + if not self.project and not self.profile: + return name + scope = json.dumps([self.project, self.profile]).encode() + return f"{name}@{sha256(scope).hexdigest()[:24]}" + + +def configured_bots() -> list[BotConfig]: + scopes = [("", "")] + for entry in plugins.find_plugin_assets(plugins.CONFIG_FILE_NAME, plugin_name=PLUGIN_NAME): + scope = (entry["project_name"], entry["agent_profile"]) + if scope not in scopes: + scopes.append(scope) + result = [] + for project, profile in scopes: + config = plugins.get_plugin_config(PLUGIN_NAME, project_name=project, agent_profile=profile) or {} + for bot in config.get("bots", []): + if bot.get("name") and bot.get("token"): + result.append(BotConfig(project, profile, bot)) + return result + + +def bot_identity(config: dict) -> str: + # Token rotation must not create two connections to the same Telegram bot. + return config["token"].split(":", 1)[0] + + +def is_safe_name(name) -> bool: + return isinstance(name, str) and bool(re.fullmatch(r"[^/\\\x00-\x1f\x7f]{1,128}", name)) + + +def enabled(project: str, profile: str) -> bool: + toggles = plugins.find_plugin_assets( + plugins.TOGGLE_FILE_PATTERN, plugin_name=PLUGIN_NAME, + project_name=project, agent_profile=profile, + ) + return not toggles or Path(toggles[0]["path"]).name == plugins.ENABLED_FILE_NAME + + +def available_bots() -> tuple[dict[str, BotConfig], list[str]]: + bots = configured_bots() + identities = [bot_identity(bot.config) for bot in bots] + keys = [bot.key for bot in bots] + conflicts = [bot.key for bot in bots if identities.count(bot_identity(bot.config)) > 1 + or keys.count(bot.key) > 1 or not is_safe_name(bot.config["name"])] + toggle_scopes = [(entry["project_name"], entry["agent_profile"]) + for entry in plugins.find_plugin_assets(plugins.TOGGLE_FILE_PATTERN, plugin_name=PLUGIN_NAME)] + return { + bot.key: bot for bot in bots + if bot.key not in conflicts and bot.config.get("enabled") + and any(resolve(bot, project or bot.project, profile or bot.profile) + for project, profile in [(bot.project, bot.profile), *toggle_scopes]) + }, conflicts + + +def resolve(bot: BotConfig, project: str, profile: str) -> dict: + if (bot.project and bot.project != project) or (bot.profile and bot.profile != profile): + return {} + if not enabled(project, profile): + return {} + config = plugins.get_plugin_config(PLUGIN_NAME, project_name=project, agent_profile=profile) or {} + return next((item for item in config.get("bots", []) + if item.get("name") == bot.config["name"] + and item.get("token") == bot.config["token"] and item.get("enabled")), {}) + + +def initial_scope(bot: BotConfig, user_id: int) -> tuple[str, str]: + project = bot.project or (bot.config.get("user_projects") or {}).get(str(user_id)) or bot.config.get("default_project", "") + profile = bot.profile or settings.get_settings()["agent_profile"] + return project, profile + + +def context_config(context, *, project=None, profile=None) -> dict: + bots, _ = available_bots() + bot = bots.get(context.data.get(CTX_TG_BOT)) + if not bot: + return {} + project = projects.get_context_project_name(context) if project is None else project + profile = context.config.profile if profile is None else profile + config = resolve(bot, project or "", profile) + from plugins._telegram_integration.helpers.handler import _is_allowed + if (not config or context.data.get(CTX_TG_USER_ID) is None + or not _is_allowed(config, context.data.get(CTX_TG_USER_ID), context.data.get(CTX_TG_USERNAME))): + return {} + if config.get("group_mode") == "off" and context.data.get(CTX_TG_CHAT_TYPE) != "private": + return {} + return config + + +def require_scope(context, project: str, profile: str) -> None: + if not context_config(context, project=project, profile=profile): + raise PermissionError("This Telegram bot or user is not allowed in that project/profile.") + # Project activation can replace unavailable profiles; never authorize one and run another. + from helpers import subagents + if profile not in subagents.get_available_agents_dict(project or None): + raise PermissionError("Choose an agent profile available in the destination project first.") + + +def can_select_session(source, target) -> bool: + config = context_config(source, project=projects.get_context_project_name(target) or "", profile=target.config.profile) + if not config: + return False + if target.data.get(CTX_TG_BOT): + return all(source.data.get(key) == target.data.get(key) + for key in (CTX_TG_BOT, CTX_TG_USER_ID, CTX_TG_CHAT_ID)) + from plugins._telegram_integration.helpers.handler import _is_admin + return _is_admin(config, source.data.get(CTX_TG_USER_ID), source.data.get(CTX_TG_USERNAME)) + + +def remember_config(context, config: dict) -> None: + context.data[CTX_TG_BOT_CFG] = {key: value for key, value in config.items() + if key not in {"token", "webhook_secret"}} + + +def authorized_bot(context): + from plugins._telegram_integration.helpers.bot_manager import get_bot + try: + config = context_config(context) + except Exception: + return None + instance = get_bot(context.data.get(CTX_TG_BOT)) + if config and instance and instance.bot.token == config["token"]: + return instance + return None diff --git a/plugins/_telegram_integration/helpers/slash_commands.py b/plugins/_telegram_integration/helpers/slash_commands.py index 337a062c6..4c8625b73 100644 --- a/plugins/_telegram_integration/helpers/slash_commands.py +++ b/plugins/_telegram_integration/helpers/slash_commands.py @@ -9,6 +9,7 @@ from helpers import integration_commands, plugins, projects from helpers.persist_chat import save_tmp_chat from plugins._commands.helpers import commands from plugins._telegram_integration.helpers import command_ui, telegram_client as tc +from plugins._telegram_integration.helpers import scopes # These names retain Telegram's existing behavior and pickers for bundled commands. @@ -178,7 +179,10 @@ async def apply_result(context, token, chat_id, message_id, name, result, *, is_ async def select_session(context, target): if context.is_running() or target.is_running(): raise ValueError("Stop the active run before switching sessions.") + if not scopes.can_select_session(context, target): + raise PermissionError("This Telegram user cannot access that session.") command_ui._copy_telegram_binding(context, target) + scopes.remember_config(target, scopes.context_config(target)) command_ui._set_session_mapping(target) save_tmp_chat(target) diff --git a/plugins/_telegram_integration/hooks.py b/plugins/_telegram_integration/hooks.py index 1de958821..29bf99762 100644 --- a/plugins/_telegram_integration/hooks.py +++ b/plugins/_telegram_integration/hooks.py @@ -4,7 +4,18 @@ from hashlib import sha256 def get_plugin_config(default=None, **kwargs): config = deepcopy(default or {}) + if not isinstance(config, dict) or not isinstance(config.get("bots", []), list): + raise ValueError("Telegram configuration must contain a bot list.") for bot in config.get("bots", []): + if not isinstance(bot, dict) or not isinstance(bot.get("enabled", False), bool): + raise ValueError("Each Telegram bot must have a boolean enabled setting.") + for field in ("allowed_users", "admin_users"): + if not isinstance(bot.get(field, []), list): + raise ValueError(f"Telegram {field} must be a list.") + if bot.get("group_mode", "mention") not in {"off", "mention", "all"}: + raise ValueError("Telegram group mode must be off, mention or all.") + if bot.get("mode", "polling") not in {"polling", "webhook"}: + raise ValueError("Telegram delivery mode must be polling or webhook.") bot["token"] = str(bot.get("token") or "").strip() if not str(bot.get("name") or "").strip() and bot["token"]: bot_id = bot["token"].split(":", 1)[0] @@ -12,23 +23,22 @@ def get_plugin_config(default=None, **kwargs): return config -def save_plugin_config(settings=None, **kwargs): +def save_plugin_config(settings=None, project_name="", agent_profile="", **kwargs): config = get_plugin_config(settings) names = [bot.get("name") for bot in config.get("bots", []) if bot.get("name")] if len(names) != len(set(names)): raise ValueError("Each Telegram bot must have a different name.") + from plugins._telegram_integration.helpers.scopes import bot_identity, configured_bots, is_safe_name + if any(not is_safe_name(name) for name in names): + raise ValueError("Bot names must contain 1–128 characters without path separators or control characters.") + identities = [bot_identity(bot) for bot in config.get("bots", []) if bot.get("token")] + other_ids = {bot_identity(bot.config) for bot in configured_bots() + if (bot.project, bot.profile) != (project_name, agent_profile)} + if len(identities) != len(set(identities)) or other_ids.intersection(identities): + raise ValueError("Each configured scope needs a separate Telegram bot. Create one with @BotFather and use its token; do not copy an existing bot token.") + if project_name: + for bot in config.get("bots", []): + targets = [bot.get("default_project")] + list((bot.get("user_projects") or {}).values()) + if any(target and target != project_name for target in targets): + raise ValueError("A project-scoped Telegram bot can only route to its own project.") return config - - -def disable(): - from plugins._telegram_integration.helpers.bot_manager import get_all_bots - from plugins._telegram_integration.helpers.sandbox import worker - for instance in list(get_all_bots().values()): - instance.webhook_active = False - instance.webhook_secret = '' - for task in list(instance.deliveries): - task.get_loop().call_soon_threadsafe(task.cancel) - if instance.task and not instance.task.done(): - instance.task.get_loop().call_soon_threadsafe(instance.task.cancel) - get_all_bots().clear() - worker.stop() diff --git a/plugins/_telegram_integration/plugin.yaml b/plugins/_telegram_integration/plugin.yaml index 72bbf76a5..7953e6482 100644 --- a/plugins/_telegram_integration/plugin.yaml +++ b/plugins/_telegram_integration/plugin.yaml @@ -4,5 +4,5 @@ description: Communicate with Agent Zero via Telegram. Supports polling and webh version: 1.0.0 settings_sections: - external -per_project_config: false -per_agent_config: false +per_project_config: true +per_agent_config: true diff --git a/plugins/_telegram_integration/webui/config.html b/plugins/_telegram_integration/webui/config.html index 5dbe59333..06ff748ef 100644 --- a/plugins/_telegram_integration/webui/config.html +++ b/plugins/_telegram_integration/webui/config.html @@ -13,10 +13,13 @@
Telegram
- Bot settings and access rules apply globally. Use Default project and User project mapping to route conversations. + Configure bots globally, per project, per agent profile, or for a project and profile together. + Each saved scope needs its own bot from @BotFather. + When copying settings to another scope, replace the token with that bot's token before saving. + Inherited settings use the existing bot without starting another connection.
- These legacy scoped settings are available for review. Reopen Telegram settings to edit the global configuration. + Bots configured here stay within this project/profile. Their allowlists and activation rules are checked on every message and button press.
diff --git a/plugins/_time_travel/helpers/compaction.py b/plugins/_time_travel/helpers/compaction.py new file mode 100644 index 000000000..1591f7fd2 --- /dev/null +++ b/plugins/_time_travel/helpers/compaction.py @@ -0,0 +1,129 @@ +"""Expire snapshot ancestry without modifying workspace files or discarding retained trees.""" + +import base64 +import json +import os +from pathlib import Path +import signal +import subprocess + + +def _git(repo: Path, *args: str, input: bytes | None = None, timeout: int = 20) -> bytes: + env = os.environ.copy() + for name in ("GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES"): + env.pop(name, None) + with subprocess.Popen( + ["git", f"--git-dir={repo}", *args], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env, start_new_session=True, + ) as process: + try: + stdout, stderr = process.communicate(input, timeout=timeout) + except subprocess.TimeoutExpired: + # GC spawns pack/repack children that must stop before the workspace lock releases. + os.killpg(process.pid, signal.SIGKILL) + process.communicate() + raise + if process.returncode: + raise RuntimeError(stderr.decode("utf-8", "replace").strip()) + return stdout + + +def object_stats(repo: Path) -> dict[str, int]: + values = {} + for line in _git(repo, "count-objects", "-v").decode().splitlines(): + key, _, value = line.partition(": ") + if value.isdigit(): + values[key] = int(value) + return { + "bytes": 1024 * (values.get("size", 0) + values.get("size-pack", 0)), + "loose_count": values.get("count", 0), + "loose_kib": values.get("size", 0), + } + + +def compact_repository(repo: Path, *, max_snapshots: int, max_age_days: int, now: float) -> dict[str, int]: + """Caller holds the workspace lock through ref replacement, index reset and GC.""" + current_ref = "refs/heads/current" + preserved_prefix = "refs/a0-time-travel/preserved/" + stats = {"repositories_compacted": 0, "commits_expired": 0, "gc_runs": 0, "bytes_reclaimed": 0} + if not (repo / "HEAD").is_file(): + return stats + if repo.is_symlink() or any((repo / name).is_symlink() for name in ("objects", "refs")): + raise RuntimeError("History storage contains a symlink; cleanup skipped.") + if _git(repo, "symbolic-ref", "HEAD").decode().strip() != current_ref: + raise RuntimeError("History HEAD is not attached to the current snapshot; cleanup skipped.") + refs = dict(line.split() for line in _git(repo, "for-each-ref", "--format=%(refname) %(objectname)").decode().splitlines()) + if not refs: + return stats + if current_ref not in refs or any(ref != current_ref and not ref.startswith(preserved_prefix) for ref in refs): + raise RuntimeError("History contains unmanaged references; cleanup skipped.") + records = [] + for line in _git(repo, "log", "--all", "--date-order", "--format=%H %T %ct %P").decode().splitlines(): + commit, tree, stamp, *parents = line.split() + if len(parents) > 1: + raise RuntimeError("History contains merge commits; cleanup skipped.") + records.append((commit, tree, int(stamp), parents[0] if parents else "")) + cutoff = now - max_age_days * 86400 if max_age_days else float("-inf") + recent = [record[0] for record in records if record[2] >= cutoff] + if max_snapshots: + recent = recent[:max_snapshots] + keep = set(recent) | {refs[current_ref]} + pending = repo.parent / "compaction.pending" + before = object_stats(repo) + mapping: dict[str, str] = {} + checkpoints: dict[str, str] = {} + + def rewrite(commit: str, parent: str, *, checkpoint: bool = False) -> str: + raw = _git(repo, "cat-file", "commit", commit) + header, body = raw.split(b"\n\n", 1) + lines = header.splitlines() + if any(not line.startswith((b"tree ", b"parent ", b"author ", b"committer ", b"encoding ")) for line in lines): + raise RuntimeError("History contains unsupported commit headers; cleanup skipped.") + lines = [line for line in lines if not line.startswith(b"parent ")] + if parent: + lines.insert(1, f"parent {parent}".encode()) + if checkpoint: + metadata = base64.b64encode(json.dumps({"retention_checkpoint": True}).encode()) + body = b"History checkpoint\n\nA0-Time-Travel-Metadata: " + metadata + b"\n" + rewritten = b"\n".join(lines) + b"\n\n" + body + if rewritten == raw: + return commit + pending.write_text("History compaction requires garbage collection.\n") + return _git(repo, "hash-object", "-t", "commit", "-w", "--stdin", input=rewritten).decode().strip() + + if len(keep) < len(records): + for commit, _tree, _stamp, parent in reversed(records): + if commit not in keep: + continue + if not parent: + mapping[commit] = commit + continue + if parent in keep: + new_parent = mapping[parent] + else: + if parent not in checkpoints: + checkpoints[parent] = rewrite(parent, "", checkpoint=True) + new_parent = checkpoints[parent] + mapping[commit] = commit if new_parent == parent else rewrite(commit, new_parent) + commands = ["start"] + for ref, old in refs.items(): + if old not in keep: + commands.append(f"delete {ref} {old}") + elif mapping[old] != old: + commands.append(f"update {ref} {mapping[old]} {old}") + if len(commands) > 1: + pending.write_text("History compaction requires garbage collection.\n") + commands.extend(["prepare", "commit"]) + _git(repo, "update-ref", "--stdin", input=("\n".join(commands) + "\n").encode()) + stats["repositories_compacted"] = 1 + stats["commits_expired"] = len(records) - len(keep) + + if pending.exists() or before["loose_count"] > 256 or before["loose_kib"] > 65536: + # The index and reflogs can otherwise keep expired blobs alive after ref replacement. + _git(repo, "read-tree", current_ref) + _git(repo, "reflog", "expire", "--expire=now", "--expire-unreachable=now", "--all") + _git(repo, "-c", "pack.threads=1", "gc", "--prune=now", timeout=120) + pending.unlink(missing_ok=True) + stats["gc_runs"] = 1 + stats["bytes_reclaimed"] = max(0, before["bytes"] - object_stats(repo)["bytes"]) + return stats diff --git a/plugins/_time_travel/helpers/locking.py b/plugins/_time_travel/helpers/locking.py new file mode 100644 index 000000000..380946426 --- /dev/null +++ b/plugins/_time_travel/helpers/locking.py @@ -0,0 +1,11 @@ +"""Locks shared by history operations and retention, outside removable repositories.""" + +from pathlib import Path + +from filelock import FileLock + + +def workspace_lock(shadow_path: Path) -> FileLock: + lock_dir = shadow_path.parent / ".locks" + lock_dir.mkdir(parents=True, exist_ok=True) + return FileLock(str(lock_dir / f"{shadow_path.name}.lock"), timeout=20, is_singleton=True) diff --git a/plugins/_time_travel/helpers/retention.py b/plugins/_time_travel/helpers/retention.py index 417aeb179..333daee32 100644 --- a/plugins/_time_travel/helpers/retention.py +++ b/plugins/_time_travel/helpers/retention.py @@ -13,17 +13,18 @@ The sweep (driven from ``job_loop``, throttled by config) removes: forward-enumerated (project folders, the configured workdir, per-chat workdirs) and hashed with the same ``workspace_id_for`` derivation; anything outside that set has no owner and can never be shown in the UI again. Deleted once last activity is past a grace window. -- AGED repositories — no snapshot in ``retention_max_age_days`` (0 = keep forever, the - default). -- STALE LOCKS — ``repo.git/index.lock`` older than ``retention_stale_lock_minutes``; Time - Travel kills its git subprocesses at ``GIT_TIMEOUT_SECONDS``, so no legitimate lock lives - that long. Removing it un-wedges future snapshots. +- AGED repositories — no snapshot or travel in ``retention_max_age_days`` (0 disables + whole-history deletion for inactive workspaces, the default). +- STALE LOCKS — ``repo.git/index.lock`` older than ``retention_stale_lock_minutes``; + removal holds the workspace lock so it cannot race a capture, restore or compaction. - INVALID BACKUPS — ``repo.git.invalid*`` set-asides made for corrupt repositories, past the same grace window. -Deleting a live workspace's shadow repository is always safe for the feature itself: the next -snapshot lazily re-initializes an empty history. Deletion is refused for any path outside the -shadow root. +Active snapshot expiry is enabled by default and can be disabled separately. ``compaction.py`` +preserves the current state, recent snapshots and checkpoint boundaries, then reclaims +unreachable objects. All mutations share workspace locks with captures and restores; +unknown ownership aborts cleanup. Deleting +an inactive history intentionally loses its recovery points, but never edits workspace files. Durable state next to the workspaces dir: ``retention.json`` (running totals + last sweep stamp) and ``retention.log`` (one JSON line per sweep with the names of everything removed, @@ -37,8 +38,13 @@ import json import os import shutil import time +from pathlib import Path from typing import Any, Optional +from filelock import Timeout + +from plugins._time_travel.helpers.locking import workspace_lock + PLUGIN_NAME = "_time_travel" MARKER_FILE = "retention.json" @@ -51,6 +57,9 @@ DEFAULT_CONFIG: dict[str, Any] = { "retention_max_age_days": 0, "retention_orphan_grace_hours": 24, "retention_stale_lock_minutes": 30, + "history_retention_enabled": True, + "history_max_snapshots": 500, + "history_max_age_days": 30, } @@ -64,15 +73,15 @@ def _int_at_least(value: Any, minimum: int, fallback: int) -> int: def effective_config(cfg: Optional[dict[str, Any]] = None) -> dict[str, Any]: """Plugin config with defaults filled in and values clamped to sane minimums.""" if cfg is None: - try: - from helpers import plugins + from helpers import plugins - cfg = plugins.get_plugin_config(PLUGIN_NAME) or {} - except Exception: - cfg = {} + cfg = plugins.get_plugin_config(PLUGIN_NAME) or {} merged = dict(DEFAULT_CONFIG) merged.update({k: v for k, v in cfg.items() if k in DEFAULT_CONFIG and v is not None}) merged["retention_enabled"] = bool(merged["retention_enabled"]) + merged["history_retention_enabled"] = merged["history_retention_enabled"] is True + merged["history_max_snapshots"] = _int_at_least(merged["history_max_snapshots"], 0, 500) + merged["history_max_age_days"] = _int_at_least(merged["history_max_age_days"], 0, 30) merged["retention_sweep_interval_hours"] = _int_at_least( merged["retention_sweep_interval_hours"], 1, 6 ) @@ -109,22 +118,19 @@ def live_workspace_ids() -> set[str]: projects_root = time_travel.real_path_for_display("/a0/usr/projects") try: for name in os.listdir(projects_root): - if os.path.isdir(os.path.join(projects_root, name)): + if (projects_root / name).is_dir(): ids.add(time_travel.workspace_id_for(f"/a0/usr/projects/{name}")) - except Exception: + except FileNotFoundError: pass - try: - ids.add(time_travel.workspace_id_for(time_travel.configured_workdir_display_path())) - except Exception: - ids.add(time_travel.workspace_id_for("/a0/usr/workdir")) + ids.add(time_travel.workspace_id_for(time_travel.configured_workdir_display_path())) chats_root = time_travel.real_path_for_display("/a0/usr/chats") try: for name in os.listdir(chats_root): - if os.path.isdir(os.path.join(chats_root, name, "workdir")): + if (chats_root / name / "workdir").is_dir(): ids.add(time_travel.workspace_id_for(f"/a0/usr/chats/{name}/workdir")) - except Exception: + except FileNotFoundError: pass return ids @@ -187,6 +193,10 @@ def read_history(limit: int = 50, state_dir: Optional[str] = None) -> list[dict[ def _last_activity(entry_path: str) -> float: + try: + return os.stat(os.path.join(entry_path, "last_activity"), follow_symlinks=False).st_mtime + except FileNotFoundError: + pass candidates = [ os.path.join(entry_path, "repo.git", "refs", "heads", "current"), os.path.join(entry_path, "repo.git", "packed-refs"), @@ -221,7 +231,7 @@ def _remove_tree(path: str, shadow_root: str) -> int: """rmtree guarded to the shadow root; returns bytes reclaimed (0 on refusal/failure).""" real = os.path.realpath(path) root = os.path.realpath(shadow_root) - if not real.startswith(root + os.sep): + if os.path.islink(path) or not real.startswith(root + os.sep): return 0 size = _tree_bytes(real) try: @@ -246,6 +256,9 @@ def sweep( "stale_locks_removed": 0, "invalid_backups_removed": 0, "bytes_reclaimed": 0, + "repositories_compacted": 0, + "commits_expired": 0, + "gc_runs": 0, } config = effective_config(cfg) if not config["retention_enabled"]: @@ -270,42 +283,70 @@ def sweep( for name in entries: entry = os.path.join(root, name) - if not os.path.isdir(entry): + if len(name) != 32 or any(char not in "0123456789abcdef" for char in name): continue - last = _last_activity(entry) - - if name not in ids: - if now - last > grace_s: - stats["bytes_reclaimed"] += _remove_tree(entry, root) - stats["orphans_removed"] += 1 - detail["orphans"].append(name) + if os.path.islink(entry) or not os.path.isdir(entry): continue - - if max_age_s and now - last > max_age_s: - stats["bytes_reclaimed"] += _remove_tree(entry, root) - stats["aged_removed"] += 1 - detail["aged"].append(name) - continue - - lock = os.path.join(entry, "repo.git", "index.lock") try: - if os.path.isfile(lock) and now - os.stat(lock).st_mtime > lock_s: - os.remove(lock) - stats["stale_locks_removed"] += 1 - detail["locks"].append(name) - except Exception: - pass + with workspace_lock(Path(entry)).acquire(timeout=0): + if os.path.islink(os.path.join(entry, "repo.git")): + continue + last = _last_activity(entry) - try: - for sub in os.listdir(entry): - if sub.startswith("repo.git.invalid"): - backup = os.path.join(entry, sub) - if now - os.stat(backup).st_mtime > grace_s: - stats["bytes_reclaimed"] += _remove_tree(backup, root) - stats["invalid_backups_removed"] += 1 - detail["invalid"].append(f"{name}/{sub}") - except Exception: - pass + if name not in ids: + if now - last > grace_s: + stats["bytes_reclaimed"] += _remove_tree(entry, root) + if not os.path.lexists(entry): + stats["orphans_removed"] += 1 + detail["orphans"].append(name) + continue + + if max_age_s and now - last > max_age_s: + stats["bytes_reclaimed"] += _remove_tree(entry, root) + if not os.path.lexists(entry): + stats["aged_removed"] += 1 + detail["aged"].append(name) + continue + + lock = os.path.join(entry, "repo.git", "index.lock") + try: + if os.path.isfile(lock) and now - os.stat(lock).st_mtime > lock_s: + os.remove(lock) + stats["stale_locks_removed"] += 1 + detail["locks"].append(name) + except Exception: + pass + if config["history_retention_enabled"]: + from helpers.print_style import PrintStyle + from plugins._time_travel.helpers.compaction import compact_repository + + try: + activity = Path(entry) / "last_activity" + if not activity.exists(): + with open(activity, "xb") as marker: + os.utime(marker.fileno(), (last, last)) + compacted = compact_repository( + Path(entry) / "repo.git", max_snapshots=config["history_max_snapshots"], + max_age_days=config["history_max_age_days"], now=now, + ) + for key, value in compacted.items(): + stats[key] += value + except Exception as exc: + PrintStyle.error(f"Time Travel compaction failed for {name}: {exc}") + + try: + for sub in os.listdir(entry): + if sub.startswith("repo.git.invalid"): + backup = os.path.join(entry, sub) + if now - os.stat(backup).st_mtime > grace_s: + stats["bytes_reclaimed"] += _remove_tree(backup, root) + if not os.path.lexists(backup): + stats["invalid_backups_removed"] += 1 + detail["invalid"].append(f"{name}/{sub}") + except Exception: + pass + except Timeout: + continue stamp = datetime.datetime.now(datetime.timezone.utc).isoformat() _write_marker(base, stats, stamp) diff --git a/plugins/_time_travel/helpers/time_travel.py b/plugins/_time_travel/helpers/time_travel.py index db0196915..8e1012b7b 100644 --- a/plugins/_time_travel/helpers/time_travel.py +++ b/plugins/_time_travel/helpers/time_travel.py @@ -8,15 +8,22 @@ import os import posixpath import shutil import subprocess +import tempfile import threading import time -from dataclasses import dataclass +from contextlib import contextmanager +from dataclasses import dataclass, field, replace +from functools import wraps from pathlib import Path from typing import Any, Iterable +from filelock import Timeout +from pathspec import PathSpec + from helpers import files from helpers.localization import Localization from helpers.print_style import PrintStyle +from plugins._time_travel.helpers.locking import workspace_lock PLUGIN_NAME = "_time_travel" @@ -72,6 +79,12 @@ EXCLUDED_DIR_NAMES = { "coverage", "htmlcov", ".parcel-cache", + ".ipynb_checkpoints", + ".hypothesis", + ".npm", + ".pnpm-store", + ".gradle", + ".conda", } EXCLUDED_DIR_PATTERNS = { @@ -129,6 +142,18 @@ class GitCommandError(TimeTravelError): self.stderr = stderr +def workspace_operation(method): + @wraps(method) + def locked(self, *args, **kwargs): + try: + with workspace_lock(self.workspace.shadow_path): + return method(self, *args, **kwargs) + except Timeout as exc: + raise TimeTravelConflictError("Workspace history is busy. Try again shortly.") from exc + + return locked + + @dataclass(frozen=True) class WorkspaceInfo: id: str @@ -163,6 +188,43 @@ class SnapshotResult: message: str files: list[dict[str, Any]] metadata: dict[str, Any] + skipped_files: list[str] = field(default_factory=list) + + +def plugin_config() -> dict[str, Any]: + from helpers import plugins + + return plugins.get_plugin_config(PLUGIN_NAME) or {} + + +def snapshots_enabled() -> bool: + from helpers import plugins + + return plugins.get_toggle_state(PLUGIN_NAME) == "enabled" + + +class SnapshotPolicy: + def __init__(self, config: dict[str, Any]): + patterns = config.get("capture_exclude_patterns") or "" + if isinstance(patterns, str): + patterns = patterns.splitlines() + if not isinstance(patterns, list) or any(not isinstance(pattern, str) for pattern in patterns): + raise TimeTravelError("Capture exclusions must be one pattern per line.") + try: + self.exclusions = PathSpec.from_lines("gitignore", patterns) + self.max_file_bytes = int(config.get("capture_max_file_mb") or 0) * 1024 * 1024 + if self.max_file_bytes < 0: + raise ValueError() + except (TypeError, ValueError) as exc: + raise TimeTravelError("Invalid Time Travel capture settings.") from exc + + def allows(self, rel: str, *, is_dir: bool = False) -> bool: + if not is_snapshot_candidate(rel, is_dir=is_dir): + return False + parts = rel.split("/") + candidates = [rel + ("/" if is_dir else "")] + candidates.extend("/".join(parts[:index]) + "/" for index in range(1, len(parts))) + return not any(self.exclusions.match_file(path) for path in candidates) def now_iso() -> str: @@ -568,6 +630,8 @@ def schedule_debounced_snapshot( changed_path_hints: list[str] | None = None, delay: float | None = None, ) -> None: + if not snapshots_enabled(): + return clean_metadata = dict(metadata or {}) metadata_hints = _extract_changed_path_hints(clean_metadata) clean_metadata.pop("changed_path_hints", None) @@ -620,7 +684,7 @@ def _flush_debounced_snapshot(workspace_id: str) -> None: with _AUTO_SNAPSHOT_LOCK: _AUTO_SNAPSHOT_TIMERS.pop(workspace_id, None) payload = _AUTO_SNAPSHOT_PAYLOADS.pop(workspace_id, None) - if not payload: + if not payload or not snapshots_enabled(): return try: @@ -639,6 +703,10 @@ def _flush_debounced_snapshot(workspace_id: str) -> None: def _handle_usr_watchdog_events(items: list[Any]) -> None: + if not snapshots_enabled(): + clear_debounced_snapshots() + return + policy = SnapshotPolicy(plugin_config()) by_workspace: dict[str, tuple[WorkspaceInfo, list[str]]] = {} for path, _event in items: display_path = normalize_display_path(str(path or "")) @@ -647,6 +715,9 @@ def _handle_usr_watchdog_events(items: list[Any]) -> None: workspace = resolve_workspace_for_path_hint(display_path) if workspace is None: continue + rel = posixpath.relpath(display_path, workspace.display_path) + if not policy.allows(rel) or not policy.allows(rel, is_dir=True): + continue hints = by_workspace.setdefault(workspace.id, (workspace, []))[1] hints.append(display_path) @@ -718,8 +789,14 @@ def _is_watchdog_snapshot_candidate(display_path: str) -> bool: class TimeTravelService: def __init__(self, workspace: WorkspaceInfo): self.workspace = workspace + self.config = plugin_config() + self.policy = SnapshotPolicy(self.config) + self.skipped_files: list[str] = [] + @workspace_operation def ensure_repo(self) -> None: + if self.workspace.shadow_path.is_symlink() or self.workspace.repo_git_path.is_symlink(): + raise TimeTravelError("History storage must not be a symlink.") self.workspace.shadow_path.mkdir(parents=True, exist_ok=True) if not self._shadow_repo_valid(): self._repair_shadow_repo_head() @@ -727,13 +804,10 @@ class TimeTravelService: self._initialize_shadow_repo(quarantine_existing=True) self._ensure_current_head_ref() - self._git("config", "user.name", "Agent Zero Time Travel") - self._git("config", "user.email", "time-travel@agent-zero.local") - self._git("config", "core.autocrlf", "false") - self._git("config", "core.filemode", "true") - + @workspace_operation def current_hash(self) -> str: - self.ensure_repo() + if not self.workspace.repo_git_path.is_dir(): + return "" completed = self._git("rev-parse", "--verify", "HEAD", check=False) return completed.stdout.strip() if completed.returncode == 0 else "" @@ -741,6 +815,7 @@ class TimeTravelService: current = self.current_hash() return current[:12] if current else "" + @workspace_operation def snapshot( self, *, @@ -763,6 +838,7 @@ class TimeTravelService: message=message or self._default_snapshot_message(trigger), files=[], metadata=self._metadata(trigger, metadata, changed_path_hints), + skipped_files=self.skipped_files, ) if not previous_hash and not included_paths: @@ -774,6 +850,7 @@ class TimeTravelService: message=message or self._default_snapshot_message(trigger), files=[], metadata=self._metadata(trigger, metadata, changed_path_hints), + skipped_files=self.skipped_files, ) full_metadata = self._metadata(trigger, metadata, changed_path_hints) @@ -788,6 +865,7 @@ class TimeTravelService: env["GIT_COMMITTER_DATE"] = timestamp commit = self._git(*args, input=commit_message, env=env).stdout.strip() self._git("update-ref", "HEAD", commit) + self._record_activity() diff_base = previous_hash or EMPTY_TREE return SnapshotResult( created=True, @@ -797,49 +875,53 @@ class TimeTravelService: message=message or self._default_snapshot_message(trigger), files=self.diff_files(diff_base, commit), metadata=full_metadata, + skipped_files=self.skipped_files, ) + @workspace_operation def history_list(self, *, limit: int = 100, offset: int = 0, file_filter: str = "") -> dict[str, Any]: self._ensure_workspace_dir() - self.ensure_repo() limit = min(max(int(limit or 100), 1), 200) offset = max(int(offset or 0), 0) file_filter = str(file_filter or "").strip().lower() current = self.current_hash() - present = self.present_summary() - - all_hashes = self._rev_list_all() - if file_filter: - all_hashes = [ - commit_hash - for commit_hash in all_hashes - if any( - file_filter in str(item.get("path") or "").lower() - or file_filter in str(item.get("old_path") or "").lower() - for item in self.commit_files(commit_hash) - ) - ] - - window = all_hashes[offset : offset + limit + 1] + window = self._history_window(limit + 1, offset, file_filter) if current else [] visible = window[:limit] return { "ok": True, "context_id": self.workspace.context_id, "workspace": self.workspace.public(), "current_hash": current, - "present": present, - "commits": [self.commit_object(commit_hash, current_hash=current) for commit_hash in visible], + "present": None, + "commits": self._commit_objects(visible, current_hash=current), "has_more": len(window) > limit, + "storage": self.storage_info(), } + def storage_info(self) -> dict[str, Any]: + from plugins._time_travel.helpers.compaction import object_stats + from plugins._time_travel.helpers.retention import effective_config + + config = effective_config(self.config) + exists = self.workspace.repo_git_path.is_dir() + return { + "object_bytes": object_stats(self.workspace.repo_git_path)["bytes"] if exists else 0, + "commits": int(self._git("rev-list", "--count", "--all").stdout) if exists else 0, + "retention_enabled": config["retention_enabled"] and config["history_retention_enabled"], + "max_snapshots": config["history_max_snapshots"], + "max_age_days": config["history_max_age_days"], + "max_file_mb": self.policy.max_file_bytes // (1024 * 1024), + } + + @workspace_operation def history_diff(self, *, commit_hash: str, path: str, mode: str = "commit") -> dict[str, Any]: - self.ensure_repo() path = self._safe_rel_path(path) mode = str(mode or "commit").strip().lower() if mode in {"present", "current"}: base = self.current_hash() or EMPTY_TREE - target, _paths = self._current_tree() + with self._present_view() as (view, target): + return view._patch_payload(base, target, path) else: commit_hash = self._validate_commit(commit_hash) base = self._first_parent(commit_hash) or EMPTY_TREE @@ -847,8 +929,8 @@ class TimeTravelService: return self._patch_payload(base, target, path) + @workspace_operation def preview(self, *, operation: str, commit_hash: str) -> dict[str, Any]: - self.ensure_repo() operation = str(operation or "").strip().lower() commit_hash = self._validate_commit(commit_hash) current = self.current_hash() or EMPTY_TREE @@ -857,12 +939,14 @@ class TimeTravelService: base = current target = commit_hash elif operation == "revert": + self._check_revert_checkpoint(commit_hash) base = commit_hash target = self._first_parent(commit_hash) or EMPTY_TREE else: raise TimeTravelError("Unsupported preview operation.") files_changed = self.diff_files(base, target) + self._check_restore_paths(files_changed, target) previews = [] for item in files_changed[:12]: rel_path = str(item.get("path") or item.get("old_path") or "") @@ -879,6 +963,7 @@ class TimeTravelService: "previews": previews, } + @workspace_operation def travel(self, *, commit_hash: str, metadata: dict[str, Any] | None = None) -> dict[str, Any]: self._ensure_workspace_dir() self.ensure_repo() @@ -888,8 +973,10 @@ class TimeTravelService: if previous: self._preserve_ref(previous, reason="travel") affected = self.diff_files(previous or EMPTY_TREE, target) + self._check_restore_paths(affected, target) self._apply_commit_tree(previous or EMPTY_TREE, target, affected) self._git("update-ref", "HEAD", target) + self._record_activity() return { "ok": True, "operation": "travel", @@ -900,12 +987,15 @@ class TimeTravelService: "affected_files": affected, } + @workspace_operation def revert(self, *, commit_hash: str, metadata: dict[str, Any] | None = None) -> dict[str, Any]: self._ensure_workspace_dir() self.ensure_repo() target = self._validate_commit(commit_hash) + self._check_revert_checkpoint(target) before = self.snapshot(trigger="before_revert", metadata=metadata or {}) parent = self._first_parent(target) or EMPTY_TREE + self._check_restore_paths(self.diff_files(parent, target), parent) patch = self._git_bytes("diff", "--binary", parent, target).stdout if patch: checked = self._git_bytes("apply", "--reverse", "--check", "--binary", "--whitespace=nowarn", input=patch, check=False) @@ -932,42 +1022,45 @@ class TimeTravelService: "affected_files": after.files, } + @workspace_operation def present_summary(self) -> dict[str, Any]: - self.ensure_repo() - current_tree, _paths = self._current_tree() current = self.current_hash() base = current or EMPTY_TREE - base_tree = self._commit_tree(current) if current else EMPTY_TREE - if base_tree == current_tree: - return clean_summary() - changed = self.diff_files(base, current_tree) + with self._present_view() as (view, current_tree): + changed = view.diff_files(base, current_tree) + skipped_files = view.skipped_files return { "dirty": bool(changed), "files_count": len(changed), "additions": sum(int(item.get("additions") or 0) for item in changed), "deletions": sum(int(item.get("deletions") or 0) for item in changed), "files": changed, + "skipped_files": skipped_files, } def commit_object(self, commit_hash: str, *, current_hash: str = "") -> dict[str, Any]: commit_hash = self._validate_commit(commit_hash) - show = self._git("show", "-s", "--format=%H%x00%h%x00%cI%x00%s%x00%B", commit_hash).stdout - parts = show.split("\0", 4) - full_hash = parts[0].strip() - short_hash = parts[1].strip() if len(parts) > 1 else full_hash[:12] - timestamp = parts[2].strip() if len(parts) > 2 else "" - subject = parts[3].strip() if len(parts) > 3 else "" - body = parts[4] if len(parts) > 4 else "" - metadata = self._parse_metadata(body) - return { - "hash": full_hash, - "short_hash": short_hash, - "timestamp": timestamp, - "message": subject, - "is_current": bool(current_hash and full_hash == current_hash), - "metadata": metadata, - "files": self.commit_files(full_hash), - } + return self._commit_objects([commit_hash], current_hash=current_hash)[0] + + def _commit_objects(self, hashes: list[str], *, current_hash: str) -> list[dict[str, Any]]: + if not hashes: + return [] + fields = self._git("show", "-s", "--format=%H%x00%h%x00%cI%x00%s%x00%B%x00%P%x00", *hashes).stdout.split("\0") + commits = [] + for index in range(0, len(fields) - 1, 6): + full_hash, short_hash, timestamp, subject, body, parents = fields[index:index + 6] + full_hash = full_hash.strip() + parent = parents.split()[0] if parents.strip() else EMPTY_TREE + commits.append({ + "hash": full_hash, + "short_hash": short_hash, + "timestamp": timestamp, + "message": subject, + "is_current": full_hash == current_hash, + "metadata": self._parse_metadata(body), + "files": self.diff_files(parent, full_hash), + }) + return commits def commit_files(self, commit_hash: str) -> list[dict[str, Any]]: commit_hash = self._validate_commit(commit_hash) @@ -981,11 +1074,15 @@ class TimeTravelService: args.extend(["--", path_filter]) output = self._git(*args).stdout entries = _parse_name_status(output) + stat_args = ["diff", "--numstat", "-z", "--find-renames", base, target] + if path_filter: + stat_args.extend(["--", path_filter]) + stats = _parse_numstat(self._git(*stat_args).stdout) if entries else {} result: list[dict[str, Any]] = [] for entry in entries: path = entry["path"] old_path = entry.get("old_path", "") - additions, deletions, binary = self._numstat(base, target, [p for p in (old_path, path) if p]) + additions, deletions, binary = stats.get((old_path, path), (0, 0, False)) action = STATUS_LABELS.get(entry["status"], entry["status"].lower()) result.append( { @@ -1000,13 +1097,28 @@ class TimeTravelService: ) return result - def _current_tree(self) -> tuple[str, list[str]]: - return self._stage_current_tree() + @contextmanager + def _present_view(self): + # Inspection must not leave uncommitted blobs or a modified index in saved history. + with tempfile.TemporaryDirectory(prefix="a0-time-travel-") as folder: + shadow = Path(folder) / "workspace" + view = TimeTravelService(replace(self.workspace, shadow_path=shadow, repo_git_path=shadow / "repo.git")) + view.policy = self.policy + view.ensure_repo() + objects = self.workspace.repo_git_path / "objects" + if objects.is_dir(): + (view.workspace.repo_git_path / "objects/info/alternates").write_text(str(objects) + "\n") + tree, _paths = view._stage_current_tree() + yield view, tree def _stage_current_tree(self) -> tuple[str, list[str]]: - self.ensure_repo() - self._git("read-tree", "--empty") - paths = list(iter_snapshot_paths(self.workspace.real_path, display_path=self.workspace.display_path)) + self.skipped_files = [] + paths = list(iter_snapshot_paths(self.workspace.real_path, display_path=self.workspace.display_path, + policy=self.policy, skipped_files=self.skipped_files)) + indexed = set(self._git("ls-files", "-z").stdout.split("\0")) - {""} + removed = indexed - set(paths) + if removed: + self._git_bytes("update-index", "--force-remove", "-z", "--stdin", input=("\0".join(sorted(removed)) + "\0").encode("utf-8")) if paths: payload = "\0".join(paths).encode("utf-8") + b"\0" self._git_bytes( @@ -1038,7 +1150,37 @@ class TimeTravelService: self._delete_workspace_entry(rel_path) for rel_path in sorted(set(write_paths)): self._materialize_tree_path(target, rel_path) - self._prune_empty_dirs() + self._prune_empty_dirs(delete_paths) + + def _check_revert_checkpoint(self, commit: str) -> None: + body = self._git("show", "-s", "--format=%B", commit).stdout + if self._parse_metadata(body).get("retention_checkpoint"): + raise TimeTravelConflictError("This checkpoint is the start of retained history and cannot be reverted.") + + def _check_restore_paths(self, affected: list[dict[str, Any]], target: str = "") -> None: + sizes = {} + if self.policy.max_file_bytes and target: + for entry in self._git("ls-tree", "-r", "-l", "-z", target).stdout.split("\0"): + if entry: + info, rel = entry.split("\t", 1) + size = info.split()[-1] + if size.isdigit(): + sizes[rel] = int(size) + for item in affected: + for rel in (item.get("path"), item.get("old_path")): + if not rel: + continue + path = self._workspace_child(rel) + if not self.policy.allows(rel): + raise TimeTravelConflictError(f"Restore would change an excluded path: {rel}") + size = max(sizes.get(rel, 0), path.lstat().st_size if path.exists() and not path.is_symlink() else 0) + if self.policy.max_file_bytes and size > self.policy.max_file_bytes: + raise TimeTravelConflictError(f"Restore would change a file above the capture size limit: {rel}") + for parent in path.parents: + if parent == self.workspace.real_path: + break + if _is_nested_git_worktree_dir(parent, self.workspace.real_path): + raise TimeTravelConflictError(f"Restore would change a nested Git workspace: {rel}") def _materialize_tree_path(self, commit_hash: str, rel_path: str) -> None: rel_path = self._safe_rel_path(rel_path) @@ -1094,17 +1236,15 @@ class TimeTravelService: ) target_path.rmdir() - def _prune_empty_dirs(self) -> None: - for root, dirs, _filenames in os.walk(self.workspace.real_path, topdown=False, followlinks=False): - root_path = Path(root) - if root_path == self.workspace.real_path: - continue - if not is_snapshot_candidate(root_path.relative_to(self.workspace.real_path).as_posix(), is_dir=True): - continue - try: - root_path.rmdir() - except OSError: - pass + def _prune_empty_dirs(self, deleted_paths: list[str]) -> None: + for rel in deleted_paths: + parent = posixpath.dirname(rel) + while parent and self.policy.allows(parent, is_dir=True): + try: + self._workspace_child(parent).rmdir() + except OSError: + break + parent = posixpath.dirname(parent) def _tree_entry(self, commit_hash: str, rel_path: str) -> tuple[str, str, str] | None: completed = self._git("ls-tree", "-z", commit_hash, "--", rel_path, check=False) @@ -1120,6 +1260,9 @@ class TimeTravelService: def _patch_payload(self, base: str, target: str, path: str) -> dict[str, Any]: path = self._safe_rel_path(path) additions, deletions, binary = self._numstat(base, target, [path]) + if binary: + return {"ok": True, "path": path, "patch": "", "binary": True, "too_large": False, + "additions": additions, "deletions": deletions, "error": ""} completed = self._git_bytes("diff", "--binary", "--patch", base, target, "--", path, check=False) data = completed.stdout or b"" too_large = len(data) > MAX_RENDERED_PATCH_BYTES @@ -1138,22 +1281,13 @@ class TimeTravelService: def _numstat(self, base: str, target: str, paths: list[str]) -> tuple[int, int, bool]: if not paths: return 0, 0, False - output = self._git("diff", "--numstat", "--find-renames", base, target, "--", *paths, check=False).stdout - additions = 0 - deletions = 0 - binary = False - for line in output.splitlines(): - if not line.strip(): - continue - parts = line.split("\t") - if len(parts) < 2: - continue - if parts[0] == "-" or parts[1] == "-": - binary = True - continue - additions += _safe_int(parts[0]) - deletions += _safe_int(parts[1]) - return additions, deletions, binary + output = self._git("diff", "--numstat", "-z", "--find-renames", base, target, "--", *paths, check=False).stdout + stats = _parse_numstat(output).values() + return ( + sum(item[0] for item in stats), + sum(item[1] for item in stats), + any(item[2] for item in stats), + ) def _rev_list_all(self) -> list[str]: completed = self._git("rev-list", "--date-order", "--all", check=False) @@ -1168,6 +1302,38 @@ class TimeTravelService: seen.add(commit) return result + def _history_window(self, limit: int, offset: int, file_filter: str) -> list[str]: + if not file_filter: + result = self._git("rev-list", "--date-order", "--all", f"--skip={offset}", f"--max-count={limit}", check=False) + return result.stdout.splitlines() if result.returncode == 0 else [] + matches = [] + skipped = 0 + cursor = 0 + while len(matches) < limit: + batch = self._history_window(100, cursor, "") + if not batch: + break + cursor += len(batch) + records = self._git("show", "-z", "--format=%x00%H%x00", "--name-only", "--no-renames", *batch).stdout.split("\0") + index = 0 + for commit in batch: + if records[index:index + 3] != ["", commit, ""]: + raise TimeTravelError("Could not read history file names.") + index += 3 + names = [] + while index < len(records) and records[index]: + names.append(records[index].removeprefix("\n") if not names else records[index]) + index += 1 + if not any(file_filter in name.lower() for name in names): + continue + if skipped < offset: + skipped += 1 + else: + matches.append(commit) + if len(matches) == limit: + break + return matches + def _validate_commit(self, commit_hash: str) -> str: candidate = str(commit_hash or "").strip() if not candidate: @@ -1230,6 +1396,11 @@ class TimeTravelService: label = str(trigger or "snapshot").replace("_", " ").strip().title() return f"Snapshot: {label}" + def _record_activity(self) -> None: + with tempfile.NamedTemporaryFile(dir=self.workspace.shadow_path, delete=False) as marker: + path = marker.name + os.replace(path, self.workspace.shadow_path / "last_activity") + def _ensure_workspace_dir(self) -> None: if not self.workspace.real_path.exists(): raise TimeTravelError("Workspace path does not exist.") @@ -1250,6 +1421,11 @@ class TimeTravelService: path.relative_to(self.workspace.real_path) except ValueError: raise TimeTravelError("Invalid path.") + for parent in path.parents: + if parent == self.workspace.real_path: + break + if parent.is_symlink(): + raise TimeTravelConflictError(f"Restore would follow a directory symlink: {rel}") return path def _rel_from_workspace(self, path: Path) -> str: @@ -1260,6 +1436,9 @@ class TimeTravelService: def _git_env(self) -> dict[str, str]: env = os.environ.copy() + for key in ("GIT_GLOB_PATHSPECS", "GIT_NOGLOB_PATHSPECS", "GIT_ICASE_PATHSPECS", "GIT_INDEX_FILE"): + env.pop(key, None) + env["GIT_LITERAL_PATHSPECS"] = "1" env["GIT_TERMINAL_PROMPT"] = "0" env["GIT_OPTIONAL_LOCKS"] = "0" return env @@ -1319,6 +1498,10 @@ class TimeTravelService: stdout=updated.stdout, stderr=updated.stderr, ) + self._git("config", "user.name", "Agent Zero Time Travel") + self._git("config", "user.email", "time-travel@agent-zero.local") + self._git("config", "core.autocrlf", "false") + self._git("config", "core.filemode", "true") def _loose_ref_exists(self, ref: str) -> bool: return self.workspace.repo_git_path.joinpath(*ref.split("/")).is_file() @@ -1361,7 +1544,6 @@ class TimeTravelService: ) def _git(self, *args: str, input: str | None = None, env: dict[str, str] | None = None, check: bool = True) -> subprocess.CompletedProcess[str]: - self.workspace.shadow_path.mkdir(parents=True, exist_ok=True) completed = subprocess.run( [ "git", @@ -1389,7 +1571,6 @@ class TimeTravelService: return completed def _git_bytes(self, *args: str, input: bytes | None = None, check: bool = True) -> subprocess.CompletedProcess[bytes]: - self.workspace.shadow_path.mkdir(parents=True, exist_ok=True) completed = subprocess.run( [ "git", @@ -1412,8 +1593,10 @@ class TimeTravelService: return completed -def iter_snapshot_paths(workspace: Path, *, display_path: str = "") -> Iterable[str]: +def iter_snapshot_paths(workspace: Path, *, display_path: str = "", policy: SnapshotPolicy | None = None, + skipped_files: list[str] | None = None) -> Iterable[str]: workspace = workspace.resolve(strict=False) + policy = policy or SnapshotPolicy({}) if display_path: root_is_usr = normalize_display_path(display_path) == USR_DISPLAY_ROOT else: @@ -1423,8 +1606,8 @@ def iter_snapshot_paths(workspace: Path, *, display_path: str = "") -> Iterable[ try: with os.scandir(folder) as iterator: entries = sorted(iterator, key=lambda entry: entry.name) - except OSError: - return + except OSError as exc: + raise TimeTravelError(f"Could not scan snapshot directory: {rel_prefix or '.'}") from exc for entry in entries: rel = f"{rel_prefix}/{entry.name}" if rel_prefix else entry.name rel = rel.replace("\\", "/") @@ -1432,17 +1615,21 @@ def iter_snapshot_paths(workspace: Path, *, display_path: str = "") -> Iterable[ is_dir = entry.is_dir(follow_symlinks=False) is_file = entry.is_file(follow_symlinks=False) is_link = entry.is_symlink() - except OSError: - continue + except OSError as exc: + raise TimeTravelError(f"Could not inspect snapshot path: {rel}") from exc if is_dir: if root_is_usr and not rel_prefix and entry.name in USR_ROOT_EXCLUDED_DIR_NAMES: continue if _is_nested_git_worktree_dir(Path(entry.path), workspace): continue - if not is_snapshot_candidate(rel, is_dir=True): + if not policy.allows(rel, is_dir=True): continue yield from walk(Path(entry.path), rel) - elif (is_file or is_link) and is_snapshot_candidate(rel, is_dir=False): + elif (is_file or is_link) and policy.allows(rel): + if is_file and policy.max_file_bytes and entry.stat(follow_symlinks=False).st_size > policy.max_file_bytes: + if skipped_files is not None: + skipped_files.append(rel) + continue yield rel yield from walk(workspace) @@ -1472,6 +1659,12 @@ def is_snapshot_candidate(rel_path: str, *, is_dir: bool) -> bool: if name in {"secrets.env", "variables.env"}: return False + directories = parts if is_dir else parts[:-1] + if any(part in EXCLUDED_DIR_NAMES or any(fnmatch.fnmatch(part, pattern) for pattern in EXCLUDED_DIR_PATTERNS) for part in directories): + return False + if not is_dir and any(fnmatch.fnmatch(name, pattern) for pattern in EXCLUDED_FILE_PATTERNS): + return False + if rel.startswith(".a0proj/"): return _is_safe_a0proj_candidate(rel, is_dir=is_dir) @@ -1541,6 +1734,21 @@ def _parse_name_status(output: str) -> list[dict[str, str]]: return entries +def _parse_numstat(output: str) -> dict[tuple[str, str], tuple[int, int, bool]]: + records = output.split("\0") + stats = {} + index = 0 + while index < len(records) - 1: + additions, deletions, path = records[index].split("\t", 2) + index += 1 + old_path = "" + if not path: + old_path, path = records[index:index + 2] + index += 2 + stats[(old_path, path)] = (_safe_int(additions), _safe_int(deletions), additions == "-" or deletions == "-") + return stats + + def _safe_int(value: str) -> int: try: return max(0, int(value)) @@ -1556,6 +1764,7 @@ def _snapshot_public(snapshot: SnapshotResult) -> dict[str, Any]: "message": snapshot.message, "files": snapshot.files, "metadata": snapshot.metadata, + "skipped_files": snapshot.skipped_files, } diff --git a/plugins/_time_travel/webui/config.html b/plugins/_time_travel/webui/config.html index 0510ecf8e..ab4a3ce69 100644 --- a/plugins/_time_travel/webui/config.html +++ b/plugins/_time_travel/webui/config.html @@ -8,11 +8,33 @@
diff --git a/webui/index.js b/webui/index.js index a95eeba6f..989b9a209 100644 --- a/webui/index.js +++ b/webui/index.js @@ -398,6 +398,7 @@ export async function applySnapshot(snapshot, options = {}) { // If the chat has been reset, reset cursors and request a resync from the caller. // Note: on first snapshot after a context switch, lastLogGuid is intentionally empty, // so the mismatch is expected and should not trigger a second state_request/poll. + const firstSnapshot = !lastLogGuid; if (lastLogGuid != snapshot.log_guid) { if (lastLogGuid) { modelGateStore.resetContext(snapshot.context); @@ -417,7 +418,8 @@ export async function applySnapshot(snapshot, options = {}) { if (lastLogVersion != snapshot.log_version) { updated = true; - if (snapshot.logs?.[0]?.no === 0) { + // Context selection already cleared history; keep any first send rendered since then. + if (!firstSnapshot && snapshot.logs?.[0]?.no === 0) { msgs.resetMessageRenderState(); } await setMessages(modelGateStore.mergeSyntheticMessages(snapshot.logs, context)); diff --git a/webui/js/AGENTS.md b/webui/js/AGENTS.md index 1dd21a436..a343a1390 100644 --- a/webui/js/AGENTS.md +++ b/webui/js/AGENTS.md @@ -66,7 +66,7 @@ - Safe markdown parsing requires double tildes for strikethrough, matching GitHub; single tildes render literally so approximate-value prose like `~1-2%` never collapses into del markup. The override lives in `safe-markdown.js` and applies to the shared marked instance every renderer imports. - Convert standard TeX delimiters before Markdown parsing without touching inline or fenced code. Keep thought-card math rendering local to the agent-message handler rather than adding math flags to generic process-step or key/value rendering. - Do not expose secrets in localStorage, console logs, URLs, or WebSocket payloads. -- Full message snapshots that start at backend log `no` 0 must replace the current message DOM before rendering; incremental snapshots should keep patching existing messages. +- Full message snapshots that start at backend log `no` 0 rebuild the message DOM from the current cache in log order; incremental snapshots keep patching existing messages. The first snapshot after context selection merges with any optimistic first send already in that cache. - The state request builder advertises collection-delta support. An incremental snapshot may carry `contexts: null` and `tasks: null`; retain the current stores and skip sidebar selection/fallback reconciliation in that case. Extension hooks still receive the cached full collections so existing plugin contracts remain list-shaped. - Root responses render with safe Markdown and LaTeX throughout live updates and completion. GEN process steps render thoughts and tool args as plain text without KaTeX, so `$$`-style sequences in technical prose stay literal. - Shared path linking recognizes plain paths, `file:///` URLs, and `/api/download_work_dir_file?path=` text, including inline code, while preserving existing anchors and fenced code blocks. @@ -79,7 +79,7 @@ - `PROCESS_STEP_TYPES` contains core log types only. `messages.js` dispatches `get_process_step_types` with a fresh `{ processStepTypes: Set }` before merging each batch. Extensions add their types and dispatch identifies generic tool fallbacks; the pure classifier receives the resulting set for grouping and utility lookahead, without knowing its source. Do not add a separate handler cache or persist declarations beyond the extension loader lifecycle. - Warnings classified into a full-log process render unit must remain process steps during replay even when the current DOM tail is already complete; use the live DOM tail only when render metadata is unavailable. - `set_messages_after_loop` receives offscreen live updates as results with `result.virtualized === true` and `result.element === null`; extensions that only need `args` may still react, while DOM-mutating extensions must guard the element. -- Context switches, log GUID resets, and full log snapshots must reset both message DOM and message-window cache state. +- Reset the message DOM and its cache on a context switch, log GUID reset, or full snapshot after the first one. - Root responses use their full-log process-group identity when available, so an intervening setup card or another DOM tail cannot strand the completed GEN group with an active animation. - Awaited message-window layout frames must have a timer fallback so hidden or occluded browser windows cannot block state synchronization on painting. - Context switches clear stale history immediately but defer the chat loading splash for 300 ms so fast loads do not flash; slower loads fade it in and dismiss it only after the matching context snapshot finishes rendering. Stale snapshots and timers must not affect a newer switch's splash. diff --git a/webui/js/messages.js b/webui/js/messages.js index bad4507cd..0f86ecadf 100644 --- a/webui/js/messages.js +++ b/webui/js/messages.js @@ -223,7 +223,8 @@ async function setMessagesNow(messages, generation) { const initialWindow = _messageWindow.size > 0 && !history?.querySelector(".message-group"); - if (initialWindow && _messageWindowFollowTail) _messageWindow.showTail(); + const fullSnapshot = messages[0]?.no === 0; + if ((initialWindow || fullSnapshot) && _messageWindowFollowTail) _messageWindow.showTail(); const compactedTail = _messageWindow.compactTailIfNeeded(); const windowMessages = _messageWindow.visibleMessages(); const cappedProcessGroupUpdate = hasCappedProcessGroupUpdate( @@ -231,7 +232,7 @@ async function setMessagesNow(messages, generation) { windowMessages, addedMessageKeys, ); - if (initialWindow || compactedTail || cappedProcessGroupUpdate) { + if (initialWindow || fullSnapshot || compactedTail || cappedProcessGroupUpdate) { return await renderMessageWindow({ preserveScroll: !initialWindow && !followTail, generation,