Agent Zero AI framework
projects preps
frdelc4bf352d9c52
diff --git a/agent.py b/agent.pyindex cb767a5a0..ae5de3e90 100644--- a/agent.py+++ b/agent.py@@ -53,6 +53,7 @@ class AgentContext:created_at: datetime | None = None,type: AgentContextType = AgentContextType.USER,last_message: datetime | None = None,+ data: dict | None = None,):# build contextself.id = id or AgentContext.generate_id()@@ -67,8 +68,8 @@ class AgentContext:self.type = typeAgentContext._counter += 1self.no = AgentContext._counter- # set to start of unix epochself.last_message = last_message or datetime.now(timezone.utc)+ self.data = data or {}existing = self._contexts.get(self.id, None)if existing:@@ -112,7 +113,15 @@ class AgentContext:context.task.kill()return context- def serialize(self):+ def get_data(self, key: str, recursive: bool = True):+ # recursive is not used now, prepared for context hierarchy+ return self.data.get(key, None)++ def set_data(self, key: str, value: Any, recursive: bool = True):+ # recursive is not used now, prepared for context hierarchy+ self.data[key] = value++ def output(self):return {"id": self.id,"name": self.name,diff --git a/python/api/poll.py b/python/api/poll.pyindex 698321cbd..cfaa74b26 100644--- a/python/api/poll.py+++ b/python/api/poll.py@@ -54,7 +54,7 @@ class Poll(ApiHandler):continue# Create the base context data that will be returned- context_data = ctx.serialize()+ context_data = ctx.output()context_task = scheduler.get_task_by_uuid(ctx.id)# Determine if this is a task-dedicated context by checking if a task with this UUID existsdiff --git a/python/api/projects.py b/python/api/projects.pynew file mode 100644index 000000000..bd0b3bee2--- /dev/null+++ b/python/api/projects.py@@ -0,0 +1,26 @@+from python.helpers.api import ApiHandler, Input, Output, Request, Response+from python.helpers import projects+++class Projects(ApiHandler):+ async def process(self, input: Input, request: Request) -> Output:+ action = input.get("action", "")++ try:+ if action == "list":+ data = self.get_projects_list()+ else:+ raise Exception("Invalid action")++ return {+ "ok": True,+ "data": data,+ }+ except Exception as e:+ return {+ "ok": False,+ "error": str(e),+ }++ async def get_projects_list(self):+ return await projects.get_projects_list()diff --git a/python/helpers/files.py b/python/helpers/files.pyindex c90c701a2..544b520d3 100644--- a/python/helpers/files.py+++ b/python/helpers/files.py@@ -334,6 +334,40 @@ def delete_dir(relative_path: str):# suppress all errors - we're ensuring no errors propagatepass+def move_dir(old_path: str, new_path: str):+ # rename/move the directory from old_path to new_path (both relative)+ abs_old = get_abs_path(old_path)+ abs_new = get_abs_path(new_path)+ if not os.path.isdir(abs_old):+ return # nothing to rename+ try:+ os.rename(abs_old, abs_new)+ except Exception:+ pass # suppress all errors, keep behavior consistent++# move dir safely, remove with number if needed+def move_dir_safe(src, dst):+ base_dst = dst+ i = 2+ while exists(dst):+ dst = f"{base_dst} {i}"+ i += 1+ move_dir(src, dst)+ return dst++# create dir safely, add number if needed+def create_dir_safe(dst):+ base_dst = dst+ i = 2+ while exists(dst):+ dst = f"{base_dst} {i}"+ i += 1+ create_dir(dst)+ return dst++def create_dir(relative_path: str):+ abs_path = get_abs_path(relative_path)+ os.makedirs(abs_path, exist_ok=True)def list_files(relative_path: str, filter: str = "*"):abs_path = get_abs_path(relative_path)diff --git a/python/helpers/projects.py b/python/helpers/projects.pynew file mode 100644index 000000000..9a0927850--- /dev/null+++ b/python/helpers/projects.py@@ -0,0 +1,111 @@+from dataclasses import dataclass+import os+from typing import TypedDict++from torch import ne+from python.helpers import files, dirty_json+from python.helpers.print_style import PrintStyle++PROJECTS_PARENT_DIR = "tmp/projects"+PROJECTS_ARCHIVE_DIR = "tmp/projects-archived"+PROJECT_META_DIR = ".a0proj"+PROJECT_INSTRUCTIONS_DIR = "instructions"+PROJECT_HEADER_FILE = "project.json"+++class BasicProjectData(TypedDict):+ title: str | None+ description: str | None+ instructions: str | None+ color: str | None+++def get_projects_parent_folder():+ return files.get_abs_path(PROJECTS_PARENT_DIR)+++def get_projects_archive_folder():+ return files.get_abs_path(PROJECTS_ARCHIVE_DIR)+++def get_project_folder(name: str):+ return files.get_abs_path(get_projects_parent_folder(), name)+++def get_archived_project_folder(name: str):+ return files.get_abs_path(get_projects_archive_folder(), name)+++def archive_project(name: str):+ return files.move_dir_safe(+ get_project_folder(name), get_archived_project_folder(name)+ )+++def unarchive_project(name: str):+ return files.move_dir_safe(+ get_archived_project_folder(name), get_project_folder(name)+ )+++def delete_project(path: str):+ files.delete_dir(path)+++async def create_project(name: str, data: BasicProjectData):+ new_name = files.create_dir_safe(get_project_folder(name))+ save_project_files(new_name, data)+++async def update_project(path: str, data: BasicProjectData):+ current: BasicProjectData = load_basic_project_data(path) # type: ignore+ current.update(data)+ save_project_files(path, current)+++def load_basic_project_data(path: str) -> BasicProjectData:+ data = dirty_json.parse(+ files.read_file(+ files.get_abs_path(path, PROJECT_HEADER_FILE)+ )+ )+ return data # type: ignore+++def save_project_files(path: str, data: BasicProjectData):+ # save project header file+ header = dirty_json.stringify(data)+ files.write_file(+ files.get_abs_path(path, PROJECT_HEADER_FILE), header+ )++async def get_active_projects_list():+ return await get_projects_list(get_projects_parent_folder())++async def get_archived_projects_list():+ return await get_projects_list(get_projects_archive_folder())++async def get_projects_list(parent_dir):+ projects = []++ # folders in project directory+ for name in os.listdir(parent_dir):+ try:+ path = os.path.join(parent_dir, name)+ if os.path.isdir(path):++ project_data = load_basic_project_data(path)++ projects.append({+ "name": name,+ "path": path,+ "title": project_data.get("title", ""),+ "description": project_data.get("description", ""),+ })+ except Exception as e:+ PrintStyle.error(f"Error loading project {name}: {str(e)}")++ # sort projects by name++ projects.sort(key=lambda x: x["name"])+ return projectsdiff --git a/python/helpers/tokens.py b/python/helpers/tokens.pyindex 622c6d5be..42224a495 100644--- a/python/helpers/tokens.py+++ b/python/helpers/tokens.py@@ -13,7 +13,7 @@ def count_tokens(text: str, encoding_name="cl100k_base") -> int:encoding = tiktoken.get_encoding(encoding_name)# Encode the text and count the tokens- tokens = encoding.encode(text)+ tokens = encoding.encode(text, disallowed_special=())token_count = len(tokens)return token_countdiff --git a/webui/components/projects/project-selector.html b/webui/components/projects/project-selector.htmlnew file mode 100644index 000000000..aa31cdc17--- /dev/null+++ b/webui/components/projects/project-selector.html@@ -0,0 +1,24 @@+<html>++<head>+ <script type="module">+ import { store } from "/components/projects/projectsStore.js";+ </script>+</head>++<body>+ <div x-data>+ <template x-if="$store.projects">+ <div>+ <template x-if="$store.selectedProject">+ <button type="button" class="btn btn-outline-primary" x-text="$store.selectedProject.name"></button>+ </template>+ <template x-if="!$store.selectedProject">+ <button type="button" class="btn btn-outline-secondary">No project</button>+ </template>+ </div>+ </template>+ </div>+</body>++</html>\ No newline at end of filediff --git a/webui/components/projects/projectsStore.js b/webui/components/projects/projectsStore.jsnew file mode 100644index 000000000..ef77ca5dd--- /dev/null+++ b/webui/components/projects/projectsStore.js@@ -0,0 +1,26 @@+import { createStore } from "/js/AlpineStore.js";+import * as api from "/js/api.js";++// define the model object holding data and functions+const model = {+ projectList: [],+ selectedProject: null,++ async loadProjectsList() {+ this.loading = true;+ try {+ const response = await api.callJsonApi("projects", { action: "list" });+ this.projectList = response.data;+ } catch (error) {+ console.error("Error loading projects list:", error);+ } finally {+ this.loading = false;+ }+ },+};++// convert it to alpine store+const store = createStore("projects", model);++// export for use in other files+export { store };diff --git a/webui/index.html b/webui/index.htmlindex 272ac1807..ec2c9c12c 100644--- a/webui/index.html+++ b/webui/index.html@@ -161,6 +161,8 @@</div><!-- Notification Toggle positioned next to time-date --><x-component path="notifications/notification-icons.html"></x-component>+ <!-- Project Selector -->+ <x-component path="projects/project-selector.html"></x-component></div><!-- Message History (actual messages) --><div id="chat-history">