Agent Zero AI framework
update docs, AGENTS.md and skill
Alessandroa13b81a9a15c
diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 000000000..92fc209e6--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,113 @@+# Agent Zero — Full-Stack Agent & Plugin Architecture++This document bridges the gap between the **Python Backend** (AgentContext, LLM loop) and the **Frontend Component System** (Alpine.js, Modals). Use this as the canonical reference for building deep integrations.++---++## 1. The Core Concept: `AgentContext`++Every conversation in Agent Zero is an `AgentContext`. It owns the message history, the LLM state, the tool definitions, and the log queue.++### Backend: Managing Contexts+When building a plugin, you must interact with the context system correctly:++```python+from agent import AgentContext, AgentContextType, initialize_agent+from python.helpers.messages import UserMessage++# 1. Access an existing context (e.g., from a stored ID)+context = AgentContext.use(context_id)++# 2. Or create a new one+config = {} # use defaults+context = AgentContext(config=config, type=AgentContextType.USER)+await initialize_agent(context)++# 3. Communicate (send a message and wait for completion)+task = context.communicate(UserMessage("Hello Agent!"))+response_text = await task.result()+```++### The Glue: `MessageQueue` (mq)+The frontend listens to a WebSocket. To make messages appear in the WebUI from your plugin, use the log helper:++```python+# In your ApiHandler or bridge+from python.helpers.messages import mq++# This makes the user message appear in the UI immediately+mq.log_user_message(context.id, "Incoming message from WhatsApp", source="WhatsApp")+```++---++## 2. The Frontend: Component System++Agent Zero uses a custom **Component Loader** that fetches HTML, extracts `<style>` and `<script type="module">`, and injects them into the DOM.++### The "Golden Rules" of Frontend Components++1. **Store Gating (Critical)**: Always wrap your component content in a template that waits for the store. This prevents "undefined" errors during the loading race.+ ```html+ <div x-data>+ <template x-if="$store.myStore">+ <div class="content">...</div>+ </template>+ </div>+ ```+2. **Separate Store Files**: Never put store registration logic directly inside the HTML `alpine:init` block. Use a separate `*-store.js` file and import it via `<script type="module" src="...">`.+3. **createStore Proxy**: Use `createStore` from `/js/AlpineStore.js`. It ensures the store is available to the module even before Alpine fully boots.++---++## 3. The Modal System++Modals in A0 are "stacked" and loaded dynamically via `openModal(path)`.++### Directory Convention+- `webui/components/modals/<feature>/<feature>.html`+- `webui/components/modals/<feature>/<feature>-store.js`++### Plugin Settings++Plugins get a dedicated settings modal with **Project** and **Agent profile** context selectors. To enable it:++1. Add `webui/settings.html` to your plugin (auto-detected).+2. Set `"settings_sections": ["agent"]` in `plugin.json` - this places a subsection with a Settings button in the chosen tab.++Your `settings.html` binds to `$store.pluginSettings.settings` (a plain object persisted as `settings.json`). The modal's Save/Cancel footer handles persistence automatically. See `plugins/README.md` for the full contract and settings resolution priority chain.++For plugins that surface **existing core settings** (e.g. wrapping `settings/agent/memory.html`), set `$store.pluginSettings.saveMode = 'core'` in `x-init` to route Save through the core settings API instead.++---++## 4. Lifecycle Synchronization++| Action | Backend Extension | Frontend Lifecycle |+|---|---|---|+| **Initialization** | `agent_init` | `init()` in Store |+| **Mounting** | N/A | `x-create` directive |+| **Processing** | `monologue_start/end` | UI loading state |+| **Cleanup** | `context_deleted` | `x-destroy` directive |++---++## 5. Directory Mapping (Plugin Layout)++> [!IMPORTANT]+> **Always create new plugins in `usr/plugins/`.** The root `/plugins/` folder is reserved for core Agent Zero plugins and may be overwritten during framework updates.++```text+usr/plugins/my-plugin/+├── plugin.json # Required manifest (name, version, settings_sections)+├── api/ # ApiHandler (python.helpers.api)+├── extensions/+│ ├── python/agent_init/ # Auto-start logic+│ └── webui/ # sidebar-quick-actions-main-start/+└── webui/+ ├── settings.html # Optional: plugin settings UI+ └── my-modal.html # Full plugin pages + stores+```++Refer to `docs/agents/AGENTS.components.md` for deep UI technicals and `docs/agents/AGENTS.modals.md` for modal-specific CSS classes (`btn-ok`, `btn-cancel`).+diff --git a/docs/agents/AGENTS.components.md b/docs/agents/AGENTS.components.mdnew file mode 100644index 000000000..7d7ed73f1--- /dev/null+++ b/docs/agents/AGENTS.components.md@@ -0,0 +1,648 @@+# Agent Zero Component System++> Generated from codebase reconnaissance on 2026-01-10+> Scope: `webui/components/` - Self-contained Alpine.js component architecture++## Quick Reference++| Aspect | Value |+|--------|-------|+| **Tech Stack** | Alpine.js, ES Modules, CSS Variables |+| **Component Tag** | `<x-component path="...">` |+| **State Management** | `createStore(name, model)` from `/js/AlpineStore.js` |+| **Modals** | `openModal(path)` / `closeModal()` from `/js/modals.js` |+| **API Layer** | `callJsonApi()` / `fetchApi()` from `/js/api.js` |++---++## Table of Contents++1. [Architecture Overview](#1-architecture-overview)+2. [Component Structure](#2-component-structure)+3. [Store Pattern](#3-store-pattern)+4. [Lifecycle Management](#4-lifecycle-management)+5. [Integration Layer](#5-integration-layer)+6. [Alpine.js Directives](#6-alpinejs-directives)+7. [Patterns and Conventions](#7-patterns-and-conventions)+8. [Pitfalls and Anti-Patterns](#8-pitfalls-and-anti-patterns)+9. [Porting Guide](#9-porting-guide)++---++## 1. Architecture Overview++### Core Files (Integration Layer)++| File | Purpose |+|------|---------|+| `/js/components.js` | Component loader - hydrates `<x-component>` tags |+| `/js/AlpineStore.js` | Store factory with Alpine proxy |+| `/js/modals.js` | Modal stack management |+| `/js/initFw.js` | Bootstrap: loads Alpine, registers custom directives |+| `/js/api.js` | CSRF-protected API client (`callJsonApi`, `fetchApi`) |++### Component Resolution++```+<x-component path="sidebar/left-sidebar.html">+ ↓+ Resolves to: components/sidebar/left-sidebar.html+ ↓+ Loader: importComponent() fetches, parses, injects+```++- Path auto-prefixes `components/` if not present+- Component HTML cached after first fetch+- Module scripts cached by virtual URL+- MutationObserver auto-loads dynamically inserted components++### Data Flow++```+Component HTML+ ↓+imports Store module+ ↓+createStore() registers with Alpine+ ↓+Template binds via $store.name+ ↓+User actions → store methods → state updates → reactive UI+```++---++## 2. Component Structure++### Anatomy of a Component++```html+<html>+<head>+ <!-- Module imports MUST be in <head> -->+ <script type="module">+ import { store } from "/components/feature/feature-store.js";+ </script>+</head>++<body>+ <!-- Store gate: prevents render until store registered -->+ <div x-data>+ <template x-if="$store.featureStore">+ <!-- Single root element inside template (mandatory) -->+ <div class="feature-container">+ <p x-text="$store.featureStore.value"></p>+ <button @click="$store.featureStore.action()">Do Thing</button>+ </div>+ </template>+ </div>++ <!-- Inline styles scoped to component -->+ <style>+ .feature-container {+ color: var(--color-text);+ }+ </style>+</body>+</html>+```++### Key Rules++| Rule | Rationale |+|------|-----------|+| Scripts in `<head>`, content in `<body>` | Loader extracts separately |+| Use `type="module"` for scripts | Enables ES imports, caching |+| Wrap with `x-data` + `x-if="$store.X"` | Prevents render before store ready |+| `<template>` has ONE root element | Alpine limitation |+| Styles inline in component | Self-contained, no global CSS files |++### Nesting Components++```html+<div class="parent-container">+ <x-component path="child/child-component.html"></x-component>+</div>+```++Components can nest other components. Loader recursively processes `x-component` tags.++---++## 3. Store Pattern++### Creating a Store++```javascript+// /components/feature/feature-store.js+import { createStore } from "/js/AlpineStore.js";++const model = {+ // State+ items: [],+ loading: false,+ _initialized: false,++ // Lifecycle (called once by Alpine when store registers)+ init() {+ if (this._initialized) return;+ this._initialized = true;+ this.load();+ },++ // Actions+ async load() {+ this.loading = true;+ // ... fetch data+ this.loading = false;+ },++ // Computed-like getters (Alpine reactivity works)+ get itemCount() {+ return this.items.length;+ }+};++export const store = createStore("featureStore", model);+```++### Store Proxy Behavior++`createStore()` returns a proxy that:+- Before Alpine boots: reads/writes directly to `model` object+- After Alpine boots: reads/writes through `Alpine.store(name)`++This enables safe module-level initialization before Alpine loads.++### Store Access++| Context | Syntax |+|---------|--------|+| Template (Alpine) | `$store.featureStore.prop` |+| Module import | `import { store } from "./feature-store.js"; store.prop` |+| Global (avoid) | `Alpine.store("featureStore").prop` |++**Prefer module imports over global lookups.**++### Persistence Helpers++```javascript+import { saveState, loadState } from "/js/AlpineStore.js";++// Save to localStorage (exclude functions automatically)+const snapshot = saveState(store, [], ["transientField"]);+localStorage.setItem("myStore", JSON.stringify(snapshot));++// Restore+const saved = JSON.parse(localStorage.getItem("myStore"));+loadState(store, saved);+```++---++## 4. Lifecycle Management++### Custom Alpine Directives++Registered in `/js/initFw.js`:++| Directive | When Fires | Use Case |+|-----------|------------|----------|+| `x-create` | Once on mount | Initialize, subscribe to events |+| `x-destroy` | On unmount/cleanup | Unsubscribe, clear timers |+| `x-every-second` | Every 1s while mounted | Polling, countdowns |+| `x-every-minute` | Every 60s while mounted | Low-frequency updates |+| `x-every-hour` | Every 3600s while mounted | Rare periodic tasks |++### Usage Pattern++```html+<div+ x-create="$store.myStore.onOpen()"+ x-destroy="$store.myStore.cleanup()"+>+ <!-- content -->+</div>+```++### Store Lifecycle Pattern++```javascript+const model = {+ _initialized: false,+ resizeHandler: null,++ init() {+ // Guard: runs only once per app lifetime+ if (this._initialized) return;+ this._initialized = true;+ // Global setup: event listeners, intervals+ this.resizeHandler = () => this.handleResize();+ window.addEventListener("resize", this.resizeHandler);+ },++ // Called via x-create when component mounts (can run multiple times)+ onOpen() {+ this.loadData();+ },++ // Called via x-destroy when component unmounts+ cleanup() {+ // Clear component-specific state, not global listeners+ },++ // For full teardown (rarely needed)+ destroy() {+ if (this.resizeHandler) {+ window.removeEventListener("resize", this.resizeHandler);+ this.resizeHandler = null;+ }+ this._initialized = false;+ }+};+```++**Key distinction:**+- `init()` → once per app load (store registration)+- `onOpen()` → each time component mounts (modal opens, etc.)+- `cleanup()`/`destroy()` → teardown resources++---++## 5. Integration Layer++### API Calls++```javascript+import { callJsonApi, fetchApi } from "/js/api.js";++// JSON POST with CSRF+const result = await callJsonApi("/endpoint", { key: "value" });++// Raw fetch with CSRF+const response = await fetchApi("/endpoint", {+ method: "GET",+ headers: { "Accept": "application/json" }+});+```++- `callJsonApi`: JSON-in, JSON-out, throws on non-2xx+- `fetchApi`: Adds CSRF header, handles 403 retry, redirects to `/login`++### Modals++```javascript+import { openModal, closeModal } from "/js/modals.js";++// Open (returns Promise that resolves when modal closes)+await openModal("feature/feature-modal.html");++// Close topmost modal+closeModal();++// Close specific modal by path+closeModal("feature/feature-modal.html");+```++Modal component receives title from `<title>` tag:+```html+<head>+ <title>My Modal Title</title>+</head>+```++Modal footer (outside scroll area):+```html+<div data-modal-footer>+ <button @click="closeModal()">Close</button>+</div>+```++### Attribute Inheritance++Parent `x-component` attributes accessible via `globalThis.xAttrs(element)`:++```html+<!-- Parent -->+<x-component path="child.html" mydata='{"id": 123}'></x-component>++<!-- Child can access -->+<script type="module">+ const attrs = globalThis.xAttrs(document.currentScript);+ console.log(attrs.mydata.id); // 123+</script>+```++---++## 6. Alpine.js Directives++### Common Patterns++| Pattern | Syntax |+|---------|--------|+| Reactive text | `x-text="$store.s.value"` |+| Conditional render | `x-if="$store.s.condition"` |+| Visibility toggle | `x-show="$store.s.visible"` |+| Class binding | `:class="{'active': $store.s.isActive}"` |+| Event handler | `@click="$store.s.action()"` |+| Two-way bind | `x-model="$store.s.inputValue"` |+| List iteration | `<template x-for="item in $store.s.items">` |+| Init expression | `x-init="$store.s.load()"` |++### Store Gating (Critical Pattern)++```html+<div x-data>+ <template x-if="$store.myStore">+ <!-- Renders only when store exists -->+ </template>+</div>+```++**Always gate components that depend on stores.** Prevents errors during initial load race.++---++## 7. Patterns and Conventions++### ✅ DO++| Pattern | Example |+|---------|---------|+| Self-contained components | All HTML/CSS/JS in one component folder |+| Module imports with absolute paths | `import { store } from "/components/..."` |+| CSS variables for theming | `color: var(--color-text)` |+| Guard `init()` with `_initialized` | Prevents duplicate setup |+| Use `display: contents` for flex chains | Wrapper doesn't break parent flex |+| Inline component styles | `<style>` in component `<body>` |+| Import stores in `<head>` | Ensures registration before render |+| Name stores uniquely | `createStore("featureStore", ...)` |++### CSS Variable Theming++```css+.component {+ background: var(--color-panel);+ color: var(--color-text);+ border: 1px solid var(--color-border);+ padding: var(--spacing-md);+ transition: all var(--transition-speed) ease-in-out;+ font-size: var(--font-size-normal);+}+```++### Flex Chain Preservation++When `x-component` wrapper would break flex layout:++```css+#parent-container > x-component,+#parent-container > x-component > div[x-data] {+ display: contents;+}+```++---++## 8. Pitfalls and Anti-Patterns++### 🚫 DON'T++| Anti-Pattern | Why | Fix |+|--------------|-----|-----|+| Global CSS files | Breaks encapsulation | Inline styles per component |+| `window.Alpine.store()` lookups | Timing issues, coupling | Import store module directly |+| Call `init()` from `x-init` | Runs multiple times | Use guard, or use `x-create` for per-mount |+| Multiple roots in `<template>` | Alpine breaks | Wrap in single `<div>` |+| `.catch(() => null)` for errors | Hides bugs | Let errors surface, use notifications |+| Scripts outside `<head>` | May not load before template | Move to `<head>` with `type="module"` |+| Hardcoded colors | Breaks theming | Use CSS variables |+| Relative imports `./file.js` | Path resolution issues | Use absolute `/components/...` |++### Common Mistakes++**Race condition: store not ready**+```html+<!-- ❌ BAD: No gate -->+<div x-data>+ <p x-text="$store.myStore.value"></p>+</div>++<!-- ✅ GOOD: Store gate -->+<div x-data>+ <template x-if="$store.myStore">+ <p x-text="$store.myStore.value"></p>+ </template>+</div>+```++**Duplicate initialization**+```javascript+// ❌ BAD: Runs every time store accessed+init() {+ window.addEventListener("resize", this.handler);+}++// ✅ GOOD: Guard pattern+init() {+ if (this._initialized) return;+ this._initialized = true;+ window.addEventListener("resize", this.handler);+}+```++**Leaking listeners**+```javascript+// ❌ BAD: No cleanup+init() {+ this.interval = setInterval(() => this.tick(), 1000);+}++// ✅ GOOD: With cleanup+init() {+ this.interval = setInterval(() => this.tick(), 1000);+},+destroy() {+ clearInterval(this.interval);+}+```++---++## 9. Porting Guide++### Minimum Requirements for External Apps++1. **Files to copy:**+ ```+ /js/components.js # Component loader+ /js/AlpineStore.js # Store factory+ /js/modals.js # Modal system (optional)+ /js/initFw.js # Alpine bootstrap + directives+ ```++2. **Dependencies:**+ - Alpine.js (vendor or CDN)+ - CSS variables (define your theme)++3. **Bootstrap sequence:**+ ```javascript+ // initFw.js pattern:+ await import("path/to/alpine.min.js");++ // Register custom directives+ Alpine.directive("destroy", ...);+ Alpine.directive("create", ...);+ // etc.+ ```++4. **HTML entry point:**+ ```html+ <script type="module" src="/js/initFw.js"></script>+ <x-component path="app/root.html"></x-component>+ ```++### Adaptation Checklist++- [ ] Define CSS variables for theming (`--color-*`, `--spacing-*`, etc.)+- [ ] Set up component directory structure+- [ ] Configure build tool to serve `/components/` path (or adjust loader)+- [ ] Create API wrapper matching your backend (replace `api.js`)+- [ ] Test MutationObserver behavior with your router/SPA framework+- [ ] Verify module caching behavior in production build++### Integration with Frameworks++| Framework | Consideration |+|-----------|--------------|+| **Vanilla/Static** | Works directly, include initFw.js |+| **Electron** | Works, may need CSP adjustments for Blob URLs |+| **React/Vue** | Mount Alpine in specific container, avoid conflicts |+| **SPA Routers** | MutationObserver handles dynamic inserts |++---++## Directory Structure Reference++```+webui/components/+├── _examples/ # Reference implementations+│ ├── _example-component.html+│ └── _example-store.js+├── chat/+│ ├── input/+│ │ ├── chat-bar.html+│ │ └── input-store.js+│ └── ...+├── sidebar/+│ ├── sidebar-store.js+│ ├── left-sidebar.html+│ └── chats/+│ └── chats-list.html+├── modals/+│ └── file-browser/+│ ├── file-browser.html+│ └── file-browser-store.js+├── notifications/+│ ├── notification-store.js+│ └── notification-toast-stack.html+└── settings/+ └── ...+```++**Naming conventions:**+- Components: `feature-name.html`+- Stores: `feature-store.js` or `feature-name-store.js`+- Modals: placed in `modals/` or feature folder++---++## Key Exports Summary++### `/js/components.js`+```javascript+export async function importComponent(path, targetElement)+export async function loadComponents(roots)+export function getParentAttributes(el)+// Global: globalThis.xAttrs+```++### `/js/AlpineStore.js`+```javascript+export function createStore(name, initialState)+export function getStore(name)+export function saveState(store, include, exclude)+export function loadState(store, state, include, exclude)+```++### `/js/modals.js`+```javascript+export function openModal(modalPath)+export function closeModal(modalPath?)+export function scrollModal(id)+// Globals: globalThis.openModal, closeModal, scrollModal+```++### `/js/api.js`+```javascript+export async function callJsonApi(endpoint, data)+export async function fetchApi(url, request)+```++---++## Addendum: Additional Patterns++### Alpine Transitions++Use `x-transition` for enter/leave animations:++```html+<div x-show="visible"+ x-transition:enter="fade-enter"+ x-transition:leave="fade-leave">+```++### Two-Click Confirmation (`$confirmClick`)++Magic helper for destructive actions:++```html+<button @click="$confirmClick($event, () => $store.myStore.delete(item.id))">+ <span class="material-symbols-outlined">delete</span>+</button>+```++First click arms (icon changes to checkmark), second click confirms. Auto-resets after 2s.++### Device Detection++Body receives `device-touch` or `device-mouse` class via `/js/initializer.js`. Use for input-type-specific styling:++```css+.device-touch .hover-only { display: none; }+```++### CSS Variables Reference++Defined in `/webui/index.css`:++| Variable | Purpose |+|----------|---------|+| `--color-background` | Page background |+| `--color-text` | Primary text |+| `--color-primary` | Headings, emphasis |+| `--color-panel` | Card/sidebar backgrounds |+| `--color-border` | Borders, dividers |+| `--color-accent` | Highlights, actions |+| `--color-input` | Form field backgrounds |+| `--spacing-xs/sm/md/lg` | Consistent spacing scale |+| `--font-size-small/normal/large` | Typography scale |+| `--transition-speed` | Animation duration (0.3s) |++Theme switching via `.light-mode` class on root element.++---++*End of Component System Documentation*diff --git a/docs/agents/AGENTS.modals.md b/docs/agents/AGENTS.modals.mdnew file mode 100644index 000000000..86fd4a5fa--- /dev/null+++ b/docs/agents/AGENTS.modals.md@@ -0,0 +1,307 @@+# Agent Zero — Frontend Modals (stacked `openModal/closeModal`)++This document covers the stacked modal system used by Agent Zero’s frontend, implemented in:++- `webui/js/modals.js`+- `webui/css/modals.css`++It also defines conventions for writing modal components in `webui/components/modals/` and `webui/components/settings/`.++> Legacy note: there is an older overlay / teleport modal style in the codebase (e.g. `x-teleport` + `.modal-overlay`). Avoid it for new work. This doc is about the stacked modal system.++---++## Prerequisites & concepts (quick orientation)++### Alpine.js and `$store`++The UI uses Alpine.js for reactivity (`x-show`, `x-if`, `x-on`, `x-model`, …). Stores are registered via `createStore()` and read in HTML via `$store.<storeName>`.++- Alpine initialization + lifecycle directives: `webui/js/initFw.js`+- Store wrapper: `webui/js/AlpineStore.js`++### `<x-component>` and `importComponent()`++Agent Zero uses a custom `<x-component path="...">` tag that is populated by the component loader.++The modal system does not rely on `<x-component>` directly; instead it calls the same loader function:++- `importComponent(path, targetElement)` from `webui/js/components.js`++That loader fetches component HTML, injects its `<style>` and `<script>` tags, and supports nested components.++---++## Why a “stacked modal system”?++Agent Zero can open modals from many places (sidebar, settings, message actions), and sometimes a modal opens another modal.++The stacked system provides:++- A single modal container structure for consistent UI+- A stack so nested modals work predictably+- A single backdrop that always sits behind the active modal+- A content loader that supports component HTML + `<style>` + `<script type="module">` the same way `<x-component>` does++---++## Core API++File: `webui/js/modals.js`++### `openModal(modalPath): Promise<void>`++- Creates a new modal element and pushes it onto a stack.+- Loads modal contents into the modal body by calling the component loader (`importComponent`).+- Resolves the returned promise when the modal element is removed from the DOM.++Edge cases / failure behavior (current implementation):++- Invalid `modalPath` does not reject the returned promise. Instead, the modal remains open and shows an error message inside the modal body; the promise still resolves when the user closes the modal.+- Calling `openModal()` multiple times with the same `modalPath` creates multiple modal instances (no deduping).++Modal paths are component paths, e.g.:++- `modals/file-browser/file-browser.html`+- `modals/history/history.html`+- `settings/settings.html`++### `closeModal(modalPath?: string): void`++- If no path is passed, closes the top modal.+- If `modalPath` is passed, finds and closes that modal in the stack.++Edge cases / failure behavior:++- If the stack is empty, `closeModal()` is a no-op.+- If `modalPath` is provided but not found, it is a no-op.++### `scrollModal(id: string): void`++Scrolls within the top modal’s `.modal-scroll` to an element by id.++---++## Modal DOM structure (what `modals.js` creates)++When `openModal()` runs, it creates this outer shell:++- `.modal` (full-screen fixed overlay container)+ - `.modal-inner`+ - `.modal-header` (title + close button)+ - `.modal-scroll`+ - `.modal-bd` (where the component HTML is imported)+ - `.modal-footer-slot` (used when the modal provides a footer)++The component HTML is imported into `.modal-bd`.++The title is taken from `<title>` inside the imported document (fallback: the modalPath).++### Sizing and scrolling (CSS behavior)++File: `webui/css/modals.css`++- `.modal` is full-screen fixed positioning.+- `.modal-inner` is centered and constrained:+ - `width: 90%`+ - `max-width: 960px`+ - `max-height: 90vh`+- Tall modals scroll inside `.modal-scroll` (`overflow-y: auto`).+- If the modal provides a footer, `.modal-footer-slot` is pinned under the scroll area (the body scrolls; the footer doesn’t).++---++## Footer support (`data-modal-footer`)++Some modals want a footer that stays fixed while the body scrolls.++Pattern:++- In your modal component HTML, include a footer element marked with `data-modal-footer`.+- `modals.js` will move that element out of the scroll area and into `.modal-footer-slot`.+- `modals.js` adds `.modal-with-footer` to `.modal-inner` so CSS can lay out the scroll area correctly.++Example patterns in the repo:++- `webui/components/settings/settings.html` (Save / Cancel footer)+- `webui/components/modals/file-browser/file-browser.html`+- `webui/components/modals/scheduler/scheduler-modal.html`++### Practical advice++- The footer element must exist *after the component is loaded*, but `modals.js` uses a `requestAnimationFrame` to let Alpine mount first.+- If you conditionally render the footer, keep it stable (don't constantly create/destroy it) or you'll fight the relocation.++---++## Shared CSS and button conventions++File: `webui/css/modals.css`++Modals should reuse shared CSS classes rather than redefining common styles. The modal system provides base classes for buttons, footers, and layout that work consistently across all modals.++### Button classes++Use these standard button classes for modal actions:++| Class | Use case | Visual style |+|-------|----------|--------------|+| `btn btn-ok` | Positive/confirmatory actions (Save, Create, Confirm) | Solid blue background, white text |+| `btn btn-cancel` | Dismissive/negative actions (Cancel, Close, Delete) | Transparent with accent border |++Footer button order convention: **positive action first** (left), **negative action second** (right).++Example footer markup:++```html+<div class="modal-footer" data-modal-footer>+ <button class="btn btn-ok" @click="$store.myStore.save()">Save</button>+ <button class="btn btn-cancel" @click="window.closeModal('...')">Cancel</button>+</div>+```++### Available shared classes++Before writing component-specific CSS, check `webui/css/modals.css` for:++- `.btn`, `.btn-ok`, `.btn-cancel`, `.btn-field` — button styles+- `.modal-footer` — footer container layout+- `.section`, `.section-title`, `.section-description` — content sections+- `.loading` — shimmer loading placeholder+- `.toolbar-button`, `.toolbar-group` — editor toolbar elements+- Range input styling for sliders++### When to add component-specific CSS++Add styles in your component's `<style>` tag only when:++- The style is truly unique to that component's layout/behavior+- No existing shared class covers the use case+- You need to override a shared class for a specific context (use sparingly)++Avoid redefining `.btn`, `.modal-footer`, or other shared classes in component CSS—this creates inconsistency and maintenance burden.++---++## Closing behavior (what users expect)++### Close by button++The shell provides a close button (`.modal-close`) that always closes the top modal.++### Close by Escape++`Escape` closes the top modal only (stack semantics).++### Close by click-outside++To avoid accidental close during drag/select, the shell only closes on click-outside when:++- both `mousedown` and `mouseup` occurred on the modal container itself (`.modal`), not on inner content.++---++## Stacking + backdrop + z-index++File: `webui/js/modals.js`++- A single `.modal-backdrop` is used for all modals.+- Z-index logic:+ - Base z-index for modals is `3000`+ - Each modal gets `base + index*20`+ - Backdrop sits below the top modal, and between the top two when multiple modals are open.++Outcome:++- Nested modals don’t “flatten” into each other.+- The backdrop always darkens the page behind the active modal without hiding lower modals incorrectly.++---++## Writing a modal component (conventions)++### File location++Prefer:++- `webui/components/modals/<name>/<name>.html` (+ optional `*-store.js`)++Settings uses:++- `webui/components/settings/settings.html` and nested settings components.++### Recommended HTML skeleton++Use this structure:++- `<head><title>...</title>`+- A `<script type="module">` that imports your store (so it registers before Alpine evaluates bindings)+- `<body>` with:+ - a single root wrapper+ - Alpine lifecycle hooks (`x-create`/`x-init` + `x-destroy`) to run open/cleanup logic+- A `<style>` tag at the bottom of the component file containing all modal-specific styling++Good examples:++- `webui/components/modals/history/history.html`+- `webui/components/modals/context/context.html`+- `webui/components/modals/scheduler/scheduler-modal.html`++### Store conventions++- Define stores via `createStore()` from `webui/js/AlpineStore.js`.+- UI reads state through `$store.<storeName>`.+- Prefer a small public API:+ - `open()` / `openModal()` to open the modal+ - `destroy()` / `cleanup()` to reset transient state++---++## “Don’t” list (keeps the system sane)++- Don’t add `document.addEventListener('alpine:init', ...)` blocks inside component HTML — it conflicts with `initFw.js` ordering and can register handlers twice when components are reloaded.+- Don’t manually manipulate `.modal-inner` or `.modal-scroll` structure — `modals.js` owns the shell and footer-slot mechanics; manual changes create layout/scroll bugs.+- Don’t introduce a new modal overlay system; keep the stack, mixed systems break z-index/backdrop expectations and make nested modals unreliable.+- Don’t assume a modal is the only one open; always write logic that behaves correctly when stacked — `Escape`/close behavior, z-index, and focus should all be “top modal wins”.+- Don’t open a new modal synchronously from another modal’s close handler — it can race stack removal and produce transient z-index/backdrop glitches; schedule via `requestAnimationFrame` if needed.+- Don’t store sensitive data in modal stores without explicit cleanup — stores often outlive a modal’s DOM and can leak values across reopen.+- Don’t rely on modal state persisting across close/reopen cycles — design stores so `open()` rehydrates and `destroy()`/`cleanup()` resets transient state.++---++## Debugging checklist++### Modal opens but content never appears++- Verify the path passed to `openModal()` is correct and resolves under `webui/components/`.+- Check browser console for fetch/import errors.+- If you use `<script type="module" src="...">` in the component, ensure the URL is correct.++### Footer is inside the scroll area (not pinned)++- Ensure your footer element has the `data-modal-footer` attribute.+- Ensure it exists after the component loads (if you gate it behind `x-if`, ensure the store is available).++### Closing behavior is weird with nested modals++- Remember `Escape` closes only the top modal.+- `closeModal('some/path.html')` closes that modal wherever it is in the stack.++### Modal opens but `$store.someStore` is undefined++- Ensure the modal HTML imports its store in a `<script type="module">` block (so the store registers before Alpine evaluates bindings).+- Ensure the store name matches what the markup reads (store registered as `createStore("history", ...)` is accessed as `$store.history`).+- If you guard with `<template x-if="$store.someStore">`, verify you’re using the correct store key and not a stale name.++### Modal won’t close / UI feels “stuck”++- `closeModal()` removes the modal element immediately; if your store keeps polling or timers alive, the UI may still feel active—ensure you have `x-destroy` cleanup (`destroy()`/`cleanup()`).+- As a last resort, inspect and remove leftover modal nodes in DevTools (`document.querySelectorAll('.modal').forEach(m => m.remove())`) and reset any store state that assumes the modal is open.++### Inspecting stack/z-index issues++- In DevTools Elements:+ - inspect `.modal` elements (multiple means you have a stack)+ - check the `style="z-index: ..."` on `.modal-inner`+ - verify `.modal-backdrop` exists and sits between modals when stacked+- If the footer is not pinned, confirm your footer element has `data-modal-footer` and that `.modal-inner` has `.modal-with-footer`.diff --git a/plugins/README.md b/plugins/README.mdindex 8b7c84344..8871736c2 100644--- a/plugins/README.md+++ b/plugins/README.md@@ -1,6 +1,9 @@# Agent Zero Plugins-This directory contains default plugins shipped with Agent Zero and is the source of truth for the plugin system.+This directory contains default plugins. For a full-stack development guide, see [docs/AGENTS.md](../docs/AGENTS.md).++> [!TIP]+> While Agent Zero looks for plugins in both `usr/plugins/` and `plugins/`, you should **always develop new plugins in `usr/plugins/`**. This ensures your work is isolated from core system files and persists through framework updates.## Architecture@@ -38,8 +41,9 @@ Agent Zero uses a convention-over-configuration plugin model:## File Structure```text-plugins/- <plugin_id>/+usr/plugins/+ <plugin_name>/+ plugin.json # Required manifest (enables discovery)api/ # API handlers (ApiHandler subclasses)tools/ # Agent tools (Tool subclasses)helpers/ # Shared Python helpers@@ -48,26 +52,41 @@ plugins/extensions/python/<extension_point>/ # Python lifecycle extensionswebui/<extension_point>/ # WebUI HTML/JS hook contributions- webui/ # Full plugin-owned UI pages/components--usr/plugins/<plugin_id>/ # User overrides (higher priority)+ webui/+ settings.html # Optional: plugin settings UI+ ... # Full plugin-owned UI pages/components```## Directory Conventions-Each plugin lives in `plugins/<plugin_id>/` (or `usr/plugins/<plugin_id>/` for overrides).+Each plugin lives in `usr/plugins/<plugin_name>/`.Capability discovery is based on these paths:-- `api/*.py` - API handlers (`ApiHandler` subclasses), exposed under `/api/plugins/<plugin_id>/<handler>`+- `plugin.json` - **required** manifest; a directory without it is not recognized as a plugin+- `api/*.py` - API handlers (`ApiHandler` subclasses), exposed under `/api/plugins/<plugin_name>/<handler>`- `tools/*.py` - agent tools (`Tool` subclasses)- `helpers/*.py` - shared Python helpers- `extensions/python/<extension_point>/*.py` - backend lifecycle extensions- `extensions/webui/<extension_point>/*` - WebUI extension assets (HTML/JS)- `webui/**` - full plugin-owned UI pages/components (loaded directly by path)+- `webui/settings.html` - if present, a Settings button appears for this plugin in the relevant settings tabs- `prompts/**/*.md` - prompt templates- `agents/` - agent profiles+### `plugin.json` format++```json+{+ "name": "My Plugin",+ "description": "What this plugin does.",+ "version": "1.0.0",+ "settings_sections": ["agent"]+}+```++`settings_sections` controls which Settings tabs show a subsection for this plugin. Current valid values: `agent`, `external`, `mcp`, `developer`, `backup`. Leave empty (`[]`) for no subsection.+## Frontend Extensions### HTML insertion via breakpoints@@ -78,57 +97,6 @@ Core UI defines insertion points like:<x-extension id="sidebar-quick-actions-main-start"></x-extension>```-Current sidebar surfaces:--- `sidebar-start`-- `sidebar-end`-- `sidebar-top-wrapper-start`-- `sidebar-top-wrapper-end`-- `sidebar-quick-actions-main-start`-- `sidebar-quick-actions-main-end`-- `sidebar-quick-actions-dropdown-start`-- `sidebar-quick-actions-dropdown-end`-- `sidebar-chats-list-start`-- `sidebar-chats-list-end`-- `sidebar-tasks-list-start`-- `sidebar-tasks-list-end`-- `sidebar-bottom-wrapper-start`-- `sidebar-bottom-wrapper-end`--Current input surfaces:--- `chat-input-start`-- `chat-input-end`-- `chat-input-progress-start`-- `chat-input-progress-end`-- `chat-input-box-start`-- `chat-input-box-end`-- `chat-input-bottom-actions-start`-- `chat-input-bottom-actions-end`--Current chat surfaces:--- `chat-top-start`-- `chat-top-end`--Current welcome surfaces:--- `welcome-screen-start`-- `welcome-screen-end`-- `welcome-actions-start`-- `welcome-actions-end`-- `welcome-banners-start`-- `welcome-banners-end`--Current modal surfaces:--- `modal-shell-start`-- `modal-shell-end`--Placement pattern:-- keep wrapper-level anchors in parent composition files-- keep section anchors in their owning component files, inside local `x-data` scope-Resolution flow:1. `webui/js/extensions.js` finds `x-extension` nodes.@@ -137,21 +105,6 @@ Resolution flow:4. `extensions.js` injects returned entries as `<x-component path="...">`.5. `components.js` loads each component using the standard component pipeline.-Baseline extension template (project convention):--```html-<div x-data>- <button- x-move-after=".config-button#dashboard"- class="config-button"- id="my-plugin-button"- @click="openModal('../plugins/my-plugin/webui/my-modal.html')"- title="My Plugin">- <span class="material-symbols-outlined">extension</span>- </button>-</div>-```-Required baseline for HTML UI extensions in this repository:- include a root `x-data` scope- include one explicit `x-move-*` placement directive@@ -166,22 +119,6 @@ Runtime code calls:`callJsExtensions("<extension_point>", contextObject)`-JS hook convention:-- pass one mutable context object when extensions are expected to influence behavior-- that object is passed by reference, so mutations are visible to subsequent hooks in the same flow-- hooks that support cancellation expose a `cancel: false` or `skip: false` field; set it to `true` to abort the operation--Current JS hook points:--| Hook | File | Context fields | skip/cancel |-|---|---|---|---|-| `set_messages_before_loop` | messages.js | `messages, history, scrollerOptions, massRender, results` | - |-| `set_messages_after_loop` | messages.js | same as above | - |-| `send_message_before` | index.js | `message, attachments, context, cancel` | `cancel` |-| `apply_snapshot_before` | index.js | `snapshot, willUpdateMessages, skip` | `skip` |-| `open_modal_before` | modals.js | `modalPath, modal, cancel` | `cancel` |-| `close_modal_before` | modals.js | `modalPath, modal, cancel` | `cancel` |-### Fine placement helpers`initFw.js` provides Alpine move directives for plugin markup:@@ -192,75 +129,71 @@ Current JS hook points:- `x-move-before`- `x-move-after`-Placement behavior:-- `x-move-to-start`, `x-move-to-end`, and `x-move-to` resolve a parent selector and insert the extension element as that parent's child.-- `x-move-before` and `x-move-after` resolve a reference selector and insert the extension element as a sibling in the reference element's parent.-- This structural difference can produce different visual results when parent and sibling styling differ (for example dropdown spacing/padding).-- Example anchor selector for placing after the first dropdown item: `x-move-after=".quick-actions-dropdown .dropdown-header + .dropdown-item"`.--## Plugin Author Flow--1. Create `plugins/<plugin_id>/`.-2. Add backend capabilities by convention (`api/`, `tools/`, `helpers/`, `extensions/python/`, `prompts/`, `agents/`).-3. Pick a WebUI breakpoint or JS hook extension point.-4. For HTML UI entries: place files under `extensions/webui/<extension_point>/`, use root `x-data` + one `x-move-*` directive.-5. For JS hooks: place `*.js` files under `extensions/webui/<extension_point>/`, export a default async function.-6. Place full plugin pages/components in `webui/` and open them directly by path.+## Plugin Settings-### Python extension example+If your plugin needs user-configurable settings:-```python-# plugins/my-plugin/extensions/python/monologue_end/_50_my_extension.py-from python.helpers.extension import Extension+1. Add `webui/settings.html` to your plugin. The system detects this file automatically.+2. Declare which settings tabs should show a subsection for your plugin via `settings_sections` in `plugin.json`.+3. The plugin settings modal provides **Project** and **Agent profile** context selectors (same as the Skills list). Settings are scoped per-project and per-agent.-class MyExtension(Extension):- async def execute(self, **kwargs):- pass-```+### Settings HTML contract-### HTML WebUI extension example+Your `settings.html` receives context from `$store.pluginSettings`:```html-<!-- plugins/my-plugin/extensions/webui/sidebar-quick-actions-main-start/my-button.html -->-<div x-data>- <button- x-move-after=".config-button#dashboard"- class="config-button"- id="my-plugin-button"- @click="openModal('../plugins/my-plugin/webui/my-modal.html')"- title="My Plugin">- <span class="material-symbols-outlined">extension</span>- </button>-</div>+<html>+<head>+ <title>My Plugin Settings</title>+ <script type="module">+ import { store } from "/components/plugins/plugin-settings-store.js";+ </script>+</head>+<body>+ <div x-data>+ <!-- bind fields to $store.pluginSettings.settings -->+ <input x-model="$store.pluginSettings.settings.my_key" />+ </div>+</body>+</html>```-### JS hook example+- `$store.pluginSettings.settings` - plain object loaded from `settings.json`, save-scoped to the selected project/agent.+- The modal's **Save** button calls `POST /plugins` (`action: save_settings`) automatically.+- For plugins that surface **core settings** (like memory), set `saveMode = 'core'` in `x-init` so Save delegates to the core settings API instead.-```js-// plugins/my-plugin/extensions/webui/send_message_before/transform.js-export default async function(ctx) {- // prepend a tag to every outgoing message- ctx.message = "[my-plugin] " + ctx.message;-}+### Settings resolution priority (highest first)++```+project/.a0proj/agents/<profile>/plugins/<name>/settings.json+project/.a0proj/plugins/<name>/settings.json+usr/agents/<profile>/plugins/<name>/settings.json+agents/<profile>/plugins/<name>/settings.json+usr/plugins/<name>/settings.json+plugins/<name>/settings.json```-### Full plugin UI page+## Plugin Author Flow-```html-<!-- opened via openModal() or x-component -->-<x-component path="../plugins/my-plugin/webui/my-modal.html"></x-component>-```+1. Create `usr/plugins/<plugin_name>/`.+2. Add `plugin.json` manifest (required for discovery).+3. Add backend capabilities by convention (`api/`, `tools/`, `helpers/`, `extensions/python/`, `prompts/`, `agents/`).+4. Pick a WebUI breakpoint or JS hook extension point.+5. For HTML UI entries: place files under `extensions/webui/<extension_point>/`, use root `x-data` + one `x-move-*` directive.+6. For JS hooks: place `*.js` files under `extensions/webui/<extension_point>/`, export a default async function.+7. Place full plugin pages/components in `webui/` and open them directly by path.+8. Optionally add `webui/settings.html` and set `settings_sections` in `plugin.json` to expose settings in the UI.## Routes-- Plugin static assets: `GET /plugins/<plugin_id>/<path>`-- Plugin APIs: `POST /api/plugins/<plugin_id>/<handler>`+- Plugin static assets: `GET /plugins/<plugin_name>/<path>`+- Plugin APIs: `POST /api/plugins/<plugin_name>/<handler>`- WebUI extension discovery: `POST /api/load_webui_extensions`+- Plugin management (list, get/save settings): `POST /plugins`## Notes- User plugins in `usr/plugins/` override repo plugins by plugin ID.- Runtime behavior is fully convention-driven from directory structure.- Extension point ordering between multiple plugins is currently implicit (filesystem order).-- Project-specific plugin roots are not yet active (commented out in `get_plugin_roots()`).- When you need a new extension point for your plugin, submit a PR - we are actively expanding coverage based on community needs.diff --git a/plugins/example_agent/plugin.json b/plugins/example_agent/plugin.jsonindex ac6b7e8cb..a3e026759 100644--- a/plugins/example_agent/plugin.json+++ b/plugins/example_agent/plugin.json@@ -2,4 +2,9 @@"description": "Example Agent Plugin","per_project_config": true,"per_agent_config": false+}+ "name": "Example Agent",+ "description": "Example agent plugin demonstrating the Agent Zero plugin system.",+ "version": "1.0.0",+ "settings_sections": []}diff --git a/plugins/memory/plugin.json b/plugins/memory/plugin.jsonindex 80df3e357..e0e205bf3 100644--- a/plugins/memory/plugin.json+++ b/plugins/memory/plugin.json@@ -2,4 +2,9 @@"description": "Memory Plugin","per_project_config": true,"per_agent_config": true-}\ No newline at end of file+}+ "name": "Memory",+ "description": "Provides persistent memory capabilities to Agent Zero agents.",+ "version": "1.0.0",+ "settings_sections": ["agent"]+}diff --git a/plugins/memory/webui/settings.html b/plugins/memory/webui/settings.htmlnew file mode 100644index 000000000..a9310d822--- /dev/null+++ b/plugins/memory/webui/settings.html@@ -0,0 +1,21 @@+<html>+<head>+ <title>Memory Settings</title>+ <script type="module">+ import { store } from "/components/settings/settings-store.js";+ </script>+</head>+<body>+ <!--+ This file surfaces the existing core memory settings inside the plugin settings modal.+ It sets saveMode='core' so the modal's Save button delegates to $store.settings.saveSettings().+ -->+ <div x-data+ x-init="+ $store.pluginSettings.saveMode = 'core';+ if ($store.settings && !$store.settings.settings) $store.settings.onOpen();+ ">+ <x-component path="settings/agent/memory.html"></x-component>+ </div>+</body>+</html>diff --git a/python/api/plugins.py b/python/api/plugins.pynew file mode 100644index 000000000..0f9a66adb--- /dev/null+++ b/python/api/plugins.py@@ -0,0 +1,40 @@+from python.helpers.api import ApiHandler, Request, Response+from python.helpers import plugins+++class Plugins(ApiHandler):+ """+ Core plugin management API.+ Actions: list, get_settings, save_settings+ """++ async def process(self, input: dict, request: Request) -> dict | Response:+ action = input.get("action", "list")++ if action == "list":+ tab = input.get("tab") # optional: filter by settings_tab+ data = plugins.list_plugins_with_metadata(tab_filter=tab or None)+ return {"ok": True, "data": data}++ if action == "get_settings":+ plugin_name = input.get("plugin_name", "")+ project_name = input.get("project_name", "")+ agent_profile = input.get("agent_profile", "")+ if not plugin_name:+ return Response(status=400, response="Missing plugin_name")+ settings = plugins.get_plugin_settings(plugin_name,+ project_name=project_name,+ agent_profile=agent_profile)+ return {"ok": True, "data": settings or {}}++ if action == "save_settings":+ plugin_name = input.get("plugin_name", "")+ project_name = input.get("project_name", "")+ agent_profile = input.get("agent_profile", "")+ settings = input.get("settings", {})+ if not plugin_name:+ return Response(status=400, response="Missing plugin_name")+ plugins.save_plugin_settings(plugin_name, project_name, agent_profile, settings)+ return {"ok": True}++ return Response(status=400, response=f"Unknown action: {action}")diff --git a/run_ui.py b/run_ui.pyindex c4f01020a..cbc340f40 100644--- a/run_ui.py+++ b/run_ui.py@@ -11,7 +11,7 @@ import asynciofrom pathlib import Pathimport urllib.requestimport urllib.error-from regex.regex import F+from regex import Fimport uvicornfrom flask import Flask, request, Response, session, redirect, url_for, render_template_stringfrom werkzeug.wrappers.response import Response as BaseResponsediff --git a/skills/a0-create-plugin/SKILL.md b/skills/a0-create-plugin/SKILL.mdnew file mode 100644index 000000000..79a501c85--- /dev/null+++ b/skills/a0-create-plugin/SKILL.md@@ -0,0 +1,149 @@+---+name: a0-create-plugin+description: Create, extend, or modify Agent Zero plugins. Follows strict full-stack conventions (usr/plugins, plugin.json, Store Gating, AgentContext, plugin settings). Use for UI hooks, API handlers, lifecycle extensions, or plugin settings UI.+---++# Agent Zero Plugin Development++> [!IMPORTANT]+> **Always create new plugins in `usr/plugins/<plugin_name>/`.** The root `/plugins` directory is reserved for core system plugins.++Primary references:+- `/a0/AGENTS.md` (Full-stack architecture & AgentContext)+- `/a0/docs/agents/AGENTS.components.md` (Component system deep dive)+- `/a0/docs/agents/AGENTS.modals.md` (Modal system & CSS conventions)+- `/a0/plugins/README.md` (Extension points, plugin.json, settings system)++## 📋 Plugin Manifest (`plugin.json`)++Every plugin **must** have a `plugin.json` or it will not be discovered:++```json+{+ "name": "My Plugin",+ "description": "What this plugin does.",+ "version": "1.0.0",+ "settings_sections": ["agent"]+}+```++`settings_sections` controls which Settings tabs show a subsection for this plugin. Valid values: `agent`, `external`, `mcp`, `developer`, `backup`. Use `[]` for no subsection.++## 🛠️ Mandatory Frontend Patterns++### 1. The "Store Gate" Template+To avoid race conditions and "undefined" errors, every component must use this wrapper:+```html+<div x-data>+ <template x-if="$store.myPluginStore">+ <div x-init="$store.myPluginStore.onOpen()" x-destroy="$store.myPluginStore.cleanup()">+ <!-- Content goes here -->+ </div>+ </template>+</div>+```++### 2. Separate Store Module+Place store logic in a separate `.js` file. Do NOT use `alpine:init` listeners inside HTML.+```javascript+// webui/my-store.js+import { createStore } from "/js/AlpineStore.js";+export const store = createStore("myPluginStore", {+ status: 'idle',+ init() { ... },+ onOpen() { ... }+});+```+Import it in the HTML `<head>`:+```html+<head>+ <script type="module" src="/plugins/<plugin_name>/webui/my-store.js"></script>+</head>+```++## ⚙️ Plugin Settings++If your plugin needs user-configurable settings, add `webui/settings.html`. The system detects it automatically and shows a Settings button in the relevant tabs (per `settings_sections` in `plugin.json`).++### Settings modal contract++The modal provides Project + Agent profile context selectors. Your `settings.html` binds to `$store.pluginSettings.settings`:++```html+<html>+<head>+ <title>My Plugin Settings</title>+ <script type="module">+ import { store } from "/components/plugins/plugin-settings-store.js";+ </script>+</head>+<body>+ <div x-data>+ <input x-model="$store.pluginSettings.settings.my_key" />+ <input type="checkbox" x-model="$store.pluginSettings.settings.feature_enabled" />+ </div>+</body>+</html>+```++The modal's Save button persists `$store.pluginSettings.settings` to `settings.json` in the correct scope (project/agent/global).++### Surfacing core settings (e.g. memory pattern)++If your plugin exposes **existing core settings** rather than plugin-specific ones, set `saveMode = 'core'` so Save delegates to the core settings API:++```html+<div x-data x-init="+ $store.pluginSettings.saveMode = 'core';+ if ($store.settings && !$store.settings.settings) $store.settings.onOpen();+">+ <x-component path="settings/agent/memory.html"></x-component>+</div>+```++### Sidebar Button (sidebar entry point)+- **Extension point**: `sidebar-quick-actions-main-start`+- **Class**: `class="config-button"`+- **Placement**: `x-move-after=".config-button#dashboard"`+- **Action**: `@click="openModal('/plugins/<plugin_name>/webui/my-modal.html')"`++## 🐍 Backend API & Context++### Import Paths+- **Correct**: `from agent import AgentContext` (not python.helpers.agent)++### Sending Messages Proactively+```python+from agent import AgentContext+from python.helpers.messages import UserMessage++context = AgentContext.use(context_id)+task = context.communicate(UserMessage("Message text"))+response = await task.result()+```++### Reading Plugin Settings (backend)+```python+from python.helpers.plugins import get_plugin_settings++# Runtime (with running agent - resolves project/profile from context)+settings = get_plugin_settings("my-plugin", agent=agent)++# UI path (explicit strings, no agent instance needed)+settings = get_plugin_settings("my-plugin", project_name="my-project", agent_profile="default")+```++## 📁 Directory Layout+```+usr/plugins/<name>/+ plugin.json # Required manifest+ api/ # API Handlers (ApiHandler base class)+ tools/ # Tool subclasses+ extensions/+ python/agent_init/ # Python lifecycle extensions+ webui/<point>/ # HTML/JS hook extensions+ webui/+ settings.html # Optional: plugin settings UI+ my-modal.html # Full plugin pages+ my-store.js # Alpine stores+```diff --git a/webui/components/plugins/plugin-settings-store.js b/webui/components/plugins/plugin-settings-store.jsnew file mode 100644index 000000000..edc80724d--- /dev/null+++ b/webui/components/plugins/plugin-settings-store.js@@ -0,0 +1,151 @@+import { createStore } from "/js/AlpineStore.js";++const fetchApi = globalThis.fetchApi;++const model = {+ // which plugin this modal is showing+ pluginName: null,+ pluginMeta: null,++ // context selectors (mirrors skills list pattern)+ projects: [],+ agentProfiles: [],+ projectName: "",+ agentProfileKey: "",++ // plugin settings data (plugins bind their fields here)+ settings: {},++ // 'plugin' = save to plugin settings API+ // 'core' = save via $store.settings.saveSettings() (for plugins that surface core settings)+ saveMode: 'plugin',++ isLoading: false,+ isSaving: false,+ error: null,++ // Called by the subsection button before openModal()+ async open(pluginName) {+ this.pluginName = pluginName;+ this.pluginMeta = null;+ this.settings = {};+ this.error = null;+ this.saveMode = 'plugin';+ this.projectName = "";+ this.agentProfileKey = "";+ await Promise.all([this.loadProjects(), this.loadAgentProfiles()]);+ await this.loadSettings();+ },++ // Called by x-create inside the modal on every open+ async onModalOpen() {+ if (this.pluginName) await this.loadSettings();+ },++ async loadAgentProfiles() {+ try {+ const response = await fetchApi("/agents", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ action: "list" }),+ });+ const data = await response.json().catch(() => ({}));+ this.agentProfiles = data.ok ? (data.data || []) : [];+ } catch {+ this.agentProfiles = [];+ }+ },++ async loadProjects() {+ try {+ const response = await fetchApi("/projects", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ action: "list_options" }),+ });+ const data = await response.json().catch(() => ({}));+ this.projects = data.ok ? (data.data || []) : [];+ } catch {+ this.projects = [];+ }+ },++ async loadSettings() {+ if (!this.pluginName) return;+ this.isLoading = true;+ this.error = null;+ try {+ const response = await fetchApi("/plugins", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ action: "get_settings",+ plugin_name: this.pluginName,+ project_name: this.projectName || "",+ agent_profile: this.agentProfileKey || "",+ }),+ });+ const result = await response.json().catch(() => ({}));+ this.settings = result.ok ? (result.data || {}) : {};+ if (!result.ok) this.error = result.error || "Failed to load settings";+ } catch (e) {+ this.error = e?.message || "Failed to load settings";+ this.settings = {};+ } finally {+ this.isLoading = false;+ }+ },++ async save() {+ if (!this.pluginName) return;++ // Core-backed plugins (e.g. memory) delegate to the settings store+ if (this.saveMode === 'core') {+ const coreStore = Alpine.store('settings');+ if (coreStore?.saveSettings) {+ const ok = await coreStore.saveSettings();+ if (ok) window.closeModal?.();+ }+ return;+ }++ // Plugin-specific settings: persist to plugin settings API+ this.isSaving = true;+ this.error = null;+ try {+ const response = await fetchApi("/plugins", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ action: "save_settings",+ plugin_name: this.pluginName,+ project_name: this.projectName || "",+ agent_profile: this.agentProfileKey || "",+ settings: this.settings,+ }),+ });+ const result = await response.json().catch(() => ({}));+ if (!result.ok) this.error = result.error || "Save failed";+ else window.closeModal?.();+ } catch (e) {+ this.error = e?.message || "Save failed";+ } finally {+ this.isSaving = false;+ }+ },++ cleanup() {+ this.pluginName = null;+ this.pluginMeta = null;+ this.settings = {};+ this.error = null;+ },++ // Reactive URL for the plugin's settings component (used with x-html injection)+ get settingsComponentHtml() {+ if (!this.pluginName) return "";+ return `<x-component path="/plugins/${this.pluginName}/webui/settings.html"></x-component>`;+ },+};++export const store = createStore("pluginSettings", model);diff --git a/webui/components/plugins/plugin-settings.html b/webui/components/plugins/plugin-settings.htmlnew file mode 100644index 000000000..a8bbab5bb--- /dev/null+++ b/webui/components/plugins/plugin-settings.html@@ -0,0 +1,152 @@+<html>+<head>+ <title>Plugin Settings</title>+ <script type="module">+ import { store } from "/components/plugins/plugin-settings-store.js";+ </script>+</head>+<body>+ <div x-data>+ <template x-if="$store.pluginSettings">+ <div x-create="$store.pluginSettings.onModalOpen()"+ x-destroy="$store.pluginSettings.cleanup()">++ <!-- Context toolbar: Project + Agent profile (mirrors skills list) -->+ <div class="plugin-settings-toolbar">+ <div class="plugin-settings-toolbar-row">++ <label class="plugin-settings-toolbar-item">+ <span class="plugin-settings-toolbar-label">Project</span>+ <select x-model="$store.pluginSettings.projectName"+ @change="$store.pluginSettings.loadSettings()">+ <option value="">Global</option>+ <template x-for="project in $store.pluginSettings.projects" :key="project.key">+ <option :value="project.key" x-text="project.label"></option>+ </template>+ </select>+ </label>++ <label class="plugin-settings-toolbar-item">+ <span class="plugin-settings-toolbar-label">Agent profile</span>+ <select x-model="$store.pluginSettings.agentProfileKey"+ @change="$store.pluginSettings.loadSettings()">+ <option value="">All profiles</option>+ <template x-for="profile in $store.pluginSettings.agentProfiles" :key="profile.key">+ <option :value="profile.key" x-text="profile.label"></option>+ </template>+ </select>+ </label>++ </div>+ </div>++ <!-- Error -->+ <div x-show="$store.pluginSettings.error" class="plugin-settings-error">+ <span class="material-symbols-outlined">error</span>+ <span x-text="$store.pluginSettings.error"></span>+ </div>++ <!-- Loading -->+ <div x-show="$store.pluginSettings.isLoading" class="plugin-settings-loading">+ <span class="material-symbols-outlined spinning">progress_activity</span>+ <span>Loading settings...</span>+ </div>++ <!-- Plugin settings body: plugin provides /plugins/<name>/webui/settings.html -->+ <div x-show="!$store.pluginSettings.isLoading"+ class="plugin-settings-body"+ x-html="$store.pluginSettings.settingsComponentHtml">+ </div>++ </div>+ </template>+ </div>++ <!-- Footer (pinned outside scroll area) -->+ <div class="modal-footer" data-modal-footer>+ <button class="btn btn-ok"+ @click="$store.pluginSettings.save()"+ :disabled="$store.pluginSettings?.isSaving || $store.pluginSettings?.isLoading">+ Save+ </button>+ <button class="btn btn-cancel"+ @click="window.closeModal?.()">+ Cancel+ </button>+ </div>++ <style>+ .plugin-settings-toolbar {+ margin-bottom: 1rem;+ }++ .plugin-settings-toolbar-row {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ flex-wrap: wrap;+ }++ .plugin-settings-toolbar-item {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ flex: 1 1 18rem;+ min-width: 12rem;+ margin: 0;+ }++ .plugin-settings-toolbar-label {+ font-weight: 600;+ color: var(--color-text-secondary);+ white-space: nowrap;+ }++ .plugin-settings-toolbar-item select {+ flex: 1 1 auto;+ min-width: 0;+ }++ @media (max-width: 640px) {+ .plugin-settings-toolbar-item {+ flex-basis: 100%;+ min-width: 0;+ }+ }++ .plugin-settings-error {+ display: flex;+ align-items: center;+ gap: 0.5rem;+ color: var(--color-error, #e74c3c);+ background: var(--color-error-bg, #fdecea);+ border-radius: 4px;+ padding: 0.5rem 0.75rem;+ margin-bottom: 0.75rem;+ font-size: var(--font-size-small);+ }++ .plugin-settings-loading {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 0.5rem;+ padding: 2rem;+ color: var(--color-text-secondary);+ }++ .plugin-settings-body {+ min-height: 4rem;+ }++ .spinning {+ animation: spin 1s linear infinite;+ }++ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ </style>+</body>+</html>diff --git a/webui/components/settings/agent/agent-settings.html b/webui/components/settings/agent/agent-settings.htmlindex 7513831a8..8dcc24e72 100644--- a/webui/components/settings/agent/agent-settings.html+++ b/webui/components/settings/agent/agent-settings.html@@ -39,12 +39,6 @@<span>Embedding Model</span></a></li>- <li>- <a href="#section-memory">- <img src="/public/memory.svg" alt="Memory" />- <span>Memory</span>- </a>- </li><li><a href="#section-speech"><img src="/public/speech.svg" alt="Speech" />@@ -81,10 +75,6 @@<x-component path="settings/agent/embed_model.html"></x-component></div>- <div id="section-memory" class="section">- <x-component path="settings/agent/memory.html"></x-component>- </div>-<div id="section-speech" class="section"><x-component path="settings/agent/speech.html"></x-component></div>@@ -93,7 +83,10 @@<x-component path="settings/agent/workdir.html"></x-component></div>-+ <!-- Plugin settings subsection: shows plugins tagged with "agent" -->+ <div id="section-agent-plugins" class="section">+ <x-component path="settings/plugins/plugins-subsection.html" data-tab="agent"></x-component>+ </div></div></template>diff --git a/webui/components/settings/plugins/plugins-subsection.html b/webui/components/settings/plugins/plugins-subsection.htmlnew file mode 100644index 000000000..78b1542f3--- /dev/null+++ b/webui/components/settings/plugins/plugins-subsection.html@@ -0,0 +1,118 @@+<html>+<head>+ <script type="module">+ import { store } from "/components/plugins/plugin-settings-store.js";+ </script>+</head>+<body>+ <!--+ Reusable plugin subsection for a settings tab.+ Parent must pass data-tab attribute on the x-component tag, e.g.:+ <x-component path="settings/plugins/plugins-subsection.html" data-tab="agent"></x-component>+ The tab value is read at init time from the x-component element's dataset.+ -->+ <div x-data="{+ tab: '',+ plugins: [],+ loading: false,+ async init() {+ // find closest x-component ancestor to read the data-tab attribute+ const host = this.$el.closest('x-component') || this.$el.parentElement?.closest('x-component');+ this.tab = host?.getAttribute('data-tab') || '';+ await this.load();+ },+ async load() {+ if (!this.tab) return;+ this.loading = true;+ try {+ const r = await globalThis.fetchApi('/plugins', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ action: 'list', tab: this.tab }),+ });+ const data = await r.json().catch(() => ({}));+ this.plugins = (data.ok ? data.data || [] : []).filter(p => p.has_settings_ui);+ } catch {+ this.plugins = [];+ } finally {+ this.loading = false;+ }+ },+ async openSettings(pluginName) {+ await Alpine.store('pluginSettings')?.open(pluginName);+ window.openModal?.('components/plugins/plugin-settings.html');+ }+ }" x-init="init()">++ <template x-if="loading || plugins.length > 0">+ <div class="plugin-subsection-wrapper">+ <div class="section-title">Plugins</div>+ <div class="section-description">+ Plugin-specific settings for this tab.+ </div>++ <div x-show="loading" class="plugin-subsection-loading">+ <span>Loading...</span>+ </div>++ <template x-for="plugin in plugins" :key="plugin.name">+ <div class="plugin-subsection-row">+ <div class="plugin-subsection-info">+ <span class="plugin-subsection-name" x-text="plugin.display_name || plugin.name"></span>+ <span class="plugin-subsection-desc" x-text="plugin.description"></span>+ </div>+ <button class="button" @click="openSettings(plugin.name)">+ <span class="icon material-symbols-outlined">settings</span>+ Settings+ </button>+ </div>+ </template>+ </div>+ </template>+ </div>++ <style>+ .plugin-subsection-wrapper {+ margin-top: 0.5rem;+ }++ .plugin-subsection-loading {+ color: var(--color-text-secondary);+ font-size: var(--font-size-small);+ margin-top: 0.5rem;+ }++ .plugin-subsection-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ padding: 0.6rem 0.75rem;+ border: 1px solid var(--color-border);+ border-radius: 4px;+ margin-top: 0.5rem;+ background: var(--color-bg-primary);+ }++ .plugin-subsection-info {+ display: flex;+ flex-direction: column;+ gap: 0.2rem;+ min-width: 0;+ }++ .plugin-subsection-name {+ font-weight: 600;+ font-size: var(--font-size-normal);+ }++ .plugin-subsection-desc {+ font-size: var(--font-size-small);+ color: var(--color-text-secondary);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ </style>+</body>+</html>