Skip to content

Agent Zero AI framework

simplification and further memory decoupling

Alessandroe18efbb115a3
diff --git a/agent.py b/agent.py
index 6d993dc92..62e5dc708 100644
--- a/agent.py
+++ b/agent.py
@@ -19,7 +19,6 @@ from python.helpers import (
context as context_helper,
dirty_json,
subagents,
- plugins
)
from python.helpers.print_style import PrintStyle
@@ -645,21 +644,15 @@ class Agent:
return system_prompt
def parse_prompt(self, _prompt_file: str, **kwargs):
- dirs = subagents.get_paths(self, "prompts")
+ dirs = subagents.get_paths(self, "prompts", include_plugins=True)
- # Plugin prompt paths
- dirs.extend(plugins.get_plugin_paths("prompt"))
-
prompt = files.parse_file(
_prompt_file, _directories=dirs, _agent=self, **kwargs
)
return prompt
def read_prompt(self, file: str, **kwargs) -> str:
- dirs = subagents.get_paths(self, "prompts")
-
- # Plugin prompt paths
- dirs.extend(plugins.get_plugin_paths("prompt"))
+ dirs = subagents.get_paths(self, "prompts", include_plugins=True)
prompt = files.read_prompt_file(file, _directories=dirs, _agent=self, **kwargs)
if files.is_full_json_template(prompt):
@@ -995,12 +988,8 @@ class Agent:
classes = []
# search for tools in agent's folder hierarchy
- paths = subagents.get_paths(self, "tools", name + ".py", default_root="python")
-
- # Add plugin tool paths
- plugin_paths = plugins.get_plugin_paths("tool", name + ".py")
- paths.extend(plugin_paths)
-
+ paths = subagents.get_paths(self, "tools", name + ".py", default_root="python", include_plugins=True)
+
for path in paths:
try:
classes = extract_tools.load_classes_from_file(path, Tool) # type: ignore[arg-type]
diff --git a/plugins/README.md b/plugins/README.md
index 73ffc6fd5..cb697e84e 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -2,83 +2,53 @@
This directory contains default plugins shipped with Agent Zero.
-## Plugin Architecture
-
-Agent Zero uses a unified capability-based plugin system where a single `plugin.json` manifest declares all capabilities via a `provides` dictionary. Each capability type maps to an integration point in the framework.
-
-## Plugin Structure
-
-Each plugin directory should contain:
-- `plugin.json` - Manifest file with capability declarations
-- Capability-specific files organized by type (helpers, tools, extensions, api, ui, etc.)
-- Other assets (CSS, images, documentation)
-
-## Manifest Schema
-
-The `plugin.json` uses a `provides` dict where keys are integration point types:
-
-```json
-{
- "id": "my-plugin",
- "name": "My Plugin",
- "version": "1.0.0",
- "author": "Author Name",
- "description": "Plugin description",
- "tags": ["tag1", "tag2"],
- "provides": {
- "helper": [
- { "module": "helpers/my_helper.py", "description": "Helper module description" }
- ],
- "tool": [
- { "module": "tools/my_tool.py", "description": "Tool description" }
- ],
- "extension": [
- { "module": "extensions/hook_name/my_extension.py", "description": "Extension description" }
- ],
- "api": [
- { "module": "api/my_api.py", "description": "API endpoint description" }
- ],
- "ui": {
- "component": "ui/component.html",
- "module": "ui/main.js",
- "description": "UI component description"
- }
- }
-}
-```
+## Architecture
+
+Agent Zero uses a convention-over-configuration plugin model:
+
+- `plugin.json` is not used by runtime discovery.
+- Runtime capabilities are discovered from directory structure.
+- Backend owns discovery and routing; frontend consumes resolved URLs.
+
+## Directory Conventions
-## Capability Types
+Each plugin lives in `plugins/<plugin_id>/` (or `usr/plugins/<plugin_id>/` for overrides).
-- **helper**: Python modules providing reusable functionality (imported via proxy or direct)
-- **tool**: Agent tools extending agent capabilities
-- **extension**: Extension hooks that run at specific lifecycle points
-- **api**: Flask API endpoints (ApiHandler subclasses)
-- **ui**: Frontend components loaded via `<x-extension>` tags
-- **prompt**: Custom prompt templates
-- **knowledge**: Knowledge base files and directories
-- **instrument**: Custom instrumentation and monitoring
+Capability discovery is based on these paths:
-## Using Plugins
+- `api/*.py` - API handlers (`ApiHandler` subclasses), exposed as `/plugins/{plugin_id}/{handler_name}`
+- `tools/*.py` - Agent tools (`Tool` subclasses)
+- `helpers/*.py` - Shared Python helpers
+- `extensions/backend/{extension_point}/*.py` - Backend lifecycle extensions
+- `extensions/frontend/**/*.html` - Frontend UI components (auto-injected via `<meta name="plugin-target">`)
+- `prompts/**/*.md` - Prompt templates
+- `agents/` - Agent profiles
+- `extensions/frontend/` - Frontend UI assets and auto-injected components
+
+## Frontend Auto-Injection (PoC)
+
+Plugins can inject HTML components into the core UI. Place components under `extensions/frontend/` and declare the injection target with a `<meta>` tag:
-### UI Components
```html
-<x-extension id="plugin-id"></x-extension>
+<meta name="plugin-target" content=".quick-actions-dropdown">
```
-### Backend Capabilities
-Backend capabilities (helpers, tools, extensions, APIs) are automatically discovered and integrated when the plugin is loaded.
-
-## User Plugins
+Components without the meta tag (e.g. modals, dashboards) are standalone and not auto-injected.
-User-created plugins should be placed in one of the following directories:
+Resolution flow:
-- `/usr/plugins/` (Global user plugins)
-- `/usr/projects/<project_name>/.a0proj/plugins/` (Project-specific plugins)
+1. The backend parses `<meta name="plugin-target">` from each component HTML at scan time.
+2. `/plugins_resolve` returns component URLs with their target selectors.
+3. `plugins.js` (loaded globally) creates `<x-component>` elements at the declared target selectors.
+4. The standard `components.js` MutationObserver handles loading automatically.
+5. A MutationObserver in `plugins.js` retries for targets that appear after initial page render.
-Note: `/usr/` refers to the Agent Zero user data directory in the application root, not the system `/usr` directory.
+## Routes
-User plugins with the same ID as repo plugins will completely override the repo version.
+- Plugin static assets: `GET /plugins/<plugin_id>/<path>`
+- Plugin APIs: `/plugins/<plugin_id>/<handler>`
-## Documentation
+## Notes
-See [docs/extensibility.md](../docs/extensibility.md) for complete documentation on creating plugins.
+- User plugins in `usr/plugins/` override repo plugins by plugin ID.
+- Runtime behavior is fully convention-driven from directory structure.
diff --git a/plugins/example_agent/plugin.json b/plugins/example_agent/plugin.json
deleted file mode 100644
index c024a77bc..000000000
--- a/plugins/example_agent/plugin.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "id": "example_agent",
- "name": "Example Agent Plugin",
- "version": "0.1.0",
- "description": "An example plugin demonstrating the agent profile capability.",
- "author": "Agent Zero",
- "provides": {
- "agent": [
- {
- "dir": "agents",
- "description": "Example agent profile"
- }
- ]
- }
-}
diff --git a/python/api/import_knowledge.py b/plugins/memory/api/import_knowledge.py
similarity index 84%
rename from python/api/import_knowledge.py
rename to plugins/memory/api/import_knowledge.py
index 39b1d1842..aa1711442 100644
--- a/python/api/import_knowledge.py
+++ b/plugins/memory/api/import_knowledge.py
@@ -1,9 +1,8 @@
from python.helpers.api import ApiHandler, Request, Response
from python.helpers import files
-from python.helpers.plugins import import_plugin_module
-memory = import_plugin_module("memory", "helpers/memory.py")
-import os
from python.helpers.security import safe_filename
+from plugins.memory.helpers.memory import Memory, get_custom_knowledge_subdir_abs
+import os
class ImportKnowledge(ApiHandler):
@@ -18,7 +17,7 @@ class ImportKnowledge(ApiHandler):
context = self.use_context(ctxid)
file_list = request.files.getlist("files[]")
- KNOWLEDGE_FOLDER = files.get_abs_path(memory.get_custom_knowledge_subdir_abs(context.agent0), "main")
+ KNOWLEDGE_FOLDER = files.get_abs_path(get_custom_knowledge_subdir_abs(context.agent0), "main")
# Ensure knowledge folder exists (create if missing)
try:
@@ -41,7 +40,7 @@ class ImportKnowledge(ApiHandler):
saved_filenames.append(filename)
#reload memory to re-import knowledge
- await memory.Memory.reload(context.agent0)
+ await Memory.reload(context.agent0)
context.log.set_initial_progress()
return {
diff --git a/python/api/knowledge_path_get.py b/plugins/memory/api/knowledge_path_get.py
similarity index 66%
rename from python/api/knowledge_path_get.py
rename to plugins/memory/api/knowledge_path_get.py
index 29033e198..b643a1d2e 100644
--- a/python/api/knowledge_path_get.py
+++ b/plugins/memory/api/knowledge_path_get.py
@@ -1,9 +1,6 @@
from python.helpers.api import ApiHandler, Request, Response
-from python.helpers import files, notification, projects, notification
-from python.helpers.plugins import import_plugin_module
-memory = import_plugin_module("memory", "helpers/memory.py")
-import os
-from werkzeug.utils import secure_filename
+from python.helpers import files, projects
+from plugins.memory.helpers.memory import get_custom_knowledge_subdir_abs
class GetKnowledgePath(ApiHandler):
@@ -17,11 +14,11 @@ class GetKnowledgePath(ApiHandler):
if project_name:
knowledge_folder = projects.get_project_meta_folder(project_name, "knowledge")
else:
- knowledge_folder = memory.get_custom_knowledge_subdir_abs(context.agent0)
+ knowledge_folder = get_custom_knowledge_subdir_abs(context.agent0)
knowledge_folder = files.normalize_a0_path(knowledge_folder)
return {
"ok": True,
"path": knowledge_folder,
- }
\ No newline at end of file
+ }
diff --git a/python/api/knowledge_reindex.py b/plugins/memory/api/knowledge_reindex.py
similarity index 67%
rename from python/api/knowledge_reindex.py
rename to plugins/memory/api/knowledge_reindex.py
index 75cb41969..b8c0a8f45 100644
--- a/python/api/knowledge_reindex.py
+++ b/plugins/memory/api/knowledge_reindex.py
@@ -1,8 +1,5 @@
from python.helpers.api import ApiHandler, Request, Response
-from python.helpers import files, notification, projects, notification
-from python.helpers.plugins import import_plugin_module
-memory = import_plugin_module("memory", "helpers/memory.py")
-import os
+from plugins.memory.helpers.memory import Memory
class ReindexKnowledge(ApiHandler):
@@ -13,7 +10,7 @@ class ReindexKnowledge(ApiHandler):
context = self.use_context(ctxid)
# reload memory to re-import knowledge
- await memory.Memory.reload(context.agent0)
+ await Memory.reload(context.agent0)
context.log.set_initial_progress()
return {
diff --git a/plugins/memory/extensions/backend/embedding_model_changed/_10_memory_reload.py b/plugins/memory/extensions/backend/embedding_model_changed/_10_memory_reload.py
new file mode 100644
index 000000000..db561d9b4
--- /dev/null
+++ b/plugins/memory/extensions/backend/embedding_model_changed/_10_memory_reload.py
@@ -0,0 +1,10 @@
+from python.helpers.extension import Extension
+
+# Direct import - this extension lives inside the memory plugin
+from plugins.memory.helpers.memory import reload as memory_reload
+
+
+class MemoryReload(Extension):
+
+ async def execute(self, **kwargs):
+ memory_reload()
diff --git a/plugins/memory/extensions/message_loop_prompts_after/_50_recall_memories.py b/plugins/memory/extensions/backend/message_loop_prompts_after/_50_recall_memories.py
similarity index 96%
rename from plugins/memory/extensions/message_loop_prompts_after/_50_recall_memories.py
rename to plugins/memory/extensions/backend/message_loop_prompts_after/_50_recall_memories.py
index 9527ef1f2..e36254383 100644
--- a/plugins/memory/extensions/message_loop_prompts_after/_50_recall_memories.py
+++ b/plugins/memory/extensions/backend/message_loop_prompts_after/_50_recall_memories.py
@@ -3,14 +3,9 @@ from python.helpers.extension import Extension
from agent import LoopData
from python.helpers import dirty_json, errors, settings, log
-# Import Memory and DEFAULT_THRESHOLD from plugin
-import sys
-from pathlib import Path
-_plugin_root = Path(__file__).parent.parent.parent
-if str(_plugin_root) not in sys.path:
- sys.path.insert(0, str(_plugin_root))
-from helpers.memory import Memory
-from tools.memory_load import DEFAULT_THRESHOLD as DEFAULT_MEMORY_THRESHOLD
+# Direct import - this extension lives inside the memory plugin
+from plugins.memory.helpers.memory import Memory
+from plugins.memory.tools.memory_load import DEFAULT_THRESHOLD as DEFAULT_MEMORY_THRESHOLD
DATA_NAME_TASK = "_recall_memories_task"
diff --git a/python/extensions/message_loop_prompts_after/_91_recall_wait.py b/plugins/memory/extensions/backend/message_loop_prompts_after/_91_recall_wait.py
similarity index 64%
rename from python/extensions/message_loop_prompts_after/_91_recall_wait.py
rename to plugins/memory/extensions/backend/message_loop_prompts_after/_91_recall_wait.py
index 6be6321c3..b21785953 100644
--- a/python/extensions/message_loop_prompts_after/_91_recall_wait.py
+++ b/plugins/memory/extensions/backend/message_loop_prompts_after/_91_recall_wait.py
@@ -1,7 +1,6 @@
from python.helpers.extension import Extension
from agent import LoopData
-from python.extensions.message_loop_prompts_after._50_recall_memories import DATA_NAME_TASK as DATA_NAME_TASK_MEMORIES, DATA_NAME_ITER as DATA_NAME_ITER_MEMORIES
-# from python.extensions.message_loop_prompts_after._51_recall_solutions import DATA_NAME_TASK as DATA_NAME_TASK_SOLUTIONS
+from plugins.memory.extensions.backend.message_loop_prompts_after._50_recall_memories import DATA_NAME_TASK as DATA_NAME_TASK_MEMORIES, DATA_NAME_ITER as DATA_NAME_ITER_MEMORIES
from python.helpers import settings
class RecallWait(Extension):
@@ -21,12 +20,6 @@ class RecallWait(Extension):
delay_text = self.agent.read_prompt("memory.recall_delay_msg.md")
loop_data.extras_temporary["memory_recall_delayed"] = delay_text
return
-
+
# otherwise await the task
await task
-
- # task = self.agent.get_data(DATA_NAME_TASK_SOLUTIONS)
- # if task and not task.done():
- # # self.agent.context.log.set_progress("Recalling solutions...")
- # await task
-
diff --git a/plugins/memory/extensions/monologue_end/_50_memorize_fragments.py b/plugins/memory/extensions/backend/monologue_end/_50_memorize_fragments.py
similarity index 95%
rename from plugins/memory/extensions/monologue_end/_50_memorize_fragments.py
rename to plugins/memory/extensions/backend/monologue_end/_50_memorize_fragments.py
index 8ff2e40ae..77dc0d204 100644
--- a/plugins/memory/extensions/monologue_end/_50_memorize_fragments.py
+++ b/plugins/memory/extensions/backend/monologue_end/_50_memorize_fragments.py
@@ -6,14 +6,9 @@ from agent import LoopData
from python.helpers.log import LogItem
from python.helpers.defer import DeferredTask, THREAD_BACKGROUND
-# Import Memory and DEFAULT_THRESHOLD from plugin
-import sys
-from pathlib import Path
-_plugin_root = Path(__file__).parent.parent.parent
-if str(_plugin_root) not in sys.path:
- sys.path.insert(0, str(_plugin_root))
-from helpers.memory import Memory
-from tools.memory_load import DEFAULT_THRESHOLD as DEFAULT_MEMORY_THRESHOLD
+# Direct import - this extension lives inside the memory plugin
+from plugins.memory.helpers.memory import Memory
+from plugins.memory.tools.memory_load import DEFAULT_THRESHOLD as DEFAULT_MEMORY_THRESHOLD
class MemorizeMemories(Extension):
@@ -115,7 +110,7 @@ class MemorizeMemories(Extension):
try:
# Use intelligent consolidation system
- from helpers.memory_consolidation import create_memory_consolidator
+ from plugins.memory.helpers.memory_consolidation import create_memory_consolidator
consolidator = create_memory_consolidator(
self.agent,
similarity_threshold=DEFAULT_MEMORY_THRESHOLD, # More permissive for discovery
@@ -197,7 +192,6 @@ class MemorizeMemories(Extension):
-
except Exception as e:
err = errors.format_error(e)
self.agent.context.log.log(
diff --git a/plugins/memory/extensions/monologue_end/_51_memorize_solutions.py b/plugins/memory/extensions/backend/monologue_end/_51_memorize_solutions.py
similarity index 95%
rename from plugins/memory/extensions/monologue_end/_51_memorize_solutions.py
rename to plugins/memory/extensions/backend/monologue_end/_51_memorize_solutions.py
index da6b9a806..24c90bab0 100644
--- a/plugins/memory/extensions/monologue_end/_51_memorize_solutions.py
+++ b/plugins/memory/extensions/backend/monologue_end/_51_memorize_solutions.py
@@ -6,14 +6,9 @@ from agent import LoopData
from python.helpers.log import LogItem
from python.helpers.defer import DeferredTask, THREAD_BACKGROUND
-# Import Memory and DEFAULT_THRESHOLD from plugin
-import sys
-from pathlib import Path
-_plugin_root = Path(__file__).parent.parent.parent
-if str(_plugin_root) not in sys.path:
- sys.path.insert(0, str(_plugin_root))
-from helpers.memory import Memory
-from tools.memory_load import DEFAULT_THRESHOLD as DEFAULT_MEMORY_THRESHOLD
+# Direct import - this extension lives inside the memory plugin
+from plugins.memory.helpers.memory import Memory
+from plugins.memory.tools.memory_load import DEFAULT_THRESHOLD as DEFAULT_MEMORY_THRESHOLD
class MemorizeSolutions(Extension):
@@ -122,7 +117,7 @@ class MemorizeSolutions(Extension):
if set["memory_memorize_consolidation"]:
try:
# Use intelligent consolidation system
- from helpers.memory_consolidation import create_memory_consolidator
+ from plugins.memory.helpers.memory_consolidation import create_memory_consolidator
consolidator = create_memory_consolidator(
self.agent,
similarity_threshold=DEFAULT_MEMORY_THRESHOLD, # More permissive for discovery
diff --git a/plugins/memory/extensions/backend/monologue_start/_10_memory_init.py b/plugins/memory/extensions/backend/monologue_start/_10_memory_init.py
new file mode 100644
index 000000000..1bacc881c
--- /dev/null
+++ b/plugins/memory/extensions/backend/monologue_start/_10_memory_init.py
@@ -0,0 +1,11 @@
+from python.helpers.extension import Extension
+from agent import LoopData
+
+# Direct import - this extension lives inside the memory plugin
+from plugins.memory.helpers import memory
+
+
+class MemoryInit(Extension):
+
+ async def execute(self, loop_data: LoopData = LoopData(), **kwargs):
+ db = await memory.Memory.get(self.agent)
diff --git a/python/extensions/system_prompt/_20_behaviour_prompt.py b/plugins/memory/extensions/backend/system_prompt/_20_behaviour_prompt.py
similarity index 71%
rename from python/extensions/system_prompt/_20_behaviour_prompt.py
rename to plugins/memory/extensions/backend/system_prompt/_20_behaviour_prompt.py
index d8b5f7ade..bec18f0fd 100644
--- a/python/extensions/system_prompt/_20_behaviour_prompt.py
+++ b/plugins/memory/extensions/backend/system_prompt/_20_behaviour_prompt.py
@@ -1,27 +1,27 @@
-from datetime import datetime
from python.helpers.extension import Extension
from agent import Agent, LoopData
from python.helpers import files
-from python.helpers.plugins import import_plugin_module
-memory = import_plugin_module("memory", "helpers/memory.py")
+# Direct import - this extension lives inside the memory plugin
+from plugins.memory.helpers import memory
class BehaviourPrompt(Extension):
async def execute(self, system_prompt: list[str]=[], loop_data: LoopData = LoopData(), **kwargs):
prompt = read_rules(self.agent)
- system_prompt.insert(0, prompt) #.append(prompt)
+ system_prompt.insert(0, prompt)
+
def get_custom_rules_file(agent: Agent):
return files.get_abs_path(memory.get_memory_subdir_abs(agent), "behaviour.md")
+
def read_rules(agent: Agent):
rules_file = get_custom_rules_file(agent)
if files.exists(rules_file):
- rules = files.read_file(rules_file) # no includes and vars here, that could crash
+ rules = files.read_file(rules_file)
return agent.read_prompt("agent.system.behaviour.md", rules=rules)
else:
rules = agent.read_prompt("agent.system.behaviour_default.md")
return agent.read_prompt("agent.system.behaviour.md", rules=rules)
-
\ No newline at end of file
diff --git a/plugins/memory/ui/memory-dashboard-store.js b/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard-store.js
similarity index 96%
rename from plugins/memory/ui/memory-dashboard-store.js
rename to plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard-store.js
index c5f8eca97..f1c6af5f8 100644
--- a/plugins/memory/ui/memory-dashboard-store.js
+++ b/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard-store.js
@@ -3,6 +3,7 @@ import { getContext } from "/index.js";
import * as API from "/js/api.js";
import { openModal, closeModal } from "/js/modals.js";
import { store as notificationStore } from "/components/notifications/notification-store.js";
+const MEMORY_DASHBOARD_API = "/plugins/memory/memory_dashboard";
// Helper function for toasts
function justToast(text, type = "info", timeout = 5000) {
@@ -53,7 +54,7 @@ const memoryDashboardStore = {
pollingEnabled: false,
async openModal() {
- await openModal("../plugins/memory/ui/memory-dashboard.html");
+ await openModal("../plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html");
},
init() {
@@ -91,7 +92,7 @@ const memoryDashboardStore = {
async getCurrentMemorySubdir() {
try {
// Try to get current memory subdirectory from the backend
- const response = await API.callJsonApi("memory_dashboard", {
+ const response = await API.callJsonApi(MEMORY_DASHBOARD_API, {
action: "get_current_memory_subdir",
context_id: getContext(),
});
@@ -113,7 +114,7 @@ const memoryDashboardStore = {
this.error = null;
try {
- const response = await API.callJsonApi("memory_dashboard", {
+ const response = await API.callJsonApi(MEMORY_DASHBOARD_API, {
action: "get_memory_subdirs",
});
@@ -172,7 +173,7 @@ const memoryDashboardStore = {
}
try {
- const response = await API.callJsonApi("memory_dashboard", {
+ const response = await API.callJsonApi(MEMORY_DASHBOARD_API, {
action: "search",
memory_subdir: this.selectedMemorySubdir,
area: this.areaFilter,
@@ -326,7 +327,7 @@ const memoryDashboardStore = {
try {
this.loading = true;
- const response = await API.callJsonApi("memory_dashboard", {
+ const response = await API.callJsonApi(MEMORY_DASHBOARD_API, {
action: "bulk_delete",
memory_subdir: this.selectedMemorySubdir,
memory_ids: selectedMemories.map((memory) => memory.id),
@@ -448,7 +449,7 @@ ${memory.content_full}
this.editMode = false;
this.editMemoryBackup = null;
// Use global modal system
- openModal("../plugins/memory/ui/memory-detail-modal.html");
+ openModal("../plugins/memory/extensions/frontend/memory_dashboard/memory-detail-modal.html");
},
closeMemoryDetails() {
@@ -556,7 +557,7 @@ ${memory.content_full}
const isViewingThisMemory =
this.detailMemory && this.detailMemory.id === memory.id;
- const response = await API.callJsonApi("memory_dashboard", {
+ const response = await API.callJsonApi(MEMORY_DASHBOARD_API, {
action: "delete",
memory_subdir: this.selectedMemorySubdir,
memory_id: memory.id,
@@ -674,7 +675,7 @@ ${memory.content_full}
async confirmEditMode() {
try {
- const response = await API.callJsonApi("memory_dashboard", {
+ const response = await API.callJsonApi(MEMORY_DASHBOARD_API, {
action: "update",
memory_subdir: this.selectedMemorySubdir,
original: JSON.parse(this.editMemoryBackup),
diff --git a/plugins/memory/ui/memory-dashboard.html b/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html
similarity index 99%
rename from plugins/memory/ui/memory-dashboard.html
rename to plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html
index dda198f93..c58cfaca5 100644
--- a/plugins/memory/ui/memory-dashboard.html
+++ b/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html
@@ -3,7 +3,7 @@
<head>
<title>Memory Dashboard</title>
<script type="module">
- import { store } from "/plugins/memory/ui/memory-dashboard-store.js";
+ import { store } from "/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard-store.js";
</script>
</head>
diff --git a/plugins/memory/ui/memory-detail-modal.html b/plugins/memory/extensions/frontend/memory_dashboard/memory-detail-modal.html
similarity index 100%
rename from plugins/memory/ui/memory-detail-modal.html
rename to plugins/memory/extensions/frontend/memory_dashboard/memory-detail-modal.html
diff --git a/plugins/memory/extensions/frontend/sidebar.quick_actions.dropdown/memory-entry.html b/plugins/memory/extensions/frontend/sidebar.quick_actions.dropdown/memory-entry.html
new file mode 100644
index 000000000..ea3d38b33
--- /dev/null
+++ b/plugins/memory/extensions/frontend/sidebar.quick_actions.dropdown/memory-entry.html
@@ -0,0 +1,14 @@
+<html>
+
+<head>
+ <meta name="plugin-target" content=".quick-actions-dropdown">
+</head>
+
+<body>
+ <button class="dropdown-item" @click="openModal('../plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html'); dropdownOpen = false">
+ <span class="material-symbols-outlined">psychology</span>
+ <span>Memories</span>
+ </button>
+</body>
+
+</html>
diff --git a/plugins/memory/extensions/monologue_start/_10_memory_init.py b/plugins/memory/extensions/monologue_start/_10_memory_init.py
deleted file mode 100644
index ab9d1990e..000000000
--- a/plugins/memory/extensions/monologue_start/_10_memory_init.py
+++ /dev/null
@@ -1,20 +0,0 @@
-from python.helpers.extension import Extension
-from agent import LoopData
-import asyncio
-
-# Import memory from plugin
-import sys
-from pathlib import Path
-_plugin_root = Path(__file__).parent.parent.parent
-if str(_plugin_root) not in sys.path:
- sys.path.insert(0, str(_plugin_root))
-from helpers import memory
-
-
-class MemoryInit(Extension):
-
- async def execute(self, loop_data: LoopData = LoopData(), **kwargs):
- db = await memory.Memory.get(self.agent)
-
-
-
\ No newline at end of file
diff --git a/plugins/memory/plugin.json b/plugins/memory/plugin.json
deleted file mode 100644
index d4ef0c364..000000000
--- a/plugins/memory/plugin.json
+++ /dev/null
@@ -1,151 +0,0 @@
-{
- "id": "memory",
- "name": "Memory System",
- "version": "1.0.0",
- "author": "Agent Zero Team",
- "description": "FAISS-based vector memory with embeddings caching and knowledge preloading",
- "tags": ["memory", "vector", "faiss", "core"],
- "provides": {
- "helper": [
- {
- "module": "helpers/memory.py",
- "description": "Core Memory class with FAISS vector store"
- },
- {
- "module": "helpers/memory_consolidation.py",
- "description": "Intelligent memory deduplication"
- },
- {
- "module": "helpers/knowledge_import.py",
- "description": "Knowledge file ingestion pipeline"
- }
- ],
- "tool": [
- {
- "module": "tools/memory_save.py",
- "description": "Save memories"
- },
- {
- "module": "tools/memory_load.py",
- "description": "Load/search memories"
- },
- {
- "module": "tools/memory_delete.py",
- "description": "Delete specific memories"
- },
- {
- "module": "tools/memory_forget.py",
- "description": "Forget memories by query"
- }
- ],
- "extension": [
- {
- "module": "extensions/monologue_start/_10_memory_init.py",
- "description": "Initialize memory on monologue start"
- },
- {
- "module": "extensions/monologue_end/_50_memorize_fragments.py",
- "description": "Auto-memorize conversation fragments"
- },
- {
- "module": "extensions/monologue_end/_51_memorize_solutions.py",
- "description": "Auto-memorize solutions"
- },
- {
- "module": "extensions/message_loop_prompts_after/_50_recall_memories.py",
- "description": "Recall relevant memories into prompt"
- }
- ],
- "api": [
- {
- "module": "api/memory_dashboard.py",
- "description": "Memory browser and management dashboard"
- }
- ],
- "ui": [
- {
- "component": "ui/memory-dashboard.html",
- "module": "ui/memory-dashboard-store.js",
- "description": "Memory Dashboard UI"
- },
- {
- "component": "ui/memory-detail-modal.html",
- "description": "Memory Detail Modal"
- }
- ],
- "prompt": [
- {
- "module": "prompts/agent.system.memories.md",
- "description": "Agent system prompt for memories"
- },
- {
- "module": "prompts/agent.system.solutions.md",
- "description": "Agent system prompt for solutions"
- },
- {
- "module": "prompts/agent.system.tool.memory.md",
- "description": "Memory tool system prompt"
- },
- {
- "module": "prompts/fw.memory.hist_suc.sys.md",
- "description": "Framework memory history success prompt"
- },
- {
- "module": "prompts/fw.memory.hist_sum.sys.md",
- "description": "Framework memory history summary prompt"
- },
- {
- "module": "prompts/fw.memory_saved.md",
- "description": "Framework memory saved prompt"
- },
- {
- "module": "prompts/memory.consolidation.msg.md",
- "description": "Memory consolidation message"
- },
- {
- "module": "prompts/memory.consolidation.sys.md",
- "description": "Memory consolidation system prompt"
- },
- {
- "module": "prompts/memory.keyword_extraction.msg.md",
- "description": "Keyword extraction message"
- },
- {
- "module": "prompts/memory.keyword_extraction.sys.md",
- "description": "Keyword extraction system prompt"
- },
- {
- "module": "prompts/memory.memories_filter.msg.md",
- "description": "Memories filter message"
- },
- {
- "module": "prompts/memory.memories_filter.sys.md",
- "description": "Memories filter system prompt"
- },
- {
- "module": "prompts/memory.memories_query.msg.md",
- "description": "Memories query message"
- },
- {
- "module": "prompts/memory.memories_query.sys.md",
- "description": "Memory query system prompt"
- },
- {
- "module": "prompts/memory.memories_sum.sys.md",
- "description": "Memories summary system prompt"
- },
- {
- "module": "prompts/memory.recall_delay_msg.md",
- "description": "Recall delay message"
- },
- {
- "module": "prompts/memory.solutions_query.sys.md",
- "description": "Solutions query system prompt"
- },
- {
- "module": "prompts/memory.solutions_sum.sys.md",
- "description": "Solutions summary system prompt"
- }
- ]
- }
-}
diff --git a/python/tools/behaviour_adjustment.py b/plugins/memory/tools/behaviour_adjustment.py
similarity index 87%
rename from python/tools/behaviour_adjustment.py
rename to plugins/memory/tools/behaviour_adjustment.py
index d82fd9774..292aaa126 100644
--- a/python/tools/behaviour_adjustment.py
+++ b/plugins/memory/tools/behaviour_adjustment.py
@@ -1,10 +1,11 @@
from python.helpers import files
-from python.helpers.plugins import import_plugin_module
-memory = import_plugin_module("memory", "helpers/memory.py")
from python.helpers.tool import Tool, Response
from agent import Agent
from python.helpers.log import LogItem
+# Direct import - this tool lives inside the memory plugin
+from plugins.memory.helpers import memory
+
class UpdateBehaviour(Tool):
@@ -19,12 +20,6 @@ class UpdateBehaviour(Tool):
message=self.agent.read_prompt("behaviour.updated.md"), break_loop=False
)
- # async def before_execution(self, **kwargs):
- # pass
-
- # async def after_execution(self, response, **kwargs):
- # pass
-
async def update_behaviour(agent: Agent, log_item: LogItem, adjustments: str):
diff --git a/python/api/chat_files_path_get.py b/python/api/chat_files_path_get.py
index 3ad734e4d..aafdd8456 100644
--- a/python/api/chat_files_path_get.py
+++ b/python/api/chat_files_path_get.py
@@ -1,8 +1,5 @@
from python.helpers.api import ApiHandler, Request, Response
-from python.helpers import files, notification, projects, notification, runtime, settings
-from python.helpers.plugins import import_plugin_module
-memory = import_plugin_module("memory", "helpers/memory.py")
-import os
+from python.helpers import files, projects, settings
class GetChatFilesPath(ApiHandler):
diff --git a/python/api/plugins_list.py b/python/api/plugins_list.py
deleted file mode 100644
index f0ffab86e..000000000
--- a/python/api/plugins_list.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from python.helpers.api import ApiHandler, Request, Response
-from python.helpers import plugins
-
-
-class PluginsList(ApiHandler):
- """
- API handler for listing all available plugins.
- Returns a list of plugin manifests.
- """
-
- @classmethod
- def get_methods(cls):
- return ["GET", "POST"]
-
- async def process(self, input: dict, request: Request) -> dict | Response:
- # Get all available plugins
- plugin_list = plugins.list_plugins()
-
- # Serialize plugin objects using helper
- data = [plugins.build_plugin_response_data(p) for p in plugin_list]
-
- return {"ok": True, "data": data}
diff --git a/python/api/plugins_resolve.py b/python/api/plugins_resolve.py
index 28a8ee2d5..dae93af62 100644
--- a/python/api/plugins_resolve.py
+++ b/python/api/plugins_resolve.py
@@ -4,11 +4,9 @@ from python.helpers import plugins
class PluginsResolve(ApiHandler):
"""
- API handler for resolving plugin manifests.
- Accepts a plugin ID or list of IDs and returns normalized manifest(s) with URLs and props.
-
- Single ID: {"id": "example"} -> {"ok": True, "data": {...}}
- Multiple IDs: {"ids": ["example", "another"]} -> {"ok": True, "data": [{...}, {...}]}
+ Return all injectable plugin frontend components.
+ Each plugin's extensions/frontend/**/*.html files are returned.
+ The components themselves declare their injection target via <meta> tags.
"""
@classmethod
@@ -16,35 +14,5 @@ class PluginsResolve(ApiHandler):
return ["POST"]
async def process(self, input: dict, request: Request) -> dict | Response:
- # Support both single ID and array of IDs
- plugin_id = input.get("id")
- plugin_ids = input.get("ids")
-
- # Batch mode: array of IDs
- if plugin_ids:
- if not isinstance(plugin_ids, list):
- return {"ok": False, "error": "ids must be an array"}
-
- results = []
- for pid in plugin_ids:
- plugin = plugins.find_plugin(pid)
- if plugin:
- results.append(plugins.build_plugin_response_data(plugin))
- else:
- results.append({
- "id": pid,
- "error": f"Plugin '{pid}' not found or invalid manifest"
- })
-
- return {"ok": True, "data": results}
-
- # Single mode: one ID
- elif plugin_id:
- plugin = plugins.find_plugin(plugin_id)
- if not plugin:
- return {"ok": False, "error": f"Plugin '{plugin_id}' not found or invalid manifest"}
-
- return {"ok": True, "data": plugins.build_plugin_response_data(plugin)}
-
- else:
- return {"ok": False, "error": "Missing plugin ID or IDs"}
+ data = plugins.get_frontend_components()
+ return {"ok": True, "data": data}
diff --git a/python/extensions/message_loop_prompts_after/_50_recall_memories.py b/python/extensions/message_loop_prompts_after/_50_recall_memories.py
deleted file mode 100644
index f4bb5d542..000000000
--- a/python/extensions/message_loop_prompts_after/_50_recall_memories.py
+++ /dev/null
@@ -1,8 +0,0 @@
-"""Recall memories extension - implementation provided by the memory plugin."""
-from python.helpers.plugins import import_plugin_module
-
-# Import the actual implementation from the plugin
-_mod = import_plugin_module("memory", "extensions/message_loop_prompts_after/_50_recall_memories.py")
-
-# Re-export all public names
-globals().update({k: v for k, v in vars(_mod).items() if not k.startswith('_')})
diff --git a/python/extensions/monologue_end/_50_memorize_fragments.py b/python/extensions/monologue_end/_50_memorize_fragments.py
deleted file mode 100644
index f7b88d9f9..000000000
--- a/python/extensions/monologue_end/_50_memorize_fragments.py
+++ /dev/null
@@ -1,8 +0,0 @@
-"""Memorize fragments extension - implementation provided by the memory plugin."""
-from python.helpers.plugins import import_plugin_module
-
-# Import the actual implementation from the plugin
-_mod = import_plugin_module("memory", "extensions/monologue_end/_50_memorize_fragments.py")
-
-# Re-export all public names
-globals().update({k: v for k, v in vars(_mod).items() if not k.startswith('_')})
diff --git a/python/extensions/monologue_end/_51_memorize_solutions.py b/python/extensions/monologue_end/_51_memorize_solutions.py
deleted file mode 100644
index 276a4aca5..000000000
--- a/python/extensions/monologue_end/_51_memorize_solutions.py
+++ /dev/null
@@ -1,8 +0,0 @@
-"""Memorize solutions extension - implementation provided by the memory plugin."""
-from python.helpers.plugins import import_plugin_module
-
-# Import the actual implementation from the plugin
-_mod = import_plugin_module("memory", "extensions/monologue_end/_51_memorize_solutions.py")
-
-# Re-export all public names
-globals().update({k: v for k, v in vars(_mod).items() if not k.startswith('_')})
diff --git a/python/extensions/monologue_start/_10_memory_init.py b/python/extensions/monologue_start/_10_memory_init.py
deleted file mode 100644
index 352a1a924..000000000
--- a/python/extensions/monologue_start/_10_memory_init.py
+++ /dev/null
@@ -1,8 +0,0 @@
-"""Memory initialization extension - implementation provided by the memory plugin."""
-from python.helpers.plugins import import_plugin_module
-
-# Import the actual implementation from the plugin
-_mod = import_plugin_module("memory", "extensions/monologue_start/_10_memory_init.py")
-
-# Re-export all public names
-globals().update({k: v for k, v in vars(_mod).items() if not k.startswith('_')})
diff --git a/python/helpers/extension.py b/python/helpers/extension.py
index 0526f68bd..f6d0d3c00 100644
--- a/python/helpers/extension.py
+++ b/python/helpers/extension.py
@@ -31,11 +31,11 @@ async def call_extensions(
# search for extension folders in all agent's paths
paths = subagents.get_paths(agent, "extensions", extension_point, default_root="python")
-
- # Add plugin extension paths
- plugin_paths = plugins.get_plugin_paths("extension", extension_point)
- paths.extend(plugin_paths)
-
+
+ # Add plugin backend extension paths (plugins/*/extensions/backend/{extension_point})
+ plugin_paths = plugins.get_plugin_paths("extensions", "backend", extension_point)
+ paths.extend(p for p in plugin_paths if p not in paths)
+
all_exts = [cls for path in paths for cls in _get_extensions(path)]
# merge: first ocurrence of file name is the override
diff --git a/python/helpers/plugins.py b/python/helpers/plugins.py
index 75aacd132..3cff77e0a 100644
--- a/python/helpers/plugins.py
+++ b/python/helpers/plugins.py
@@ -1,272 +1,105 @@
from __future__ import annotations
-import json
-from dataclasses import dataclass, field
+import re
+from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional
from python.helpers import files
+# Extracts target selector from <meta name="plugin-target" content="...">
+_META_TARGET_RE = re.compile(
+ r'<meta\s+name=["\']plugin-target["\']\s+content=["\']([^"\']+)["\']',
+ re.IGNORECASE,
+)
-# ============================================================================
-# Core Data Structures
-# ============================================================================
@dataclass(slots=True)
class Plugin:
id: str
name: str
path: Path
- manifest_path: Path
- provides: Dict[str, Any] = field(default_factory=dict) # capability map
- version: str = ""
- author: str = ""
- description: str = ""
- tags: List[str] = field(default_factory=list)
-
- # Optional heavy fields
- raw_manifest: Dict[str, Any] = field(default_factory=dict)
-# ============================================================================
-# Discovery & Loading
-# ============================================================================
-
def get_plugin_roots() -> List[str]:
- """
- Get plugin root directories.
- Priority: project plugins > usr plugins > core plugins
- """
- # Project-specific plugins
- projects = files.find_existing_paths_by_pattern("usr/projects/*/.a0proj/plugins")
-
+ """Plugin root directories, ordered by priority (user first)."""
+ # Project-specific plugins (commented out for now, will add project/agent plugins later)
+ # projects = files.find_existing_paths_by_pattern("usr/projects/*/.a0proj/plugins")
return [
- *projects,
+ # *projects,
files.get_abs_path("usr/plugins"),
files.get_abs_path("plugins"),
]
-def discover_plugin_manifests(root: str) -> List[Path]:
- """Recursively discover plugin.json files under a root directory."""
- root_path = Path(root)
- if not root_path.exists():
- return []
-
- results: List[Path] = []
- for p in root_path.rglob("plugin.json"):
- if p.is_file() and ".git" not in str(p):
- results.append(p)
-
- return sorted(results, key=lambda x: str(x))
-
-
-def plugin_from_manifest(manifest_path: Path) -> Optional[Plugin]:
- """Load plugin from manifest file."""
- try:
- text = manifest_path.read_text(encoding="utf-8", errors="replace")
- manifest = json.loads(text)
- except Exception:
- return None
-
- if not isinstance(manifest, dict):
- return None
-
- plugin_dir = manifest_path.parent
- plugin_id = manifest.get("id", "").strip()
-
- if not plugin_id:
- return None
-
- plugin = Plugin(
- id=plugin_id,
- name=manifest.get("name", plugin_id),
- path=plugin_dir,
- manifest_path=manifest_path,
- provides=manifest.get("provides", {}),
- version=manifest.get("version", ""),
- author=manifest.get("author", ""),
- description=manifest.get("description", ""),
- tags=manifest.get("tags", []),
- raw_manifest=manifest,
- )
-
- return plugin
-
-
-# ============================================================================
-# Registry Access (List/Find)
-# ============================================================================
-
def list_plugins() -> List[Plugin]:
- """List all discovered plugins."""
- plugins: List[Plugin] = []
-
- for root in get_plugin_roots():
- for manifest_path in discover_plugin_manifests(root):
- p = plugin_from_manifest(manifest_path)
- if p:
- plugins.append(p)
-
- # Dedupe by ID (earlier roots win)
+ """Discover plugins by directory convention. First root wins on ID conflict."""
by_id: Dict[str, Plugin] = {}
- for p in plugins:
- if p.id not in by_id:
- by_id[p.id] = p
-
+ for root in get_plugin_roots():
+ root_path = Path(root)
+ if not root_path.exists():
+ continue
+ for d in sorted(root_path.iterdir(), key=lambda p: p.name):
+ if not d.is_dir() or d.name.startswith("."):
+ continue
+ if d.name not in by_id:
+ by_id[d.name] = Plugin(id=d.name, name=d.name, path=d)
return list(by_id.values())
def find_plugin(plugin_id: str) -> Optional[Plugin]:
- """Find a specific plugin by ID."""
+ """Find a single plugin by ID."""
if not plugin_id:
return None
-
- # Search roots in priority order (first one found wins)
- for root in get_plugin_roots():
- for manifest_path in discover_plugin_manifests(root):
- p = plugin_from_manifest(manifest_path)
- if p and p.id == plugin_id:
- return p
-
+ for p in list_plugins():
+ if p.id == plugin_id:
+ return p
return None
-# ============================================================================
-# Path Resolution & Import
-# ============================================================================
-
-def _extract_module_dir(module_path: str) -> str:
- """Extract directory from module path (e.g., 'tools/my_tool.py' -> 'tools')."""
- return str(Path(module_path).parent)
-
-
-def get_plugin_paths(cap_type: str, *subpaths: str) -> List[str]:
+def get_plugin_paths(*subpaths: str) -> List[str]:
"""
- Get all paths from loaded plugins for a given capability type.
- Supports both 'module' (parent dir used) and 'dir' (direct path used) in config.
-
- Args:
- cap_type: Capability type (e.g., "tool", "extension", "api", "agent")
- subpaths: Additional path components to append
-
- Returns:
- List of absolute paths matching the capability type
+ Resolve existing directories under each plugin matching subpaths.
+
+ Example:
+ get_plugin_paths("extensions", "backend", "monologue_end")
+ -> ["/abs/plugins/memory/extensions/backend/monologue_end", ...]
"""
+ sub = "/".join(subpaths) if subpaths else ""
paths: List[str] = []
-
for plugin in list_plugins():
- cap_config = plugin.provides.get(cap_type)
- if not cap_config:
- continue
-
- # Normalize to list for uniform processing
- items = []
- if isinstance(cap_config, list):
- items = [c for c in cap_config if isinstance(c, dict)]
- elif isinstance(cap_config, dict):
- items = [cap_config]
-
- # Build paths from items
- for item in items:
- path_to_add = ""
-
- # Priority 1: Explicit directory
- if item.get("dir"):
- path_to_add = item["dir"]
- # Priority 2: Module parent directory
- elif item.get("module"):
- path_to_add = _extract_module_dir(item["module"])
-
- if path_to_add:
- full_path = files.get_abs_path(str(plugin.path), path_to_add, *subpaths)
- if files.exists(full_path) and full_path not in paths:
- paths.append(full_path)
-
+ candidate = str(plugin.path / sub) if sub else str(plugin.path)
+ if Path(candidate).is_dir() and candidate not in paths:
+ paths.append(candidate)
return paths
-def import_plugin_module(plugin_id: str, module_path: str) -> Any:
+def get_frontend_components() -> List[Dict[str, Any]]:
"""
- Import a Python module from a plugin using importlib.
-
- Args:
- plugin_id: Plugin ID
- module_path: Relative path to module within plugin (e.g., "helpers/memory.py")
-
- Returns:
- The imported module object
-
- Raises:
- ImportError: If plugin or module not found
+ Return all injectable plugin frontend components.
+ Convention: plugins/*/extensions/frontend/**/*.html
+ The backend reads each file to extract the optional
+ <meta name="plugin-target" content=".css-selector"> tag so the
+ frontend never needs to fetch component HTML just to discover targets.
"""
- import importlib.util
- import sys
-
- plugin = find_plugin(plugin_id)
- if not plugin:
- raise ImportError(f"Plugin '{plugin_id}' not found")
-
- full_path = plugin.path / module_path
- if not full_path.exists():
- raise ImportError(f"Module '{module_path}' not found in plugin '{plugin_id}'")
-
- # Create a unique module name to avoid conflicts
- module_name = f"plugins.{plugin_id}.{module_path.replace('/', '.').replace('.py', '')}"
-
- # Check if already loaded
- if module_name in sys.modules:
- return sys.modules[module_name]
-
- # Load the module
- spec = importlib.util.spec_from_file_location(module_name, full_path)
- if spec is None or spec.loader is None:
- raise ImportError(f"Could not load module spec from {full_path}")
-
- module = importlib.util.module_from_spec(spec)
- sys.modules[module_name] = module
- spec.loader.exec_module(module)
-
- return module
-
-
-# ============================================================================
-# API Helpers
-# ============================================================================
-
-def build_plugin_response_data(plugin: Plugin) -> dict:
- """
- Build normalized API response data for a plugin.
- Resolves URLs for UI capabilities.
-
- Args:
- plugin: Plugin object to serialize
-
- Returns:
- Dictionary with plugin data, component_url, module_url, and provides
- """
- base_url = f"/plugins/{plugin.id}/"
-
- response_data = {
- "id": plugin.id,
- "name": plugin.name,
- "base_url": base_url,
- "version": plugin.version,
- "author": plugin.author,
- "description": plugin.description,
- "tags": plugin.tags,
- "provides": plugin.provides,
- }
-
- # Resolve UI capability URLs from provides.ui
- if "ui" in plugin.provides:
- ui_config = plugin.provides["ui"]
- if isinstance(ui_config, dict):
- if ui_config.get("component"):
- response_data["component_url"] = f"{base_url}{ui_config['component']}"
- if ui_config.get("module"):
- response_data["module_url"] = f"{base_url}{ui_config['module']}"
- if ui_config.get("props"):
- response_data["props"] = ui_config["props"]
-
- return response_data
+ entries: List[Dict[str, Any]] = []
+ for plugin in list_plugins():
+ frontend_dir = plugin.path / "extensions" / "frontend"
+ if not frontend_dir.is_dir():
+ continue
+ for html_file in sorted(frontend_dir.rglob("*.html"), key=lambda p: p.name):
+ rel_path = html_file.relative_to(plugin.path).as_posix()
+ entry: Dict[str, Any] = {
+ "plugin_id": plugin.id,
+ "component_url": f"/plugins/{plugin.id}/{rel_path}",
+ }
+ # Extract injection target from meta tag (if present)
+ try:
+ content = html_file.read_text(encoding="utf-8")
+ m = _META_TARGET_RE.search(content)
+ if m:
+ entry["target"] = m.group(1)
+ except Exception:
+ pass
+ entries.append(entry)
+ return entries
diff --git a/python/helpers/projects.py b/python/helpers/projects.py
index 2c0d440ff..40adc0c63 100644
--- a/python/helpers/projects.py
+++ b/python/helpers/projects.py
@@ -477,15 +477,8 @@ def create_project_meta_folders(name: str):
# create instructions folder
files.create_dir(get_project_meta_folder(name, PROJECT_INSTRUCTIONS_DIR))
- # create knowledge folders
+ # create knowledge folders (plugins create their own subdirs lazily)
files.create_dir(get_project_meta_folder(name, PROJECT_KNOWLEDGE_DIR))
- from python.helpers.plugins import import_plugin_module
- memory = import_plugin_module("memory", "helpers/memory.py")
-
- for memory_type in memory.Memory.Area:
- files.create_dir(
- get_project_meta_folder(name, PROJECT_KNOWLEDGE_DIR, memory_type.value)
- )
def get_knowledge_files_count(name: str):
diff --git a/python/helpers/settings.py b/python/helpers/settings.py
index 2d9099302..fa29f65a4 100644
--- a/python/helpers/settings.py
+++ b/python/helpers/settings.py
@@ -623,17 +623,17 @@ def _apply_settings(previous: Settings | None):
whisper.preload, _settings["stt_model_size"]
) # TODO overkill, replace with background task
- # force memory reload on embedding model change
+ # notify plugins of embedding model change
if not previous or (
_settings["embed_model_name"] != previous["embed_model_name"]
or _settings["embed_model_provider"] != previous["embed_model_provider"]
or _settings["embed_model_kwargs"] != previous["embed_model_kwargs"]
):
- from python.helpers.plugins import import_plugin_module
- memory = import_plugin_module("memory", "helpers/memory.py")
- memory_reload = memory.reload
+ from python.helpers.extension import call_extensions
- memory_reload()
+ defer.DeferredTask().start_task(
+ call_extensions, "embedding_model_changed"
+ )
# update mcp settings if necessary
if not previous or _settings["mcp_servers"] != previous["mcp_servers"]:
diff --git a/python/helpers/subagents.py b/python/helpers/subagents.py
index a851fdb23..d9196aca5 100644
--- a/python/helpers/subagents.py
+++ b/python/helpers/subagents.py
@@ -57,13 +57,14 @@ def get_agents_dict(
)
return merged
+ from python.helpers import plugins
+
# load default, plugin, and custom agents and merge
default_agents = _get_agents_list_from_dir(DEFAULT_AGENTS_DIR, origin="default")
merged: dict[str, SubAgentListItem] = dict(default_agents)
# merge with plugin agents
- from python.helpers import plugins
- for plugin_dir in reversed(plugins.get_plugin_paths("agent")):
+ for plugin_dir in plugins.get_plugin_paths("agents"):
plugin_agents = _get_agents_list_from_dir(plugin_dir, origin="plugin")
merged = _merge_agent_dicts(merged, plugin_agents)
@@ -110,6 +111,8 @@ def load_agent_data(name: str, project_name: str | None = None) -> SubAgent:
return original
return override
+ from python.helpers import plugins
+
# load default, plugin, and user agents and merge
default_agent = _load_agent_data_from_dir(
DEFAULT_AGENTS_DIR, name, origin="default"
@@ -117,8 +120,7 @@ def load_agent_data(name: str, project_name: str | None = None) -> SubAgent:
merged = default_agent
# merge with plugin agents
- from python.helpers import plugins
- for plugin_dir in reversed(plugins.get_plugin_paths("agent")):
+ for plugin_dir in plugins.get_plugin_paths("agents"):
plugin_agent = _load_agent_data_from_dir(plugin_dir, name, origin="plugin")
merged = _merge_agent(merged, plugin_agent)
@@ -240,7 +242,7 @@ def _merge_agent_list_items(
def get_agents_roots() -> list[str]:
from python.helpers import plugins
- plugin_agents = list(reversed(plugins.get_plugin_paths("agent")))
+ plugin_agents = plugins.get_plugin_paths("agents")
project_agents = files.find_existing_paths_by_pattern("usr/projects/*/.a0proj/agents")
paths = [
files.get_abs_path(DEFAULT_AGENTS_DIR),
@@ -326,10 +328,11 @@ def get_paths(
include_project: bool = True,
include_user: bool = True,
include_default: bool = True,
+ include_plugins: bool = False,
default_root: str = "",
) -> list[str]:
"""Returns list of file paths for the given agent and subpaths, searched in order of priority:
- project/agents/, project/, usr/agents/, agents/, usr/, default."""
+ project/agents/, project/, usr/agents/, plugin agents/, agents/, usr/, plugins/, default."""
paths: list[str] = []
check_subpaths = subpaths if must_exist_completely else []
profile_name = agent.config.profile if agent and agent.config.profile else ""
@@ -363,7 +366,7 @@ def get_paths(
# plugin agents/<profile>/...
from python.helpers import plugins
- for plugin_dir in plugins.get_plugin_paths("agent"):
+ for plugin_dir in plugins.get_plugin_paths("agents"):
path = files.get_abs_path(plugin_dir, profile_name, *subpaths)
if (not must_exist_completely) or files.exists(files.get_abs_path(plugin_dir, profile_name, *check_subpaths)):
paths.append(path)
@@ -379,6 +382,11 @@ def get_paths(
if (not must_exist_completely) or files.exists(path):
paths.append(path)
+ if include_plugins:
+ # plugins/*/subpaths...
+ plugin_paths = plugins.get_plugin_paths(*subpaths)
+ paths.extend(p for p in plugin_paths if p not in paths)
+
if include_default:
# default_root/...
path = files.get_abs_path(default_root, *subpaths)
diff --git a/python/tools/knowledge_tool._py b/python/tools/knowledge_tool._py
index 1726c372e..386440b6e 100644
--- a/python/tools/knowledge_tool._py
+++ b/python/tools/knowledge_tool._py
@@ -1,9 +1,7 @@
import asyncio
from python.helpers import dotenv, perplexity_search, duckduckgo_search
-from python.helpers.plugins import import_plugin_module
-memory = import_plugin_module("memory", "helpers/memory.py")
-memory_load_tool = import_plugin_module("memory", "tools/memory_load.py")
-DEFAULT_MEMORY_THRESHOLD = memory_load_tool.DEFAULT_THRESHOLD
+from plugins.memory.helpers.memory import Memory
+from plugins.memory.tools.memory_load import DEFAULT_THRESHOLD as DEFAULT_MEMORY_THRESHOLD
from python.helpers.tool import Tool, Response
from python.helpers.document_query import DocumentQueryHelper
@@ -98,11 +96,11 @@ class Knowledge(Tool):
return result
async def mem_search(self, question: str):
- db = await memory.Memory.get(self.agent)
+ db = await Memory.get(self.agent)
docs = await db.search_similarity_threshold(
query=question, limit=5, threshold=DEFAULT_MEMORY_THRESHOLD
)
- text = memory.Memory.format_docs_plain(docs)
+ text = Memory.format_docs_plain(docs)
return "\n\n".join(text)
async def mem_search_enhanced(self, question: str):
@@ -111,7 +109,7 @@ class Knowledge(Tool):
Separates and prioritizes knowledge sources vs conversation memories.
"""
try:
- db = await memory.Memory.get(self.agent)
+ db = await Memory.get(self.agent)
# Search for knowledge sources (knowledge_source=True)
knowledge_docs = await db.search_similarity_threshold(
diff --git a/python/tools/search_engine.py b/python/tools/search_engine.py
index 121a97c60..9891e46b9 100644
--- a/python/tools/search_engine.py
+++ b/python/tools/search_engine.py
@@ -1,8 +1,6 @@
import os
import asyncio
from python.helpers import dotenv, perplexity_search, duckduckgo_search
-from python.helpers.plugins import import_plugin_module
-memory = import_plugin_module("memory", "helpers/memory.py")
from python.helpers.tool import Tool, Response
from python.helpers.print_style import PrintStyle
from python.helpers.errors import handle_error
diff --git a/run_ui.py b/run_ui.py
index 1bbb77e6a..bf8d63d94 100644
--- a/run_ui.py
+++ b/run_ui.py
@@ -468,7 +468,7 @@ def run():
runtime.get_arg("host") or dotenv.get_dotenv_value("WEB_UI_HOST") or "localhost"
)
- def register_api_handler(app, handler: type[ApiHandler]):
+ def register_api_handler(app, handler: type[ApiHandler], url_prefix: str = ""):
name = handler.__module__.split(".")[-1]
instance = handler(app, lock)
@@ -484,9 +484,10 @@ def run():
if handler.requires_csrf():
handler_wrap = csrf_protect(handler_wrap)
+ route = f"{url_prefix}/{name}"
app.add_url_rule(
- f"/{name}",
- f"/{name}",
+ route,
+ route,
handler_wrap,
methods=handler.get_methods(),
)
@@ -495,12 +496,19 @@ def run():
for handler in handlers:
register_api_handler(webapp, handler)
- # Load API handlers from plugins
+ # Load API handlers from plugins (prefixed with /plugins/{plugin_id}/)
from python.helpers import plugins
- plugin_api_paths = plugins.get_plugin_paths("api")
- for api_path in plugin_api_paths:
- plugin_handlers = load_classes_from_folder(api_path, "*.py", ApiHandler)
+
+ for plugin in plugins.list_plugins():
+ api_path = plugin.path / "api"
+ if not api_path.exists() or not api_path.is_dir():
+ continue
+
+ plugin_handlers = load_classes_from_folder(str(api_path), "*.py", ApiHandler)
for handler in plugin_handlers:
+ # prefixed route for explicit namespacing
+ register_api_handler(webapp, handler, url_prefix=f"/plugins/{plugin.id}")
+ # bare route so callers don't need to know the plugin prefix
register_api_handler(webapp, handler)
handlers_by_namespace = _build_websocket_handlers_by_namespace(socketio_server, lock)
diff --git a/webui/components/settings/agent/memory.html b/webui/components/settings/agent/memory.html
index 39bde1993..8b30b42ca 100644
--- a/webui/components/settings/agent/memory.html
+++ b/webui/components/settings/agent/memory.html
@@ -34,7 +34,7 @@
<div class="field-control">
<button
class="btn btn-field"
- @click="openModal('../plugins/memory/ui/memory-dashboard.html');"
+ @click="openModal('../plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html');"
>
Open Dashboard
</button>
diff --git a/webui/components/sidebar/top-section/quick-actions.html b/webui/components/sidebar/top-section/quick-actions.html
index aa6db71cc..1d7a26b81 100644
--- a/webui/components/sidebar/top-section/quick-actions.html
+++ b/webui/components/sidebar/top-section/quick-actions.html
@@ -17,7 +17,7 @@
</button>
<!-- Memory -->
- <button class="config-button" id="memory-dash" @click="openModal('../plugins/memory/ui/memory-dashboard.html')" title="Memory">
+ <button class="config-button" id="memory-dash" @click="openModal('../plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard.html')" title="Memory">
<span class="material-symbols-outlined">psychology</span>
</button>
@@ -53,12 +53,7 @@
<span class="material-symbols-outlined">snippet_folder</span>
<span>Projects</span>
</button>
-
- <button class="dropdown-item" @click="openModal('../plugins/memory/ui/memory-dashboard.html'); dropdownOpen = false">
- <span class="material-symbols-outlined">psychology</span>
- <span>Memories</span>
- </button>
-
+
<button class="dropdown-item" @click="openModal('modals/scheduler/scheduler-modal.html'); dropdownOpen = false">
<span class="material-symbols-outlined">schedule</span>
<span>Scheduler</span>
diff --git a/webui/components/welcome/welcome-store.js b/webui/components/welcome/welcome-store.js
index 6c3e3e808..50bc30c3d 100644
--- a/webui/components/welcome/welcome-store.js
+++ b/webui/components/welcome/welcome-store.js
@@ -1,7 +1,7 @@
import { createStore } from "/js/AlpineStore.js";
import { getContext } from "/index.js";
import { store as chatsStore } from "/components/sidebar/chats/chats-store.js";
-import { store as memoryStore } from "/plugins/memory/ui/memory-dashboard-store.js";
+import { store as memoryStore } from "/plugins/memory/extensions/frontend/memory_dashboard/memory-dashboard-store.js";
import { store as projectsStore } from "/components/projects/projects-store.js";
import { store as chatInputStore } from "/components/chat/input/input-store.js";
import * as API from "/js/api.js";
diff --git a/webui/js/initFw.js b/webui/js/initFw.js
index adeec657e..73fa3815c 100644
--- a/webui/js/initFw.js
+++ b/webui/js/initFw.js
@@ -1,7 +1,7 @@
import * as initializer from "./initializer.js";
import * as _modals from "./modals.js";
import * as _components from "./components.js";
-import * as _plugins from "./plugins.js";
+import "./plugins.js";
import { registerAlpineMagic } from "./confirmClick.js";
// initialize required elements
diff --git a/webui/js/plugins.js b/webui/js/plugins.js
index ac092d380..dff2e4d5e 100644
--- a/webui/js/plugins.js
+++ b/webui/js/plugins.js
@@ -1,215 +1,47 @@
-// Plugin system for Agent Zero
-// Loads x-extension tags by resolving plugin manifests and reusing component infrastructure
-
-import { importComponent, getParentAttributes } from './components.js';
-import { getCsrfToken } from './api.js';
-
-// Cache for plugin manifests
-const extensionCache = {};
-
-// Batch fetch plugin manifests from API
-async function fetchPluginManifests(pluginIds) {
- try {
- const response = await fetch("/plugins_resolve", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "X-CSRF-Token": await getCsrfToken(),
- },
- body: JSON.stringify({ ids: pluginIds }),
- });
-
- if (!response.ok) {
- throw new Error(`Failed to resolve plugins: ${response.statusText}`);
- }
-
- const result = await response.json();
- if (!result.ok || !result.data) {
- throw new Error("Invalid plugins response");
- }
-
- return result.data;
- } catch (error) {
- console.error("Error batch-fetching plugin manifests:", error);
- return [];
- }
-}
-
-// Merge manifest props with element attributes (element attributes override manifest)
-function mergePropsWithAttributes(manifestProps, element) {
- const elementAttrs = {};
- for (let attr of element.attributes) {
- if (attr.name !== "id") {
- try {
- elementAttrs[attr.name] = JSON.parse(attr.value);
- } catch (_e) {
- elementAttrs[attr.name] = attr.value;
- }
- }
- }
- return { ...manifestProps, ...elementAttrs };
-}
-
-// Set merged props as data attributes on element
-function setAttributesOnElement(props, element) {
- for (const [key, value] of Object.entries(props)) {
- if (typeof value === "object") {
- element.setAttribute(key, JSON.stringify(value));
- } else {
- element.setAttribute(key, value);
- }
- }
-}
-
-// Load a single plugin by calling importComponent with manifest URLs
-async function loadPlugin(pluginId, targetElement) {
- // Get manifest from cache
- let manifest = extensionCache[pluginId];
-
- if (!manifest || manifest.error) {
- throw new Error(manifest?.error || `Plugin '${pluginId}' not found`);
- }
-
- // Extract UI configuration from provides.ui
- // The API already resolves component_url and module_url from provides.ui
- const componentUrl = manifest.component_url;
- const moduleUrl = manifest.module_url;
- const props = manifest.props || {};
-
- // Merge props and set as attributes
- const mergedProps = mergePropsWithAttributes(props, targetElement);
- setAttributesOnElement(mergedProps, targetElement);
-
- // Call importComponent with plugin URLs
- // We prepend "components/../" to bypass the check in importComponent
- if (componentUrl) {
- const adjustedUrl = "components/.." + componentUrl;
- await importComponent(adjustedUrl, targetElement);
- }
-
- // Load module if specified
- // Browser's native module cache handles deduplication
- if (moduleUrl) {
- await import(moduleUrl);
- }
-}
-
-// Find all x-extension tags in root elements
-function findAllExtensionTags(roots) {
- const rootElements = Array.isArray(roots) ? roots : [roots];
- return rootElements.flatMap((root) =>
- Array.from(root.querySelectorAll("x-extension"))
- );
-}
-
-// Collect unique plugin IDs that need to be fetched (not in cache)
-function collectUniqueUncachedPluginIds(extensions) {
- const pluginIds = [];
- const seen = new Set();
-
- for (const extension of extensions) {
- const pluginId = extension.getAttribute("id");
- if (!pluginId) {
- console.error("x-extension missing id attribute:", extension);
- continue;
- }
-
- // Only add if not seen and not cached
- if (!seen.has(pluginId) && !extensionCache[pluginId]) {
- pluginIds.push(pluginId);
- seen.add(pluginId);
- }
- }
-
- return pluginIds;
-}
-
-// Main loader: scan DOM, batch fetch manifests, load all plugins
-export async function loadExtensions(roots = [document.documentElement]) {
+// Plugin frontend auto-injection.
+// Imported once in initFw.js. The backend resolves plugin components and their
+// injection targets (parsed from <meta name="plugin-target"> server-side).
+// This module simply creates <x-component> elements at the declared targets;
+// the standard components.js MutationObserver handles loading automatically.
+import { callJsonApi } from "/js/api.js";
+
+const injected = new Set();
+
+function tryInject(entry) {
+ const key = `${entry.component_url}|${entry.target}`;
+ if (injected.has(key)) return true;
+ const host = document.querySelector(entry.target);
+ if (!host) return false;
+ injected.add(key);
+ const el = document.createElement("x-component");
+ el.setAttribute("path", `../${entry.component_url.replace(/^\/+/, "")}`);
+ el.className = "plugin-slot-entry";
+ host.appendChild(el);
+ return true;
+}
+
+(async () => {
+ let res;
try {
- // Find all x-extension tags
- const extensions = findAllExtensionTags(roots);
-
- if (extensions.length === 0) return;
-
- // Collect plugin IDs that need fetching
- const pluginIds = collectUniqueUncachedPluginIds(extensions);
-
- // Batch fetch all uncached manifests in one API call
- if (pluginIds.length > 0) {
- const manifests = await fetchPluginManifests(pluginIds);
-
- // Update cache with fetched manifests
- for (const manifest of manifests) {
- if (!manifest.error) {
- extensionCache[manifest.id] = manifest;
- } else {
- console.error(`Plugin '${manifest.id}' failed to load:`, manifest.error);
- }
+ res = await callJsonApi("/plugins_resolve", {});
+ } catch (e) {
+ console.warn("Plugin resolve failed:", e);
+ return;
+ }
+ if (!res.ok || !Array.isArray(res.data)) return;
+
+ // Only auto-inject entries that declare a target; others are standalone (modals etc.)
+ const pending = res.data.filter(e => e?.component_url && e?.target);
+ const remaining = pending.filter(e => !tryInject(e));
+
+ // Retry for targets that load after initial render (e.g. sidebar components)
+ if (remaining.length > 0) {
+ const obs = new MutationObserver(() => {
+ for (let i = remaining.length - 1; i >= 0; i--) {
+ if (tryInject(remaining[i])) remaining.splice(i, 1);
}
- }
-
- // Map plugin IDs to extension elements for parallel loading
- const extensionMap = new Map();
- for (const extension of extensions) {
- const pluginId = extension.getAttribute("id");
- if (!pluginId) continue;
-
- if (!extensionMap.has(pluginId)) {
- extensionMap.set(pluginId, []);
- }
- extensionMap.get(pluginId).push(extension);
- }
-
- // Load all plugins in parallel using cached manifests
- await Promise.all(
- Array.from(extensionMap.entries()).flatMap(([pluginId, extensionElements]) =>
- extensionElements.map(async (extension) => {
- try {
- await loadPlugin(pluginId, extension);
- } catch (error) {
- console.error(`Error loading extension '${pluginId}':`, error);
- extension.innerHTML = `<div class="error">Failed to load plugin: ${pluginId}</div>`;
- }
- })
- )
- );
- } catch (error) {
- console.error("Error loading extensions:", error);
- }
-}
-
-// Extend global xAttrs to check both x-component and x-extension tags
-// This allows plugins to use globalThis.xAttrs() and get both component and extension attrs
-globalThis.xAttrs = function(el) {
- return getParentAttributes(el, ['x-component', 'x-extension']);
-};
-
-// Initialize when DOM is ready
-if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', () => loadExtensions());
-} else {
- loadExtensions();
-}
-
-// Watch for DOM changes to dynamically load x-extension tags
-const observer = new MutationObserver((mutations) => {
- for (const mutation of mutations) {
- for (const node of mutation.addedNodes) {
- if (node.nodeType === 1) {
- // ELEMENT_NODE
- // Check if this node is an x-extension tag
- if (node.matches?.("x-extension")) {
- loadExtensions([node.parentElement || document.documentElement]);
- } else if (node.querySelectorAll) {
- // Check if descendants contain x-extension tags
- const extensions = node.querySelectorAll("x-extension");
- if (extensions.length > 0) {
- loadExtensions([node]);
- }
- }
- }
- }
+ if (remaining.length === 0) obs.disconnect();
+ });
+ obs.observe(document.body, { childList: true, subtree: true });
}
-});
-observer.observe(document.body, { childList: true, subtree: true });
+})();