Skip to content

Agent Zero AI framework

v0.9.5-pre cleanup, polishing, bugfixing

frdel0aacdf98bcc0
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 95b62c668..ba8fe79c8 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -12,5 +12,6 @@
"*": ["webui/*"]
},
// Optional: point VSCode to jsconfig.json if you add one
- "jsconfig.json": "${workspaceFolder}/jsconfig.json"
+ "jsconfig.json": "${workspaceFolder}/jsconfig.json",
+ "postman.settings.dotenv-detection-notification-visibility": false
}
\ No newline at end of file
diff --git a/agent.py b/agent.py
index 9354bf7c6..e86cb2f22 100644
--- a/agent.py
+++ b/agent.py
@@ -1,4 +1,4 @@
-import asyncio
+import asyncio, random, string
import nest_asyncio
nest_asyncio.apply()
@@ -55,7 +55,7 @@ class AgentContext:
last_message: datetime | None = None,
):
# build context
- self.id = id or str(uuid.uuid4())
+ self.id = id or AgentContext.generate_id()
self.name = name
self.config = config
self.log = log or Log.Log()
@@ -89,6 +89,15 @@ class AgentContext:
def all():
return list(AgentContext._contexts.values())
+ @staticmethod
+ def generate_id():
+ def generate_short_id():
+ return ''.join(random.choices(string.ascii_letters + string.digits, k=8))
+ while True:
+ short_id = generate_short_id()
+ if short_id not in AgentContext._contexts:
+ return short_id
+
@classmethod
def get_notification_manager(cls):
if cls._notification_manager is None:
@@ -509,29 +518,27 @@ class Agent:
)
return system_prompt
- def parse_prompt(self, file: str, **kwargs):
- prompt_dir = files.get_abs_path("prompts")
- backup_dir = []
+ def parse_prompt(self, _prompt_file: str, **kwargs):
+ dirs = [files.get_abs_path("prompts")]
if (
self.config.profile
): # if agent has custom folder, use it and use default as backup
prompt_dir = files.get_abs_path("agents", self.config.profile, "prompts")
- backup_dir.append(files.get_abs_path("prompts"))
+ dirs.insert(0, prompt_dir)
prompt = files.parse_file(
- files.get_abs_path(prompt_dir, file), _backup_dirs=backup_dir, **kwargs
+ _prompt_file, _directories=dirs, **kwargs
)
return prompt
def read_prompt(self, file: str, **kwargs) -> str:
- prompt_dir = files.get_abs_path("prompts")
- backup_dir = []
+ dirs = [files.get_abs_path("prompts")]
if (
self.config.profile
): # if agent has custom folder, use it and use default as backup
prompt_dir = files.get_abs_path("agents", self.config.profile, "prompts")
- backup_dir.append(files.get_abs_path("prompts"))
+ dirs.insert(0, prompt_dir)
prompt = files.read_prompt_file(
- files.get_abs_path(prompt_dir, file), _backup_dirs=backup_dir, **kwargs
+ file, _directories=dirs, **kwargs
)
prompt = files.remove_code_fences(prompt)
return prompt
@@ -548,11 +555,7 @@ class Agent:
self.last_message = datetime.now(timezone.utc)
# Allow extensions to process content before adding to history
content_data = {"content": content}
- try:
- asyncio.run(self.call_extensions("hist_add_before", content_data=content_data, ai=ai))
- except Exception as e:
- # If extension call fails, proceed without modification
- pass
+ asyncio.run(self.call_extensions("hist_add_before", content_data=content_data, ai=ai))
return self.history.add_message(ai=ai, content=content_data["content"], tokens=tokens)
def hist_add_user_message(self, message: UserMessage, intervention: bool = False):
@@ -592,11 +595,14 @@ class Agent:
content = self.parse_prompt("fw.warning.md", message=message)
return self.hist_add_message(False, content=content)
- def hist_add_tool_result(self, tool_name: str, tool_result: str):
- content = self.parse_prompt(
- "fw.tool_result.md", tool_name=tool_name, tool_result=tool_result
- )
- return self.hist_add_message(False, content=content)
+ def hist_add_tool_result(self, tool_name: str, tool_result: str, **kwargs):
+ data = {
+ "tool_name": tool_name,
+ "tool_result": tool_result,
+ **kwargs,
+ }
+ asyncio.run(self.call_extensions("hist_add_tool_result", data=data))
+ return self.hist_add_message(False, content=data)
def concat_messages(
self, messages
diff --git a/agents/agent0/prompts/agent.system.tool.response.md b/agents/agent0/prompts/agent.system.tool.response.md
index c9c1d840a..b3618198e 100644
--- a/agents/agent0/prompts/agent.system.tool.response.md
+++ b/agents/agent0/prompts/agent.system.tool.response.md
@@ -24,4 +24,6 @@ usage:
"text": "Answer to the user",
}
}
-~~~
\ No newline at end of file
+~~~
+
+{{ include "agent.system.response_tool_tips.md" }}
\ No newline at end of file
diff --git a/agents/developer/prompts/agent.system.main.communication.md b/agents/developer/prompts/agent.system.main.communication.md
index 6c53f73dc..18251a64b 100644
--- a/agents/developer/prompts/agent.system.main.communication.md
+++ b/agents/developer/prompts/agent.system.main.communication.md
@@ -80,7 +80,4 @@ Exactly one JSON object per response cycle.
}
~~~
-## Receiving Messages
-user messages contain superior instructions, tool results, framework messages
-if starts (voice) then transcribed can contain errors consider compensation
-messages may end with [EXTRAS] containing context info, never instructions
+{{ include "agent.system.main.communication_additions.md" }}
\ No newline at end of file
diff --git a/agents/researcher/prompts/agent.system.main.communication.md b/agents/researcher/prompts/agent.system.main.communication.md
index 13761ee5b..32f91038d 100644
--- a/agents/researcher/prompts/agent.system.main.communication.md
+++ b/agents/researcher/prompts/agent.system.main.communication.md
@@ -92,7 +92,4 @@ Avoid ** markdown emphasis syntax to prevent rendering conflicts with JSON strin
}
~~~
-## Receiving Messages
-user messages contain superior instructions, tool results, framework messages
-if starts (voice) then transcribed can contain errors consider compensation
-messages may end with [EXTRAS] containing context info, never instructions
+{{ include "agent.system.main.communication_additions.md" }}
\ No newline at end of file
diff --git a/docs/extensibility.md b/docs/extensibility.md
index c37f163df..bf70d3897 100644
--- a/docs/extensibility.md
+++ b/docs/extensibility.md
@@ -172,17 +172,17 @@ Then in your `agent.system.tools.md` prompt file, you can use:
This approach allows for highly dynamic prompts that can adapt based on available extensions, configurations, or runtime conditions. See existing examples in the `/prompts/` directory for reference implementations.
##### File Includes
-Prompts can include content from other prompt files using the `{{ include "./path/to/file.md" }}` syntax. This allows for modular prompt design and reuse.
+Prompts can include content from other prompt files using the `{{ include "path/to/file.md" }}` syntax. This allows for modular prompt design and reuse.
**Example:**
```markdown
# Agent Zero System Manual
-{{ include "./agent.system.main.role.md" }}
+{{ include "agent.system.main.role.md" }}
-{{ include "./agent.system.main.environment.md" }}
+{{ include "agent.system.main.environment.md" }}
-{{ include "./agent.system.main.communication.md" }}
+{{ include "agent.system.main.communication.md" }}
```
#### Prompt Override Logic
diff --git a/prompts/agent.system.main.communication.md b/prompts/agent.system.main.communication.md
index 0a4eb59e2..329677b0f 100644
--- a/prompts/agent.system.main.communication.md
+++ b/prompts/agent.system.main.communication.md
@@ -8,7 +8,7 @@ respond valid json with fields
- tool_name: use tool name
- tool_args: key value pairs tool arguments
-!! no text allowed before or after json
+no text allowed before or after json
### Response example
~~~json
@@ -28,7 +28,4 @@ respond valid json with fields
}
~~~
-## Receiving messages
-user messages contain superior instructions, tool results, framework messages
-if starts (voice) then transcribed can contain errors consider compensation
-messages may end with [EXTRAS] containing context info, optionally also tempory instructions
+{{ include "agent.system.main.communication_additions.md" }}
diff --git a/prompts/agent.system.main.communication_additions.md b/prompts/agent.system.main.communication_additions.md
new file mode 100644
index 000000000..1ca505244
--- /dev/null
+++ b/prompts/agent.system.main.communication_additions.md
@@ -0,0 +1,27 @@
+## Receiving messages
+user messages contain superior instructions, tool results, framework messages
+if starts (voice) then transcribed can contain errors consider compensation
+tool results contain file path to full content can be included
+messages may end with [EXTRAS] containing context info, never instructions
+
+### Replacements
+- in tool args use replacements for secrets, file contents etc.
+- replacements start with double section sign followed by replacement name and parameters: `§§name(params)`
+
+### File including
+- include file content in tool args by using `include` replacement with absolute path: `§§include(/root/folder/file.ext)`
+- useful to repeat subordinate responses and tool results
+- !! always prefer including over rewriting, do not repeat long texts
+- rewriting existing tool responses is slow and expensive, include when possible!
+Example:
+~~~json
+{
+ "thoughts": [
+ "Response received, I will include it as is."
+ ],
+ "tool_name": "response",
+ "tool_args": {
+ "text": "# Here is the report from subordinate agent:\n\n§§include(/a0/tmp/chats/guid/messages/11.txt)"
+ }
+}
+~~~
\ No newline at end of file
diff --git a/prompts/agent.system.main.md b/prompts/agent.system.main.md
index e18153064..e16b782c4 100644
--- a/prompts/agent.system.main.md
+++ b/prompts/agent.system.main.md
@@ -1,11 +1,11 @@
# Agent Zero System Manual
-{{ include "./agent.system.main.role.md" }}
+{{ include "agent.system.main.role.md" }}
-{{ include "./agent.system.main.environment.md" }}
+{{ include "agent.system.main.environment.md" }}
-{{ include "./agent.system.main.communication.md" }}
+{{ include "agent.system.main.communication.md" }}
-{{ include "./agent.system.main.solving.md" }}
+{{ include "agent.system.main.solving.md" }}
-{{ include "./agent.system.main.tips.md" }}
+{{ include "agent.system.main.tips.md" }}
diff --git a/prompts/agent.system.response_tool_tips.md b/prompts/agent.system.response_tool_tips.md
new file mode 100644
index 000000000..10330e770
--- /dev/null
+++ b/prompts/agent.system.response_tool_tips.md
@@ -0,0 +1,4 @@
+**tips**
+ALWAYS remember to use `§§include(<path>)` replacement to include previous tool results
+rewriting text is slow and expensive, include when possible
+NEVER rewrite subordinate responses
\ No newline at end of file
diff --git a/prompts/agent.system.secrets.md b/prompts/agent.system.secrets.md
index a1995b040..6cd0612f9 100644
--- a/prompts/agent.system.secrets.md
+++ b/prompts/agent.system.secrets.md
@@ -1,6 +1,6 @@
# Secret Placeholders
-- User secrets are masked and used as placeholders
-- Use placeholders in tool calls they will be automatically replaced with actual values
+- user secrets are masked and used as aliases
+- use aliases in tool calls they will be automatically replaced with actual values
You have access to the following secrets:
<secrets>
@@ -8,7 +8,12 @@ You have access to the following secrets:
</secrets>
## Important Guidelines:
-- Use exact placeholder format §§KEY_NAME§§ double section sign markers
-- Values may contain special characters or quotes that may need escaping in code, keep in mind and sanitize in your code if errors occur
-- Comments help understand purpose
+- use exact alias format `§§secret(key_name)`
+- values may contain special characters needing escaping in code, sanitize in your code if errors occur
+- comments help understand purpose
+# Additional variables
+- use these non-sensitive variables as they are when needed
+<variables>
+{{vars}}
+</variables>
diff --git a/prompts/agent.system.tool.call_sub.md b/prompts/agent.system.tool.call_sub.md
index e13231b03..b2e267f93 100644
--- a/prompts/agent.system.tool.call_sub.md
+++ b/prompts/agent.system.tool.call_sub.md
@@ -27,5 +27,8 @@ example usage
}
~~~
+**response handling**
+- you might be part of long chain of subordinates, avoid slow and expensive rewriting subordinate responses, instead use `§§include(<path>)` alias to include the response as is
+
**available profiles:**
{{agent_profiles}}
\ No newline at end of file
diff --git a/prompts/agent.system.tool.call_sub.py b/prompts/agent.system.tool.call_sub.py
index 5bdc134f4..e840cca60 100644
--- a/prompts/agent.system.tool.call_sub.py
+++ b/prompts/agent.system.tool.call_sub.py
@@ -14,7 +14,8 @@ class CallSubordinate(VariablesPlugin):
for agent_subdir in agent_subdirs:
try:
context = files.read_prompt_file(
- files.get_abs_path("agents", agent_subdir, "_context.md")
+ "_context.md",
+ [files.get_abs_path("agents", agent_subdir)]
)
profiles.append({"name": agent_subdir, "context": context})
except Exception as e:
diff --git a/prompts/agent.system.tool.response.md b/prompts/agent.system.tool.response.md
index 1eec56c20..0dba5db48 100644
--- a/prompts/agent.system.tool.response.md
+++ b/prompts/agent.system.tool.response.md
@@ -15,3 +15,5 @@ usage:
}
}
~~~
+
+{{ include "agent.system.response_tool_tips.md" }}
\ No newline at end of file
diff --git a/prompts/agent.system.tools.md b/prompts/agent.system.tools.md
index 218fdb09f..34ca96951 100644
--- a/prompts/agent.system.tools.md
+++ b/prompts/agent.system.tools.md
@@ -1,26 +1,3 @@
## Tools available:
-{{tools}}
-
-## Remarks about calling tools
-Tool calls must always be valid json.
-Tool arguments can contain special placeholders:
-
-### Copy/paste last tool output
-- Include the full output of the previous tool call inside any `tool_args` field by inserting the literal token `{last_tool_output}`. It will be replaced automatically before the tool executes.
-- Check the [EXTRAS] section for a preview and the originating `tool_name`.
-- !! Never repeat the full output of a tool call if it is possible to copy&paste it.
-Example for copying the output of the last tool call into the response tool arguments:
-~~~json
-{
- "thoughts": [
- "Acknowledge system warning about JSON formatting.",
- "Send properly formatted reply using the response tool.",
- "Include the previously collected terminal output by inserting the {last_tool_output} token to avoid duplicating raw text manually."
- ],
- "tool_name": "response",
- "tool_args": {
- "text": "Here is the terminal output you requested:\n\n{last_tool_output}"
- }
-}
-~~~
+{{tools}}
\ No newline at end of file
diff --git a/prompts/fw.extras.last_tool_copy.md b/prompts/fw.extras.last_tool_copy.md
deleted file mode 100644
index 667548888..000000000
--- a/prompts/fw.extras.last_tool_copy.md
+++ /dev/null
@@ -1,2 +0,0 @@
-You can copy and paste the result of the last tool call of {{tool_name}} beginning with "{{last_tool_output_preview}}" into any of the next tool's arguments.
-To paste the full content into any next tool's argument, insert the literal token '{last_tool_output}' in the string where you want the content to appear. It will be replaced automatically before the tool runs.
diff --git a/prompts/fw.hint.call_sub.md b/prompts/fw.hint.call_sub.md
new file mode 100644
index 000000000..b2b310b2d
--- /dev/null
+++ b/prompts/fw.hint.call_sub.md
@@ -0,0 +1 @@
+do not rewrite long responses, use §§include(<file>) instead!
\ No newline at end of file
diff --git a/python/api/chat_reset.py b/python/api/chat_reset.py
index 99032c549..5086aacc1 100644
--- a/python/api/chat_reset.py
+++ b/python/api/chat_reset.py
@@ -12,6 +12,7 @@ class Reset(ApiHandler):
context = self.get_context(ctxid)
context.reset()
persist_chat.save_tmp_chat(context)
+ persist_chat.remove_msg_files(ctxid)
return {
"message": "Agent restarted.",
diff --git a/python/extensions/hist_add_tool_result/_90_save_tool_call_file.py b/python/extensions/hist_add_tool_result/_90_save_tool_call_file.py
new file mode 100644
index 000000000..3aa734cee
--- /dev/null
+++ b/python/extensions/hist_add_tool_result/_90_save_tool_call_file.py
@@ -0,0 +1,37 @@
+from typing import Any
+from python.helpers.extension import Extension
+from python.helpers import files, persist_chat
+import os, re
+
+LEN_MIN = 500
+
+class SaveToolCallFile(Extension):
+ async def execute(self, data: dict[str, Any] | None = None, **kwargs):
+ if not data:
+ return
+
+ # get tool call result
+ result = data.get("tool_result") if isinstance(data, dict) else None
+ if result is None:
+ return
+
+ # skip short results
+ if len(str(result)) < LEN_MIN:
+ return
+
+ # message files directory
+ msgs_folder = persist_chat.get_chat_msg_files_folder(self.agent.context.id)
+ os.makedirs(msgs_folder, exist_ok=True)
+
+ # count the files in the directory
+ last_num = len(os.listdir(msgs_folder))
+
+ # create new file
+ new_file = files.get_abs_path(msgs_folder, f"{last_num+1}.txt")
+ files.write_file(
+ new_file,
+ result,
+ )
+
+ # add the path to the history
+ data["file"] = new_file
diff --git a/python/extensions/message_loop_prompts_after/_75_include_last_tool_copy_paste_tip.py b/python/extensions/message_loop_prompts_after/_75_include_last_tool_copy_paste_tip.py
deleted file mode 100644
index 1aafa5687..000000000
--- a/python/extensions/message_loop_prompts_after/_75_include_last_tool_copy_paste_tip.py
+++ /dev/null
@@ -1,22 +0,0 @@
-from agent import LoopData
-from python.helpers.extension import Extension
-
-
-class IncludeLastToolCopyPasteTip(Extension):
- async def execute(self, loop_data: LoopData = LoopData(), **kwargs):
- last_call = self.agent.get_data("last_tool_call")
- if not last_call:
- return
-
- tool_name: str = last_call.get("tool_name", "")
- last_output: str = last_call.get("last_tool_output", "")
- if not last_output:
- return
-
- preview = (last_output[:50] or "").replace("\n", " ").strip()
- tip = self.agent.read_prompt(
- "fw.extras.last_tool_copy.md",
- tool_name=tool_name,
- last_tool_output_preview=preview,
- )
- loop_data.extras_temporary["last_tool_copy_paste"] = tip
diff --git a/python/extensions/response_stream/_15_replace_last_tool_output_in_stream.py b/python/extensions/response_stream/_15_replace_include_alias.py
similarity index 61%
rename from python/extensions/response_stream/_15_replace_last_tool_output_in_stream.py
rename to python/extensions/response_stream/_15_replace_include_alias.py
index 69d92148b..103ed7114 100644
--- a/python/extensions/response_stream/_15_replace_last_tool_output_in_stream.py
+++ b/python/extensions/response_stream/_15_replace_include_alias.py
@@ -1,24 +1,23 @@
from typing import Any
from python.helpers.extension import Extension
+from python.helpers.strings import replace_file_includes
-class ReplaceLastToolOutputInStream(Extension):
- async def execute(self, loop_data=None, text: str = "", parsed: dict[str, Any] | None = None, **kwargs):
+class ReplaceIncludeAlias(Extension):
+ async def execute(
+ self,
+ loop_data=None,
+ text: str = "",
+ parsed: dict[str, Any] | None = None,
+ **kwargs
+ ):
if not parsed or not isinstance(parsed, dict):
return
- last_call = self.agent.get_data("last_tool_call") or {}
- last_output = last_call.get("last_tool_output", "")
- if not last_output:
- return
-
- tokens = ("{last_tool_output}", "{{last_tool_output}}")
-
def replace_placeholders(value: Any) -> Any:
if isinstance(value, str):
new_val = value
- for token in tokens:
- new_val = new_val.replace(token, last_output)
+ new_val = replace_file_includes(new_val, r"§§include\(([^)]+)\)")
return new_val
if isinstance(value, dict):
return {k: replace_placeholders(v) for k, v in value.items()}
diff --git a/python/extensions/system_prompt/_10_system_prompt.py b/python/extensions/system_prompt/_10_system_prompt.py
index d55d3f44d..eb0089779 100644
--- a/python/extensions/system_prompt/_10_system_prompt.py
+++ b/python/extensions/system_prompt/_10_system_prompt.py
@@ -2,6 +2,7 @@ from typing import Any
from python.helpers.extension import Extension
from python.helpers.mcp_handler import MCPConfig
from agent import Agent, LoopData
+from python.helpers.settings import get_settings
class SystemPrompt(Extension):
@@ -49,7 +50,8 @@ def get_secrets_prompt(agent: Agent):
from python.helpers.secrets import SecretsManager
secrets_manager = SecretsManager.get_instance()
secrets = secrets_manager.get_secrets_for_prompt()
- return agent.read_prompt("agent.system.secrets.md", secrets=secrets)
+ vars = get_settings()["variables"]
+ return agent.read_prompt("agent.system.secrets.md", secrets=secrets, vars=vars)
except Exception as e:
# If secrets module is not available or has issues, return empty string
return ""
diff --git a/python/extensions/tool_execute_after/_90_store_last_tool_call.py b/python/extensions/tool_execute_after/_90_store_last_tool_call.py
deleted file mode 100644
index 34dde8ab6..000000000
--- a/python/extensions/tool_execute_after/_90_store_last_tool_call.py
+++ /dev/null
@@ -1,26 +0,0 @@
-from typing import Any
-from python.helpers.extension import Extension
-
-
-class StoreLastToolCall(Extension):
- async def execute(self, response_data: dict[str, Any] | None = None, tool_name: str = "", tool_args: dict[str, Any] | None = None, **kwargs):
- if not response_data:
- return
-
- response = response_data.get("response") if isinstance(response_data, dict) else None
- if response is None:
- return
-
- try:
- message = getattr(response, "message") if hasattr(response, "message") else str(response)
- except Exception:
- message = str(response)
-
- self.agent.set_data(
- "last_tool_call",
- {
- "tool_name": tool_name or "",
- "tool_args": tool_args or {},
- "last_tool_output": message or "",
- },
- )
diff --git a/python/helpers/files.py b/python/helpers/files.py
index 02827c6c0..c90c701a2 100644
--- a/python/helpers/files.py
+++ b/python/helpers/files.py
@@ -1,6 +1,7 @@
from abc import ABC, abstractmethod
from fnmatch import fnmatch
import json
+from ntpath import isabs
import os
import sys
import re
@@ -29,10 +30,10 @@ def load_plugin_variables(file: str, backup_dirs: list[str] | None = None) -> di
backup_dirs = []
try:
- plugin_file = find_file_in_dirs(
- get_abs_path(dirname(file), basename(file, ".md") + ".py"),
- backup_dirs
- )
+ # Create filename and directories list
+ plugin_filename = basename(file, ".md") + ".py"
+ directories = [dirname(file)] + backup_dirs
+ plugin_file = find_file_in_dirs(plugin_filename, directories)
except FileNotFoundError:
plugin_file = None
@@ -72,12 +73,12 @@ def load_plugin_variables(file: str, backup_dirs: list[str] | None = None) -> di
from python.helpers.strings import sanitize_string
-def parse_file(_relative_path, _backup_dirs=None, _encoding="utf-8", **kwargs):
- if _backup_dirs is None:
- _backup_dirs = []
+def parse_file(_filename: str, _directories: list[str] | None = None, _encoding="utf-8", **kwargs):
+ if _directories is None:
+ _directories = []
- # Try to get the absolute path for the file from the original directory or backup directories
- absolute_path = find_file_in_dirs(_relative_path, _backup_dirs)
+ # Find the file in the directories
+ absolute_path = find_file_in_dirs(_filename, _directories)
# Read the file content
with open(absolute_path, "r", encoding=_encoding) as f:
@@ -86,7 +87,7 @@ def parse_file(_relative_path, _backup_dirs=None, _encoding="utf-8", **kwargs):
is_json = is_full_json_template(content)
content = remove_code_fences(content)
- variables = load_plugin_variables(_relative_path, _backup_dirs) or {} # type: ignore
+ variables = load_plugin_variables(absolute_path, _directories) or {} # type: ignore
variables.update(kwargs)
if is_json:
content = replace_placeholders_json(content, **variables)
@@ -98,24 +99,30 @@ def parse_file(_relative_path, _backup_dirs=None, _encoding="utf-8", **kwargs):
# Process include statements
content = process_includes(
# here we use kwargs, the plugin variables are not inherited
- content, os.path.dirname(_relative_path), _backup_dirs, **kwargs
+ content, _directories, **kwargs
)
return content
-def read_prompt_file(_relative_path, _backup_dirs=None, _encoding="utf-8", **kwargs):
- if _backup_dirs is None:
- _backup_dirs = []
+def read_prompt_file(_file: str, _directories: list[str] | None = None, _encoding="utf-8", **kwargs):
+ if _directories is None:
+ _directories = []
- # Try to get the absolute path for the file from the original directory or backup directories
- absolute_path = find_file_in_dirs(_relative_path, _backup_dirs)
+ # If filename contains folder path, extract it and add to directories
+ if os.path.dirname(_file):
+ folder_path = os.path.dirname(_file)
+ _file = os.path.basename(_file)
+ _directories = [folder_path] + _directories
+
+ # Find the file in the directories
+ absolute_path = find_file_in_dirs(_file, _directories)
# Read the file content
with open(absolute_path, "r", encoding=_encoding) as f:
# content = remove_code_fences(f.read())
content = f.read()
- variables = load_plugin_variables(_relative_path, _backup_dirs) or {} # type: ignore
+ variables = load_plugin_variables(_file, _directories) or {} # type: ignore
variables.update(kwargs)
# Replace placeholders with values from kwargs
@@ -124,43 +131,33 @@ def read_prompt_file(_relative_path, _backup_dirs=None, _encoding="utf-8", **kwa
# Process include statements
content = process_includes(
# here we use kwargs, the plugin variables are not inherited
- content, os.path.dirname(_relative_path), _backup_dirs, **kwargs
+ content, _directories, **kwargs
)
return content
-def read_file(relative_path:str, backup_dirs:list[str]|None=None, encoding="utf-8"):
- if backup_dirs is None:
- backup_dirs = []
-
+def read_file(relative_path:str, encoding="utf-8"):
# Try to get the absolute path for the file from the original directory or backup directories
- absolute_path = find_file_in_dirs(relative_path, backup_dirs)
+ absolute_path = get_abs_path(relative_path)
# Read the file content
with open(absolute_path, "r", encoding=encoding) as f:
return f.read()
-def read_file_bin(relative_path:str, backup_dirs:list[str]|None=None):
- if backup_dirs is None:
- backup_dirs = []
-
+def read_file_bin(relative_path:str):
# Try to get the absolute path for the file from the original directory or backup directories
- absolute_path = find_file_in_dirs(relative_path, backup_dirs)
+ absolute_path = get_abs_path(relative_path)
# read binary content
with open(absolute_path, "rb") as f:
return f.read()
-def read_file_base64(relative_path, backup_dirs:list[str]|None=None):
- # init backup dirs
- if backup_dirs is None:
- backup_dirs = []
-
+def read_file_base64(relative_path):
# get absolute path
- absolute_path = find_file_in_dirs(relative_path, backup_dirs)
+ absolute_path = get_abs_path(relative_path)
# read binary content and encode to base64
with open(absolute_path, "rb") as f:
@@ -214,7 +211,7 @@ def replace_placeholders_dict(_content: dict, **kwargs):
return replace_value(_content)
-def process_includes(_content, _base_path, _backup_dirs, **kwargs):
+def process_includes(_content: str, _directories: list[str], **kwargs):
# Regex to find {{ include 'path' }} or {{include'path'}}
include_pattern = re.compile(r"{{\s*include\s*['\"](.*?)['\"]\s*}}")
@@ -223,41 +220,32 @@ def process_includes(_content, _base_path, _backup_dirs, **kwargs):
# if the path is absolute, do not process it
if os.path.isabs(include_path):
return match.group(0)
- # First attempt to resolve the include relative to the base path
- full_include_path = find_file_in_dirs(
- os.path.join(_base_path, include_path), _backup_dirs
- )
-
- # Recursively read the included file content, keeping the original base path
- included_content = read_prompt_file(full_include_path, _backup_dirs, **kwargs)
- return included_content
+ # Search for the include file in the directories
+ try:
+ included_content = read_prompt_file(include_path, _directories, **kwargs)
+ return included_content
+ except FileNotFoundError:
+ return match.group(0) # Return original if file not found
# Replace all includes with the file content
return re.sub(include_pattern, replace_include, _content)
-def find_file_in_dirs(file_path, backup_dirs):
+def find_file_in_dirs(_filename: str, _directories: list[str]):
"""
- This function tries to find the file first in the given file_path,
- and then in the backup_dirs if not found in the original location.
- Returns the absolute path of the found file.
+ This function searches for a filename in a list of directories in order.
+ Returns the absolute path of the first found file.
"""
- # Try the original path first
- if os.path.isfile(get_abs_path(file_path)):
- return get_abs_path(file_path)
-
- # Loop through the backup directories
- for backup_dir in backup_dirs:
- # backup path should be os.path.join(backup_dir, file_path) but that can lead to problems
- # with absolute paths in file_path. So we use basename.
- # This means that we don't support include paths like "subdir/something.md" from backups
- backup_path = os.path.join(backup_dir, os.path.basename(file_path))
- if os.path.isfile(get_abs_path(backup_path)):
- return get_abs_path(backup_path)
-
- # If the file is not found, let it raise the FileNotFoundError
+ # Loop through the directories in order
+ for directory in _directories:
+ # Create full path
+ full_path = get_abs_path(directory, _filename)
+ if exists(full_path):
+ return full_path
+
+ # If the file is not found, raise FileNotFoundError
raise FileNotFoundError(
- f"File '{file_path}' not found in the original path or backup directories."
+ f"File '{_filename}' not found in any of the provided directories."
)
def get_unique_filenames_in_dirs(dir_paths: list[str], pattern: str = "*"):
diff --git a/python/helpers/history.py b/python/helpers/history.py
index 421809b18..fb30fcd05 100644
--- a/python/helpers/history.py
+++ b/python/helpers/history.py
@@ -295,6 +295,7 @@ class History(Record):
def __init__(self, agent):
from agent import Agent
+ self.counter = 0
self.bulks: list[Bulk] = []
self.topics: list[Topic] = []
self.current = Topic(history=self)
@@ -324,6 +325,7 @@ class History(Record):
def add_message(
self, ai: bool, content: MessageContent, tokens: int = 0
) -> Message:
+ self.counter += 1
return self.current.add_message(ai, content=content, tokens=tokens)
def new_topic(self):
@@ -340,6 +342,7 @@ class History(Record):
@staticmethod
def from_dict(data: dict, history: "History"):
+ history.counter = data.get("counter", 0)
history.bulks = [Bulk.from_dict(b, history=history) for b in data["bulks"]]
history.topics = [Topic.from_dict(t, history=history) for t in data["topics"]]
history.current = Topic.from_dict(data["current"], history=history)
@@ -348,6 +351,7 @@ class History(Record):
def to_dict(self):
return {
"_cls": "History",
+ "counter": self.counter,
"bulks": [b.to_dict() for b in self.bulks],
"topics": [t.to_dict() for t in self.topics],
"current": self.current.to_dict(),
diff --git a/python/helpers/mcp_handler.py b/python/helpers/mcp_handler.py
index b71af7acf..b4f25736f 100644
--- a/python/helpers/mcp_handler.py
+++ b/python/helpers/mcp_handler.py
@@ -156,35 +156,35 @@ class MCPTool(Tool):
raw_tool_response = "[Tool returned no textual content]"
# Prepare user message context
- user_message_text = (
- "No specific user message context available for this exact step."
- )
- if (
- self.agent
- and self.agent.last_user_message
- and self.agent.last_user_message.content
- ):
- content = self.agent.last_user_message.content
- if isinstance(content, dict):
- # Attempt to get a 'message' field, otherwise stringify the dict
- user_message_text = str(content.get(
- "message", json.dumps(content, indent=2)
- ))
- elif isinstance(content, str):
- user_message_text = content
- else:
- # Fallback for any other types (e.g. list, if that were possible for content)
- user_message_text = str(content)
-
- # Ensure user_message_text is a string before length check and slicing
- user_message_text = str(user_message_text)
-
- # Truncate user message context if it's too long to avoid overwhelming the prompt
- max_user_context_len = 500 # characters
- if len(user_message_text) > max_user_context_len:
- user_message_text = (
- user_message_text[:max_user_context_len] + "... (truncated)"
- )
+ # user_message_text = (
+ # "No specific user message context available for this exact step."
+ # )
+ # if (
+ # self.agent
+ # and self.agent.last_user_message
+ # and self.agent.last_user_message.content
+ # ):
+ # content = self.agent.last_user_message.content
+ # if isinstance(content, dict):
+ # # Attempt to get a 'message' field, otherwise stringify the dict
+ # user_message_text = str(content.get(
+ # "message", json.dumps(content, indent=2)
+ # ))
+ # elif isinstance(content, str):
+ # user_message_text = content
+ # else:
+ # # Fallback for any other types (e.g. list, if that were possible for content)
+ # user_message_text = str(content)
+
+ # # Ensure user_message_text is a string before length check and slicing
+ # user_message_text = str(user_message_text)
+
+ # # Truncate user message context if it's too long to avoid overwhelming the prompt
+ # max_user_context_len = 500 # characters
+ # if len(user_message_text) > max_user_context_len:
+ # user_message_text = (
+ # user_message_text[:max_user_context_len] + "... (truncated)"
+ # )
final_text_for_agent = raw_tool_response
diff --git a/python/helpers/persist_chat.py b/python/helpers/persist_chat.py
index f6ea35bb2..290bf9c87 100644
--- a/python/helpers/persist_chat.py
+++ b/python/helpers/persist_chat.py
@@ -26,6 +26,8 @@ def get_chat_folder_path(ctxid: str):
"""
return files.get_abs_path(CHATS_FOLDER, ctxid)
+def get_chat_msg_files_folder(ctxid: str):
+ return files.get_abs_path(get_chat_folder_path(ctxid), "messages")
def save_tmp_chat(context: AgentContext):
"""Save context to the chats folder"""
@@ -107,6 +109,12 @@ def remove_chat(ctxid):
files.delete_dir(path)
+def remove_msg_files(ctxid):
+ """Remove all message files for a chat or task context"""
+ path = get_chat_msg_files_folder(ctxid)
+ files.delete_dir(path)
+
+
def _serialize_context(context: AgentContext):
# serialize agents
agents = []
@@ -119,12 +127,14 @@ def _serialize_context(context: AgentContext):
"id": context.id,
"name": context.name,
"created_at": (
- context.created_at.isoformat() if context.created_at
+ context.created_at.isoformat()
+ if context.created_at
else datetime.fromtimestamp(0).isoformat()
),
"type": context.type.value,
"last_message": (
- context.last_message.isoformat() if context.last_message
+ context.last_message.isoformat()
+ if context.last_message
else datetime.fromtimestamp(0).isoformat()
),
"agents": agents,
diff --git a/python/helpers/secrets.py b/python/helpers/secrets.py
index 8b2c4b6c2..a4b58c51c 100644
--- a/python/helpers/secrets.py
+++ b/python/helpers/secrets.py
@@ -4,13 +4,19 @@ import time
import os
from io import StringIO
from dataclasses import dataclass
-from typing import Dict, Optional, List, Literal, Set
+from typing import Dict, Optional, List, Literal, Set, Callable
from dotenv.parser import parse_stream
from python.helpers.errors import RepairableException
from python.helpers import files
-KEY_DELIMITER = "§§"
+# New alias-based placeholder format §§secret(KEY)
+ALIAS_PATTERN = r"§§secret\(([A-Za-z_][A-Za-z0-9_]*)\)"
+
+def alias_for_key(key: str, placeholder: str = "§§secret({key})") -> str:
+ # Return alias string for given key in upper-case
+ key = key.upper()
+ return placeholder.format(key=key)
@dataclass
class EnvLine:
@@ -27,7 +33,7 @@ class EnvLine:
class StreamingSecretsFilter:
"""Stateful streaming filter that masks secrets on the fly.
- - Replaces full secret values with placeholders §§KEY§§ when detected.
+ - Replaces full secret values with placeholders §§secret(KEY) when detected.
- Holds the longest suffix of the current buffer that matches any secret prefix
(with minimum trigger length of 3) to avoid leaking partial secrets across chunks.
- On finalize(), any unresolved partial is masked with '***'.
@@ -59,7 +65,7 @@ class StreamingSecretsFilter:
continue
key = self.value_to_key.get(val, "")
if key:
- text = text.replace(val, f"{KEY_DELIMITER}{key}{KEY_DELIMITER}")
+ text = text.replace(val, alias_for_key(key))
return text
def _longest_suffix_prefix(self, text: str) -> int:
@@ -113,7 +119,7 @@ class StreamingSecretsFilter:
class SecretsManager:
SECRETS_FILE = "tmp/secrets.env"
- PLACEHOLDER_PATTERN = rf"{KEY_DELIMITER}([A-Za-z_][A-Za-z0-9_]*){KEY_DELIMITER}"
+ PLACEHOLDER_PATTERN = ALIAS_PATTERN
MASK_VALUE = "***"
_instance: Optional["SecretsManager"] = None
@@ -224,7 +230,7 @@ class SecretsManager:
with_comments=True,
with_blank=True,
with_other=True,
- key_delimiter=KEY_DELIMITER,
+ key_formatter=alias_for_key,
)
def create_streaming_filter(self) -> "StreamingSecretsFilter":
@@ -246,7 +252,7 @@ class SecretsManager:
else:
available_keys = ", ".join(secrets.keys())
error_msg = (
- f"Secret placeholder '{KEY_DELIMITER}{key}{KEY_DELIMITER}' not found in secrets store.\n"
+ f"Secret placeholder '{alias_for_key(key)}' not found in secrets store.\n"
)
error_msg += f"Available secrets: {available_keys}"
@@ -254,7 +260,23 @@ class SecretsManager:
return re.sub(self.PLACEHOLDER_PATTERN, replacer, text)
- def mask_values(self, text: str) -> str:
+ def change_placeholders(self, text: str, new_format: str) -> str:
+ """Substitute secret placeholders with a different placeholder format"""
+ if not text:
+ return text
+
+ secrets = self.load_secrets()
+ result = text
+
+ # Sort by length (longest first) to avoid partial replacements
+ for key, _value in sorted(
+ secrets.items(), key=lambda x: len(x[1]), reverse=True
+ ):
+ result = result.replace(alias_for_key(key), new_format.format(key=key))
+
+ return result
+
+ def mask_values(self, text: str, min_length: int = 4, placeholder: str = "§§secret({key})") -> str:
"""Replace actual secret values with placeholders in text"""
if not text:
return text
@@ -266,8 +288,8 @@ class SecretsManager:
for key, value in sorted(
secrets.items(), key=lambda x: len(x[1]), reverse=True
):
- if value and len(value.strip()) > 0:
- result = result.replace(value, f"{KEY_DELIMITER}{key}{KEY_DELIMITER}")
+ if value and len(value.strip()) >= min_length:
+ result = result.replace(value, alias_for_key(key, placeholder))
return result
@@ -377,17 +399,19 @@ class SecretsManager:
with_blank=True,
with_other=True,
key_delimiter="",
+ key_formatter: Optional[Callable[[str], str]] = None,
) -> str:
out: List[str] = []
for ln in lines:
if ln.type == "pair" and ln.key is not None:
- left = ln.key_part if ln.key_part is not None else ln.key
- left = left.upper()
+ left_raw = ln.key_part if ln.key_part is not None else ln.key
+ left = left_raw.upper()
val = ln.value if ln.value is not None else ""
comment = ln.inline_comment or ""
- out.append(
- f"{key_delimiter}{left}{key_delimiter}{'="'+val+'"' if with_values else ""}{" " + comment if with_comments and comment else ""}"
- )
+ formatted_key = key_formatter(left) if key_formatter else f"{key_delimiter}{left}{key_delimiter}"
+ val_part = f'="{val}"' if with_values else ""
+ comment_part = f" {comment}" if with_comments and comment else ""
+ out.append(f"{formatted_key}{val_part}{comment_part}")
elif ln.type == "blank" and with_blank:
out.append(ln.raw)
elif ln.type == "comment" and with_comments:
diff --git a/python/helpers/settings.py b/python/helpers/settings.py
index db4d9b780..4fb19ed6e 100644
--- a/python/helpers/settings.py
+++ b/python/helpers/settings.py
@@ -103,6 +103,7 @@ class Settings(TypedDict):
a2a_server_enabled: bool
+ variables: str
secrets: str
class PartialSettings(Settings, total=False):
@@ -1068,10 +1069,19 @@ def convert_out(settings: Settings) -> SettingsOutput:
except Exception:
secrets = ""
+ secrets_fields.append({
+ "id": "variables",
+ "title": "Variables Store",
+ "description": "Store non-sensitive variables in .env format e.g. EMAIL_IMAP_SERVER=\"imap.gmail.com\", one item per line. You can use comments starting with # to add descriptions for the agent. See <a href=\"javascript:openModal('settings/secrets/example-vars.html')\">example</a>.<br>These variables are visible to LLMs and in chat history, they are not being masked.",
+ "type": "textarea",
+ "value": settings["variables"].strip(),
+ "style": "height: 20em",
+ })
+
secrets_fields.append({
"id": "secrets",
"title": "Secrets Store",
- "description": "Store secrets and credentials in .env format e.g. EMAIL_PASSWORD=\"s3cret-p4$$w0rd\", one item per line. You can use comments starting with # to add descriptions for the agent. See <a href=\"javascript:openModal('settings/secrets/example.html')\">example</a>.",
+ "description": "Store secrets and credentials in .env format e.g. EMAIL_PASSWORD=\"s3cret-p4$$w0rd\", one item per line. You can use comments starting with # to add descriptions for the agent. See <a href=\"javascript:openModal('settings/secrets/example-secrets.html')\">example</a>.<br>These variables are not visile to LLMs and in chat history, they are being masked. ⚠️ only values with length >= 4 are being masked to prevent false positives. ",
"type": "textarea",
"value": secrets,
"style": "height: 20em",
@@ -1440,6 +1450,7 @@ def get_default_settings() -> Settings:
mcp_server_enabled=False,
mcp_server_token=create_auth_token(),
a2a_server_enabled=False,
+ variables="",
secrets="",
)
diff --git a/python/helpers/strings.py b/python/helpers/strings.py
index 2dc250d06..1144b1f3b 100644
--- a/python/helpers/strings.py
+++ b/python/helpers/strings.py
@@ -1,6 +1,7 @@
import re
import sys
import time
+from python.helpers import files
def sanitize_string(s: str, encoding: str = "utf-8") -> str:
# Replace surrogates and invalid unicode with replacement character
@@ -155,4 +156,21 @@ def truncate_text_by_ratio(text: str, threshold: int, replacement: str = "...",
# Replace in middle based on ratio
start_len = int(available_space * ratio)
end_len = available_space - start_len
- return text[:start_len] + replacement + text[-end_len:]
\ No newline at end of file
+ return text[:start_len] + replacement + text[-end_len:]
+
+
+def replace_file_includes(text: str, placeholder_pattern: str = r"§§include\(([^)]+)\)") -> str:
+ # Replace include aliases with file content
+ if not text:
+ return text
+
+ def _repl(match):
+ path = match.group(1)
+ try:
+ # read file content
+ return files.read_file(path)
+ except Exception:
+ # if file not readable keep original placeholder
+ return match.group(0)
+
+ return re.sub(placeholder_pattern, _repl, text)
\ No newline at end of file
diff --git a/python/helpers/tool.py b/python/helpers/tool.py
index d993eff41..5825958ef 100644
--- a/python/helpers/tool.py
+++ b/python/helpers/tool.py
@@ -1,5 +1,6 @@
from abc import abstractmethod
from dataclasses import dataclass
+from typing import Any
from agent import Agent, LoopData
from python.helpers.print_style import PrintStyle
@@ -10,6 +11,7 @@ from python.helpers.strings import sanitize_string
class Response:
message:str
break_loop: bool
+ additional: dict[str, Any] | None = None
class Tool:
@@ -36,7 +38,7 @@ class Tool:
async def after_execution(self, response: Response, **kwargs):
text = sanitize_string(response.message.strip())
- self.agent.hist_add_tool_result(self.name, text)
+ self.agent.hist_add_tool_result(self.name, text, **(response.additional or {}))
PrintStyle(font_color="#1B4F72", background_color="white", padding=True, bold=True).print(f"{self.agent.agent_name}: Response from tool '{self.name}'")
PrintStyle(font_color="#85C1E9").print(text)
self.log.update(content=text)
diff --git a/python/tools/a2a_chat.py b/python/tools/a2a_chat.py
index 6ee664449..a7cfcc0b0 100644
--- a/python/tools/a2a_chat.py
+++ b/python/tools/a2a_chat.py
@@ -1,10 +1,6 @@
from python.helpers.tool import Tool, Response
from python.helpers.print_style import PrintStyle
-
-try:
- from python.helpers.fasta2a_client import connect_to_agent, is_client_available # type: ignore
-except ImportError: # pragma: no cover – client helper missing
- is_client_available = lambda: False # type: ignore
+from python.helpers.fasta2a_client import connect_to_agent, is_client_available
class A2AChatTool(Tool):
diff --git a/python/tools/browser_agent.py b/python/tools/browser_agent.py
index f0d894d73..7a5b472e7 100644
--- a/python/tools/browser_agent.py
+++ b/python/tools/browser_agent.py
@@ -191,6 +191,7 @@ class BrowserAgent(Tool):
self.guid = str(uuid.uuid4())
reset = str(reset).lower().strip() == "true"
await self.prepare_state(reset=reset)
+ message = SecretsManager.get_instance().mask_values(message, placeholder="<secret>{key}</secret>") # mask any potential passwords passed from A0 to browser-use to browser-use format
task = self.state.start_task(message) if self.state else None
# wait for browser agent to finish and update progress with timeout
diff --git a/python/tools/call_subordinate.py b/python/tools/call_subordinate.py
index 3b316fc51..dd19b40ce 100644
--- a/python/tools/call_subordinate.py
+++ b/python/tools/call_subordinate.py
@@ -1,6 +1,7 @@
from agent import Agent, UserMessage
from python.helpers.tool import Tool, Response
from initialize import initialize_agent
+from python.extensions.hist_add_tool_result import _90_save_tool_call_file as save_tool_call_file
class Delegation(Tool):
@@ -26,16 +27,21 @@ class Delegation(Tool):
self.agent.set_data(Agent.DATA_NAME_SUBORDINATE, sub)
# add user message to subordinate agent
- subordinate: Agent = self.agent.get_data(Agent.DATA_NAME_SUBORDINATE) # type: ignore
+ subordinate: Agent = self.agent.get_data(Agent.DATA_NAME_SUBORDINATE) # type: ignore
subordinate.hist_add_user_message(UserMessage(message=message, attachments=[]))
-
-
# run subordinate monologue
result = await subordinate.monologue()
+ # hint to use includes for long responses
+ additional = None
+ if len(result) >= save_tool_call_file.LEN_MIN:
+ hint = self.agent.read_prompt("fw.hint.call_sub.md")
+ if hint:
+ additional = {"hint": hint}
+
# result
- return Response(message=result, break_loop=False)
+ return Response(message=result, break_loop=False, additional=additional)
def get_log_object(self):
return self.agent.context.log.log(
@@ -43,4 +49,4 @@ class Delegation(Tool):
heading=f"icon://communication {self.agent.agent_name}: Calling Subordinate Agent",
content="",
kvps=self.args,
- )
\ No newline at end of file
+ )
diff --git a/python/tools/code_execution_tool.py b/python/tools/code_execution_tool.py
index 07ee02396..0b0a05416 100644
--- a/python/tools/code_execution_tool.py
+++ b/python/tools/code_execution_tool.py
@@ -74,7 +74,7 @@ class CodeExecution(Tool):
return f"icon://terminal {session_text}{text}"
async def after_execution(self, response, **kwargs):
- self.agent.hist_add_tool_result(self.name, response.message)
+ self.agent.hist_add_tool_result(self.name, response.message, **(response.additional or {}))
async def prepare_state(self, reset=False, session: int | None = None):
self.state: State | None = self.agent.get_data("_cet_state")
@@ -372,5 +372,5 @@ class CodeExecution(Tool):
output = re.sub(r"(?<!\\)\\x[0-9A-Fa-f]{2}", "", output)
# Strip every line of output before truncation
output = "\n".join(line.strip() for line in output.splitlines())
- output = truncate_text_agent(agent=self.agent, output=output, threshold=10000)
+ output = truncate_text_agent(agent=self.agent, output=output, threshold=1000000) # ~1MB, larger outputs should be dumped to file, not read from terminal
return output
diff --git a/python/tools/input.py b/python/tools/input.py
index 7452b6770..7d99a9285 100644
--- a/python/tools/input.py
+++ b/python/tools/input.py
@@ -23,4 +23,4 @@ class Input(Tool):
return self.agent.context.log.log(type="code_exe", heading=f"icon://keyboard {self.agent.agent_name}: Using tool '{self.name}'", content="", kvps=self.args)
async def after_execution(self, response, **kwargs):
- self.agent.hist_add_tool_result(self.name, response.message)
\ No newline at end of file
+ self.agent.hist_add_tool_result(self.name, response.message, **(response.additional or {}))
\ No newline at end of file
diff --git a/python/tools/scheduler.py b/python/tools/scheduler.py
index 8263ecad2..61b613de8 100644
--- a/python/tools/scheduler.py
+++ b/python/tools/scheduler.py
@@ -60,7 +60,7 @@ class SchedulerTool(Tool):
return Response(message=json.dumps(filtered_tasks, indent=4), break_loop=False)
async def find_task_by_name(self, **kwargs) -> Response:
- name: str = kwargs.get("name", None)
+ name: str = kwargs.get("name", "")
if not name:
return Response(message="Task name is required", break_loop=False)
tasks: list[ScheduledTask | AdHocTask | PlannedTask] = TaskScheduler.get().find_task_by_name(name)
@@ -69,7 +69,7 @@ class SchedulerTool(Tool):
return Response(message=json.dumps([serialize_task(task) for task in tasks], indent=4), break_loop=False)
async def show_task(self, **kwargs) -> Response:
- task_uuid: str = kwargs.get("uuid", None)
+ task_uuid: str = kwargs.get("uuid", "")
if not task_uuid:
return Response(message="Task UUID is required", break_loop=False)
task: ScheduledTask | AdHocTask | PlannedTask | None = TaskScheduler.get().get_task_by_uuid(task_uuid)
@@ -78,7 +78,7 @@ class SchedulerTool(Tool):
return Response(message=json.dumps(serialize_task(task), indent=4), break_loop=False)
async def run_task(self, **kwargs) -> Response:
- task_uuid: str = kwargs.get("uuid", None)
+ task_uuid: str = kwargs.get("uuid", "")
if not task_uuid:
return Response(message="Task UUID is required", break_loop=False)
task_context: str | None = kwargs.get("context", None)
@@ -93,7 +93,7 @@ class SchedulerTool(Tool):
return Response(message=f"Task started: {task_uuid}", break_loop=break_loop)
async def delete_task(self, **kwargs) -> Response:
- task_uuid: str = kwargs.get("uuid", None)
+ task_uuid: str = kwargs.get("uuid", "")
if not task_uuid:
return Response(message="Task UUID is required", break_loop=False)
@@ -133,9 +133,9 @@ class SchedulerTool(Tool):
# "month": "*",
# "weekday": "*",
# }
- name: str = kwargs.get("name", None)
- system_prompt: str = kwargs.get("system_prompt", None)
- prompt: str = kwargs.get("prompt", None)
+ name: str = kwargs.get("name", "")
+ system_prompt: str = kwargs.get("system_prompt", "")
+ prompt: str = kwargs.get("prompt", "")
attachments: list[str] = kwargs.get("attachments", [])
schedule: dict[str, str] = kwargs.get("schedule", {})
dedicated_context: bool = kwargs.get("dedicated_context", False)
@@ -165,9 +165,9 @@ class SchedulerTool(Tool):
return Response(message=f"Scheduled task '{name}' created: {task.uuid}", break_loop=False)
async def create_adhoc_task(self, **kwargs) -> Response:
- name: str = kwargs.get("name", None)
- system_prompt: str = kwargs.get("system_prompt", None)
- prompt: str = kwargs.get("prompt", None)
+ name: str = kwargs.get("name", "")
+ system_prompt: str = kwargs.get("system_prompt", "")
+ prompt: str = kwargs.get("prompt", "")
attachments: list[str] = kwargs.get("attachments", [])
token: str = str(random.randint(1000000000000000000, 9999999999999999999))
dedicated_context: bool = kwargs.get("dedicated_context", False)
@@ -184,9 +184,9 @@ class SchedulerTool(Tool):
return Response(message=f"Adhoc task '{name}' created: {task.uuid}", break_loop=False)
async def create_planned_task(self, **kwargs) -> Response:
- name: str = kwargs.get("name", None)
- system_prompt: str = kwargs.get("system_prompt", None)
- prompt: str = kwargs.get("prompt", None)
+ name: str = kwargs.get("name", "")
+ system_prompt: str = kwargs.get("system_prompt", "")
+ prompt: str = kwargs.get("prompt", "")
attachments: list[str] = kwargs.get("attachments", [])
plan: list[str] = kwargs.get("plan", [])
dedicated_context: bool = kwargs.get("dedicated_context", False)
@@ -219,7 +219,7 @@ class SchedulerTool(Tool):
return Response(message=f"Planned task '{name}' created: {task.uuid}", break_loop=False)
async def wait_for_task(self, **kwargs) -> Response:
- task_uuid: str = kwargs.get("uuid", None)
+ task_uuid: str = kwargs.get("uuid", "")
if not task_uuid:
return Response(message="Task UUID is required", break_loop=False)
diff --git a/webui/components/_examples/_example-store.js b/webui/components/_examples/_example-store.js
index 480e2f070..17d1be692 100644
--- a/webui/components/_examples/_example-store.js
+++ b/webui/components/_examples/_example-store.js
@@ -8,6 +8,10 @@ const model = {
// gets called when the store is created
init(){
console.log("Example store initialized");
+ },
+
+ clickHandler(event){
+ console.log(event)
}
};
diff --git a/webui/components/settings/secrets/example.html b/webui/components/settings/secrets/example-secrets.html
similarity index 96%
rename from webui/components/settings/secrets/example.html
rename to webui/components/settings/secrets/example-secrets.html
index b0e6ffb65..c695cd0b3 100644
--- a/webui/components/settings/secrets/example.html
+++ b/webui/components/settings/secrets/example-secrets.html
@@ -26,7 +26,7 @@ BRAVE_API_KEY="brv_xxxxxxxxxxxxxxxxxxxxx"
GOOGLE_API_KEY="AIzaSyD-xxxxxxxxxxxxxxxxxxxx"
# Email password for notifications
-EMAIL_PASSWORD="another-secret-password"
+NOTIF_EMAIL_PASSWORD="another-secret-password"
`;
const editor = ace.edit("secrets-example");
diff --git a/webui/components/settings/secrets/example-vars.html b/webui/components/settings/secrets/example-vars.html
new file mode 100644
index 000000000..c636a0285
--- /dev/null
+++ b/webui/components/settings/secrets/example-vars.html
@@ -0,0 +1,56 @@
+<html>
+
+<head>
+ <title>Example secrets file</title>
+
+</head>
+
+<body>
+ <div x-data>
+ <p>You can store passwords and secrets in standard <code>.env</code> format, one per line.<br>
+Add comments using <code>#</code> to help the agent understand the purpose of each secret.<br>
+See example below.</p>
+
+
+ <h3>Example secrets file</h3>
+ <div id="secrets-example"></div>
+
+ <script>
+ setTimeout(() => {
+ const envExample = `# Sales email connection
+SALES_EMAIL_IMAP_HOST="imap.company.com"
+SALES_EMAIL_IMAP_PORT=993
+SALES_EMAIL_IMAP_SSL=true
+
+# Other email params
+CHECK_INTERVAL=60 # check every X seconds
+RETRY_INTERVAL=10 # retry every X seconds
+MAX_RETRIES=3 # max retries
+`;
+
+ const editor = ace.edit("secrets-example");
+ const dark = localStorage.getItem("darkMode");
+ if (dark != "false") {
+ editor.setTheme("ace/theme/github_dark");
+ } else {
+ editor.setTheme("ace/theme/tomorrow");
+ }
+ editor.session.setMode("ace/mode/ini");
+ editor.setValue(envExample);
+ editor.clearSelection();
+ editor.setReadOnly(true);
+ }, 0);
+ </script>
+ <!-- </template> -->
+ </div>
+
+ <style>
+ #secrets-example {
+ width: 100%;
+ height: 20em;
+ }
+ </style>
+
+</body>
+
+</html>
\ No newline at end of file
diff --git a/webui/index.js b/webui/index.js
index 40588cb2e..558e833a4 100644
--- a/webui/index.js
+++ b/webui/index.js
@@ -595,7 +595,7 @@ globalThis.resetChat = async function (ctxid = null) {
globalThis.newChat = async function () {
try {
- setContext(generateGUID());
+ newContext();
updateAfterScroll();
} catch (e) {
globalThis.toastFetchError("Error creating new chat", e);
@@ -661,7 +661,7 @@ export function switchFromContext(id) {
setContext(alternateChat.id);
} else {
// If no other chats, create a new empty context
- setContext(generateGUID());
+ newContext();
}
}
}
@@ -736,6 +736,20 @@ globalThis.selectChat = async function (id) {
updateAfterScroll();
};
+function generateShortId() {
+ const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+ let result = '';
+ for (let i = 0; i < 8; i++) {
+ result += chars.charAt(Math.floor(Math.random() * chars.length));
+ }
+ return result;
+}
+
+export const newContext = function () {
+ context = generateShortId();
+ setContext(context);
+}
+
export const setContext = function (id) {
if (id == context) return;
context = id;
diff --git a/webui/js/manifest.json b/webui/js/manifest.json
index eddd0f1da..5122f2bb5 100644
--- a/webui/js/manifest.json
+++ b/webui/js/manifest.json
@@ -1,7 +1,7 @@
{
"name": "Agent Zero",
"short_name": "Agent Zero",
- "description": "The Resilient Autonomous Orchestrator",
+ "description": "Autonomous AI agent",
"start_url": "/",
"display": "standalone",
"background_color": "#1a1a1a",