Skip to content

Agent Zero AI framework

refactor(chat_branching): ID-based log ↔ history linking for precise branch trimming

keyboardstaff1bd5bc01d66c
diff --git a/agent.py b/agent.py
index 3fd5eaa2c..f8e53ac64 100644
--- a/agent.py
+++ b/agent.py
@@ -320,6 +320,7 @@ class UserMessage:
message: str
attachments: list[str] = field(default_factory=list[str])
system_message: list[str] = field(default_factory=list[str])
+ id: str = ""
class LoopData:
@@ -466,18 +467,20 @@ class Agent:
self.loop_data.last_response == agent_response
): # if assistant_response is the same as last message in history, let him know
# Append the assistant's response to the history
- self.hist_add_ai_response(agent_response)
+ log_item = self.loop_data.params_temporary.get("log_item_generating")
+ self.hist_add_ai_response(agent_response, id=log_item.id if log_item else "")
# Append warning message to the history
warning_msg = self.read_prompt("fw.msg_repeat.md")
- self.hist_add_warning(message=warning_msg)
+ wmsg = self.hist_add_warning(message=warning_msg)
PrintStyle(font_color="orange", padding=True).print(
warning_msg
)
- self.context.log.log(type="warning", content=warning_msg)
+ self.context.log.log(type="warning", content=warning_msg, id=wmsg.id)
else: # otherwise proceed with tool
# Append the assistant's response to the history
- self.hist_add_ai_response(agent_response)
+ log_item = self.loop_data.params_temporary.get("log_item_generating")
+ self.hist_add_ai_response(agent_response, id=log_item.id if log_item else "")
# process tools requested in agent message
tools_result = await self.process_tools(agent_response)
if tools_result: # final response of message loop available
@@ -637,7 +640,7 @@ class Agent:
@extension.extensible
def hist_add_message(
- self, ai: bool, content: history.MessageContent, tokens: int = 0
+ self, ai: bool, content: history.MessageContent, tokens: int = 0, id: str = ""
):
self.last_message = datetime.now(timezone.utc)
# Allow extensions to process content before adding to history
@@ -646,7 +649,7 @@ class Agent:
"hist_add_before", self, content_data=content_data, ai=ai
)
return self.history.add_message(
- ai=ai, content=content_data["content"], tokens=tokens
+ ai=ai, content=content_data["content"], tokens=tokens, id=id
)
@extension.extensible
@@ -674,30 +677,31 @@ class Agent:
content = {k: v for k, v in content.items() if v}
# add to history
- msg = self.hist_add_message(False, content=content) # type: ignore
+ msg = self.hist_add_message(False, content=content, id=message.id) # type: ignore
self.last_user_message = msg
return msg
@extension.extensible
- def hist_add_ai_response(self, message: str):
+ def hist_add_ai_response(self, message: str, id: str = ""):
self.loop_data.last_response = message
content = self.parse_prompt("fw.ai_response.md", message=message)
- return self.hist_add_message(True, content=content)
+ return self.hist_add_message(True, content=content, id=id)
@extension.extensible
- def hist_add_warning(self, message: history.MessageContent):
+ def hist_add_warning(self, message: history.MessageContent, id: str = ""):
content = self.parse_prompt("fw.warning.md", message=message)
- return self.hist_add_message(False, content=content)
+ return self.hist_add_message(False, content=content, id=id)
@extension.extensible
def hist_add_tool_result(self, tool_name: str, tool_result: str, **kwargs):
+ msg_id = kwargs.pop("id", "")
data = {
"tool_name": tool_name,
"tool_result": tool_result,
**kwargs,
}
extension.call_extensions_sync("hist_add_tool_result", self, data=data)
- return self.hist_add_message(False, content=data)
+ return self.hist_add_message(False, content=data, id=msg_id)
def concat_messages(
self, messages
@@ -927,18 +931,19 @@ class Agent:
error_detail = (
f"Tool '{raw_tool_name}' not found or could not be initialized."
)
- self.hist_add_warning(error_detail)
+ wmsg = self.hist_add_warning(error_detail)
PrintStyle(font_color="red", padding=True).print(error_detail)
self.context.log.log(
- type="warning", content=f"{self.agent_name}: {error_detail}"
+ type="warning", content=f"{self.agent_name}: {error_detail}", id=wmsg.id
)
else:
warning_msg_misformat = self.read_prompt("fw.msg_misformat.md")
- self.hist_add_warning(warning_msg_misformat)
+ wmsg = self.hist_add_warning(warning_msg_misformat)
PrintStyle(font_color="red", padding=True).print(warning_msg_misformat)
self.context.log.log(
type="warning",
content=f"{self.agent_name}: Message misformat, no valid tool request found.",
+ id=wmsg.id,
)
@extension.extensible
diff --git a/api/api_message.py b/api/api_message.py
index cf20b937f..fc4e50706 100644
--- a/api/api_message.py
+++ b/api/api_message.py
@@ -1,5 +1,6 @@
import base64
import os
+import uuid
from datetime import datetime, timedelta
from agent import AgentContext, UserMessage, AgentContextType
from helpers.api import ApiHandler, Request, Response
@@ -134,15 +135,17 @@ class ApiMessage(ApiHandler):
PrintStyle(font_color="white", padding=False).print(f"- {filename}")
# Add user message to chat history so it's visible in the UI
+ msg_id = str(uuid.uuid4())
context.log.log(
type="user",
heading="",
content=message,
kvps={"attachments": attachment_filenames},
+ id=msg_id,
)
# Send message to agent
- task = context.communicate(UserMessage(message=message, attachments=attachment_paths))
+ task = context.communicate(UserMessage(message=message, attachments=attachment_paths, id=msg_id))
result = await task.result()
# Clean up expired chats
diff --git a/api/message.py b/api/message.py
index 27a5a7677..6ea66027e 100644
--- a/api/message.py
+++ b/api/message.py
@@ -68,4 +68,4 @@ class Message(ApiHandler):
# Log to console and UI using helper function
mq.log_user_message(context, message, attachment_paths, message_id)
- return context.communicate(UserMessage(message=message, attachments=attachment_paths)), context
+ return context.communicate(UserMessage(message=message, attachments=attachment_paths, id=message_id or "")), context
diff --git a/extensions/python/_functions/agent/Agent/handle_exception/end/_50_handle_repairable_exception.py b/extensions/python/_functions/agent/Agent/handle_exception/end/_50_handle_repairable_exception.py
index f35016570..e6d098c2a 100644
--- a/extensions/python/_functions/agent/Agent/handle_exception/end/_50_handle_repairable_exception.py
+++ b/extensions/python/_functions/agent/Agent/handle_exception/end/_50_handle_repairable_exception.py
@@ -17,9 +17,9 @@ class HandleRepairableException(Extension):
if isinstance(data["exception"], RepairableException):
msg = {"message": errors.format_error(data["exception"])}
await extension.call_extensions_async("error_format", agent=self.agent, msg=msg)
- self.agent.hist_add_warning(msg["message"])
+ wmsg = self.agent.hist_add_warning(msg["message"])
PrintStyle(font_color="red", padding=True).print(msg["message"])
- self.agent.context.log.log(type="warning", content=msg["message"])
+ self.agent.context.log.log(type="warning", content=msg["message"], id=wmsg.id)
data["exception"] = None
diff --git a/extensions/python/agent_init/_10_initial_message.py b/extensions/python/agent_init/_10_initial_message.py
index 557f8701a..cca5f798e 100644
--- a/extensions/python/agent_init/_10_initial_message.py
+++ b/extensions/python/agent_init/_10_initial_message.py
@@ -28,7 +28,7 @@ class InitialMessage(Extension):
self.agent.loop_data = LoopData(user_message=None)
# Add the message to history as an AI response
- self.agent.hist_add_ai_response(initial_message)
+ msg = self.agent.hist_add_ai_response(initial_message)
# json parse the message, get the tool_args text
initial_message_json = json.loads(initial_message)
@@ -40,4 +40,5 @@ class InitialMessage(Extension):
content=initial_message_text,
finished=True,
update_progress="none",
+ id=msg.id,
)
diff --git a/extensions/python/before_main_llm_call/_10_log_for_stream.py b/extensions/python/before_main_llm_call/_10_log_for_stream.py
index 58684ab27..66fab4011 100644
--- a/extensions/python/before_main_llm_call/_10_log_for_stream.py
+++ b/extensions/python/before_main_llm_call/_10_log_for_stream.py
@@ -5,6 +5,7 @@ import asyncio
from helpers.log import LogItem
from helpers import log
import math
+import uuid
class LogForStream(Extension):
@@ -19,6 +20,7 @@ class LogForStream(Extension):
self.agent.context.log.log(
type="agent",
heading=build_default_heading(self.agent),
+ id=str(uuid.uuid4()),
)
)
diff --git a/extensions/python/response_stream/_20_live_response.py b/extensions/python/response_stream/_20_live_response.py
index 255358117..ecabb8a48 100644
--- a/extensions/python/response_stream/_20_live_response.py
+++ b/extensions/python/response_stream/_20_live_response.py
@@ -30,10 +30,14 @@ class LiveResponse(Extension):
# create log message and store it in loop data temporary params
if "log_item_response" not in loop_data.params_temporary:
+ # Share id with the agent log item so branching covers the response bubble
+ gen_item = loop_data.params_temporary.get("log_item_generating")
+ shared_id = gen_item.id if gen_item and gen_item.id else ""
loop_data.params_temporary["log_item_response"] = (
self.agent.context.log.log(
type="response",
heading=f"icon://chat {self.agent.agent_name}: Responding",
+ id=shared_id,
)
)
diff --git a/helpers/history.py b/helpers/history.py
index 43b0fbdde..4fdefd179 100644
--- a/helpers/history.py
+++ b/helpers/history.py
@@ -4,6 +4,7 @@ from collections import OrderedDict
from collections.abc import Mapping
import json
import math
+import uuid
from typing import Coroutine, Literal, TypedDict, cast, Union, Dict, List, Any
from helpers import messages, tokens, settings, call_llm
from enum import Enum
@@ -81,7 +82,8 @@ class Record:
class Message(Record):
- def __init__(self, ai: bool, content: MessageContent, tokens: int = 0):
+ def __init__(self, ai: bool, content: MessageContent, tokens: int = 0, id: str = ""):
+ self.id = id or str(uuid.uuid4())
self.ai = ai
self.content = content
self.summary: str = ""
@@ -115,6 +117,7 @@ class Message(Record):
def to_dict(self):
return {
"_cls": "Message",
+ "id": self.id,
"ai": self.ai,
"content": self.content,
"summary": self.summary,
@@ -124,7 +127,7 @@ class Message(Record):
@staticmethod
def from_dict(data: dict, history: "History"):
content = data.get("content", "Content lost")
- msg = Message(ai=data["ai"], content=content)
+ msg = Message(ai=data["ai"], content=content, id=data.get("id", ""))
msg.summary = data.get("summary", "")
msg.tokens = data.get("tokens", 0)
return msg
@@ -143,9 +146,9 @@ class Topic(Record):
return sum(msg.get_tokens() for msg in self.messages)
def add_message(
- self, ai: bool, content: MessageContent, tokens: int = 0
+ self, ai: bool, content: MessageContent, tokens: int = 0, id: str = ""
) -> Message:
- msg = Message(ai=ai, content=content, tokens=tokens)
+ msg = Message(ai=ai, content=content, tokens=tokens, id=id)
self.messages.append(msg)
return msg
@@ -332,10 +335,10 @@ class History(Record):
return self.current.get_tokens()
def add_message(
- self, ai: bool, content: MessageContent, tokens: int = 0
+ self, ai: bool, content: MessageContent, tokens: int = 0, id: str = ""
) -> Message:
self.counter += 1
- return self.current.add_message(ai, content=content, tokens=tokens)
+ return self.current.add_message(ai, content=content, tokens=tokens, id=id)
def new_topic(self):
if self.current.messages:
diff --git a/helpers/mcp_handler.py b/helpers/mcp_handler.py
index c93cf1369..439127b21 100644
--- a/helpers/mcp_handler.py
+++ b/helpers/mcp_handler.py
@@ -102,11 +102,13 @@ class MCPTool(Tool):
"""MCP Tool wrapper"""
def get_log_object(self) -> LogItem:
+ import uuid
return self.agent.context.log.log(
type="mcp",
heading=f"icon://extension {self.agent.agent_name}: Using MCP tool '{self.name}'",
content="",
kvps={"tool_name": self.name, **self.args},
+ id=str(uuid.uuid4()),
)
async def execute(self, **kwargs: Any):
@@ -198,7 +200,7 @@ class MCPTool(Tool):
final_text_for_agent = raw_tool_response
- self.agent.hist_add_tool_result(self.name, final_text_for_agent)
+ self.agent.hist_add_tool_result(self.name, final_text_for_agent, id=self.log.id if self.log else "")
(
PrintStyle(
font_color="#1B4F72", background_color="white", padding=True, bold=True
diff --git a/helpers/message_queue.py b/helpers/message_queue.py
index 37d8065e1..51e05c6b2 100644
--- a/helpers/message_queue.py
+++ b/helpers/message_queue.py
@@ -153,8 +153,9 @@ def send_message(context: "AgentContext", item: dict, source: str = " (from queu
message = item.get("text", "")
attachments = item.get("attachments", [])
- log_user_message(context, message, attachments, source=source)
- context.communicate(UserMessage(message, attachments))
+ msg_id = str(uuid.uuid4())
+ log_user_message(context, message, attachments, message_id=msg_id, source=source)
+ context.communicate(UserMessage(message, attachments, id=msg_id))
def send_next(context: "AgentContext") -> bool:
@@ -183,6 +184,7 @@ def send_all_aggregated(context: "AgentContext") -> int:
text = "\n\n---\n\n".join(i["text"] for i in items if i["text"])
attachments = [a for i in items for a in i.get("attachments", [])]
- log_user_message(context, text, attachments, source=" (queued batch)")
- context.communicate(UserMessage(text, attachments))
+ msg_id = str(uuid.uuid4())
+ log_user_message(context, text, attachments, message_id=msg_id, source=" (queued batch)")
+ context.communicate(UserMessage(text, attachments, id=msg_id))
return len(items)
diff --git a/helpers/task_scheduler.py b/helpers/task_scheduler.py
index 05f352a76..71f55e1c6 100644
--- a/helpers/task_scheduler.py
+++ b/helpers/task_scheduler.py
@@ -882,19 +882,21 @@ class TaskScheduler:
task_prompt = f"## Task:\n{current_task.prompt}"
# Log the message with message_id and attachments
+ msg_id = str(uuid.uuid4())
context.log.log(
type="user",
heading="",
content=task_prompt,
kvps={"attachments": attachment_filenames},
- id=str(uuid.uuid4()),
+ id=msg_id,
)
agent.hist_add_user_message(
UserMessage(
message=task_prompt,
system_message=[current_task.system_prompt],
- attachments=attachment_filenames))
+ attachments=attachment_filenames,
+ id=msg_id))
# Persist after setting up the context but before running the agent
# This ensures the task context is saved and can be found by polling
diff --git a/helpers/tool.py b/helpers/tool.py
index 0891e9c61..820164d59 100644
--- a/helpers/tool.py
+++ b/helpers/tool.py
@@ -53,17 +53,19 @@ 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, **(response.additional or {}))
+ self.agent.hist_add_tool_result(self.name, text, id=self.log.id, **(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)
def get_log_object(self):
+ import uuid
+ pre_id = str(uuid.uuid4())
if self.method:
heading = f"icon://construction {self.agent.agent_name}: Using tool '{self.name}:{self.method}'"
else:
heading = f"icon://construction {self.agent.agent_name}: Using tool '{self.name}'"
- return self.agent.context.log.log(type="tool", heading=heading, content="", kvps=self.args, _tool_name=self.name)
+ return self.agent.context.log.log(type="tool", heading=heading, content="", kvps=self.args, _tool_name=self.name, id=pre_id)
def nice_key(self, key:str):
words = key.split('_')
diff --git a/plugins/_chat_branching/README.md b/plugins/_chat_branching/README.md
index f7fcf5204..2d4be43c5 100644
--- a/plugins/_chat_branching/README.md
+++ b/plugins/_chat_branching/README.md
@@ -4,26 +4,28 @@ Create a new chat from any existing point in a conversation.
## What It Does
-This plugin adds an API endpoint that clones an existing chat context, trims its log history up to a selected message, gives the new chat a `(branch)` suffix, persists it immediately, and refreshes connected tabs so the new branch appears in the UI.
+Adds a **Branch** button to every chat message. Clicking it clones the current chat up to that message, creating a new conversation you can continue independently.
-## Main Behavior
+## How It Works
-- **Clone context**
- - Serializes the current chat context and deserializes it into a brand-new context with a new ID.
-- **Trim history**
- - Keeps log entries only up to and including the selected `log_no`.
- - Includes a fallback for cases where reloaded logs use sequential array indexes.
-- **Persist immediately**
- - Saves the newly created branched chat to temporary chat storage.
-- **Refresh UI state**
- - Marks state dirty for all tabs after the branch is created.
+1. **ID-based log ↔ history linking**
+ Every `LogItem` and `history.Message` share a UUID generated at creation time. The branch button is only shown on messages that carry this ID.
+
+2. **Clone & trim**
+ - Serializes the source context → deserializes into a new context with a fresh ID.
+ - Walks log entries: keeps everything up to the selected `log_no`, discards the rest.
+ - Collects the IDs of kept entries and uses them to trim `history.messages` so log and history stay consistent.
+
+3. **Persist & refresh**
+ - Saves the branched chat immediately.
+ - Marks UI state dirty so all connected tabs see the new branch.
## Entry Points
-- **API**
- - `api/branch_chat.py` implements the branching operation.
-- **Extensions**
- - `extensions/` contains integration glue for making the feature available in the app.
+| Path | Purpose |
+|---|---|
+| `api/branch_chat.py` | API endpoint — clone, trim, persist |
+| `extensions/webui/set_messages_after_loop/inject-branch-buttons.js` | Injects the Branch button into each message DOM element |
## Plugin Metadata
diff --git a/plugins/_chat_branching/api/branch_chat.py b/plugins/_chat_branching/api/branch_chat.py
index e9f652c35..bdc33edda 100644
--- a/plugins/_chat_branching/api/branch_chat.py
+++ b/plugins/_chat_branching/api/branch_chat.py
@@ -9,55 +9,69 @@ from helpers.persist_chat import (
)
from agent import AgentContext
-# Log types that produce a history message (via hist_add_* in Agent)
-_HIST_LOG_TYPES = {"user", "agent", "tool", "warning"}
+def _trim_history_json(history_json: str, kept_ids: set[str], after_cut_ids: set[str]) -> str:
+ """Trim a serialized history JSON to keep only messages that appear
+ before the branch cut point.
-def _count_history_msgs(logs, agent_no):
- """Count log items that produced history messages for a specific agent."""
- return sum(
- 1 for item in logs
- if item["type"] in _HIST_LOG_TYPES and item.get("agentno", 0) == agent_no
- )
+ *kept_ids*: IDs of log items up to and including the cut point.
+ *after_cut_ids*: IDs of log items after the cut point.
-
-def _trim_history_json(history_json, keep_count):
- """Trim a serialized history JSON string to keep only the first
- *keep_count* un-summarized messages. Summarized bulks/topics are
- always preserved (they represent older history before any cut point)."""
+ Walk messages in order. A message is kept while the running state
+ is "keep". The state flips to "drop" the first time we encounter
+ a message whose id is in *after_cut_ids*. Messages whose id does
+ not appear in any log set (unpaired) inherit the current state.
+ Summarized topics/bulks are always preserved.
+ """
if not history_json:
return history_json
- hist = json.loads(history_json)
- # Flatten messages from topics + current, count and trim
- remaining = keep_count
+ hist = json.loads(history_json)
+ keep = True # running state
+
+ def filter_messages(messages: list[dict]) -> list[dict]:
+ nonlocal keep
+ result = []
+ for msg in messages:
+ mid = msg.get("id", "")
+ if mid and mid in after_cut_ids:
+ keep = False
+ elif mid and mid in kept_ids:
+ keep = True
+ # else: unpaired – inherit current state
+ if keep:
+ result.append(msg)
+ return result
+
+ # Bulks are already summarized old history – always keep
+ # Topics: keep summarized ones; filter unsummarized
trimmed_topics = []
-
for topic in hist.get("topics", []):
if topic.get("summary"):
- # Summarized topic — keep whole, don't count
trimmed_topics.append(topic)
continue
- msgs = topic.get("messages", [])
- if remaining >= len(msgs):
+ msgs = filter_messages(topic.get("messages", []))
+ if msgs:
+ topic["messages"] = msgs
trimmed_topics.append(topic)
- remaining -= len(msgs)
- elif remaining > 0:
- topic["messages"] = msgs[:remaining]
- trimmed_topics.append(topic)
- remaining = 0
- # else: drop entirely
-
+ if not keep:
+ break
hist["topics"] = trimmed_topics
- # Trim current topic
+ # Current topic
current = hist.get("current", {})
- if not current.get("summary"):
- msgs = current.get("messages", [])
- if remaining < len(msgs):
- current["messages"] = msgs[:remaining]
+ if not current.get("summary") and keep:
+ current["messages"] = filter_messages(current.get("messages", []))
+ elif not keep:
+ current["messages"] = []
+ hist["current"] = current
+
+ # Recount
+ total = sum(
+ len(t.get("messages", [])) for t in hist["topics"] if not t.get("summary")
+ ) + len(hist.get("current", {}).get("messages", []))
+ hist["counter"] = total
- hist["counter"] = keep_count
return json.dumps(hist, ensure_ascii=False)
@@ -98,12 +112,18 @@ class BranchChat(ApiHandler):
return Response("log_no not found in chat log", 400)
kept_logs = src_logs[: cut_idx + 1]
+ after_logs = src_logs[cut_idx + 1 :]
data["log"]["logs"] = kept_logs
- # Trim agent history to match the log cut point
+ # Build ID sets for history trimming
+ kept_ids = {item["id"] for item in kept_logs if item.get("id")}
+ after_cut_ids = {item["id"] for item in after_logs if item.get("id")}
+
+ # Trim each agent's history using ID matching
for ag in data.get("agents", []):
- msg_count = _count_history_msgs(kept_logs, ag["number"])
- ag["history"] = _trim_history_json(ag.get("history", ""), msg_count)
+ ag["history"] = _trim_history_json(
+ ag.get("history", ""), kept_ids, after_cut_ids
+ )
# Give the branch a distinguishable name
src_name = data.get("name") or "Chat"
diff --git a/plugins/_chat_branching/extensions/webui/set_messages_after_loop/inject-branch-buttons.js b/plugins/_chat_branching/extensions/webui/set_messages_after_loop/inject-branch-buttons.js
index c98f84f96..b9d85ad9f 100644
--- a/plugins/_chat_branching/extensions/webui/set_messages_after_loop/inject-branch-buttons.js
+++ b/plugins/_chat_branching/extensions/webui/set_messages_after_loop/inject-branch-buttons.js
@@ -9,7 +9,7 @@ export default async function injectBranchButtons(context) {
if (!context?.results?.length) return;
for (const { args, result } of context.results) {
- if (!result?.element || args.no == null) continue;
+ if (!result?.element || args.no == null || !args.id) continue;
const logNo = args.no;
for (const bar of result.element.querySelectorAll(".step-action-buttons")) {
diff --git a/plugins/_code_execution/tools/code_execution_tool.py b/plugins/_code_execution/tools/code_execution_tool.py
index 88478bc82..6ebec1d61 100644
--- a/plugins/_code_execution/tools/code_execution_tool.py
+++ b/plugins/_code_execution/tools/code_execution_tool.py
@@ -71,11 +71,13 @@ class CodeExecution(Tool):
return Response(message=response, break_loop=False)
def get_log_object(self):
+ import uuid
return self.agent.context.log.log(
type="code_exe",
heading=self.get_heading(),
content="",
kvps=self.args,
+ id=str(uuid.uuid4()),
)
def get_heading(self, text: str = ""):
@@ -86,7 +88,7 @@ class CodeExecution(Tool):
return f"icon://terminal {session_text}{truncate_text_string(text, 200)}"
async def after_execution(self, response, **kwargs):
- self.agent.hist_add_tool_result(self.name, response.message, **(response.additional or {}))
+ self.agent.hist_add_tool_result(self.name, response.message, id=self.log.id if self.log else "", **(response.additional or {}))
async def prepare_state(self, cfg: dict, reset=False, session: int | None = None):
self.state: State | None = self.agent.get_data("_cet_state")
diff --git a/plugins/_code_execution/tools/input.py b/plugins/_code_execution/tools/input.py
index 283670fb6..3f11d150b 100644
--- a/plugins/_code_execution/tools/input.py
+++ b/plugins/_code_execution/tools/input.py
@@ -19,7 +19,8 @@ class Input(Tool):
return await cet.execute(**args)
def get_log_object(self):
- 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)
+ import uuid
+ 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, id=str(uuid.uuid4()))
async def after_execution(self, response, **kwargs):
- self.agent.hist_add_tool_result(self.name, response.message, **(response.additional or {}))
\ No newline at end of file
+ self.agent.hist_add_tool_result(self.name, response.message, id=self.log.id if self.log else "", **(response.additional or {}))
\ No newline at end of file
diff --git a/plugins/_email_integration/helpers/handler.py b/plugins/_email_integration/helpers/handler.py
index ef194f3fd..020f00bbf 100644
--- a/plugins/_email_integration/helpers/handler.py
+++ b/plugins/_email_integration/helpers/handler.py
@@ -8,6 +8,7 @@ import asyncio
import base64
import json
import os
+import uuid
from agent import Agent, AgentContext, AgentContextType, UserMessage
from helpers import guids, plugins, files, runtime
@@ -285,11 +286,13 @@ async def _start_new_chat(agent: Agent, handler_cfg: dict, msg: InboundMessage):
user_msg = _build_user_message(agent, msg, handler_cfg)
system_ctx = agent.read_prompt("fw.email.system_context.md")
- mq.log_user_message(context, user_msg, msg.attachments or [], source=" (email)")
+ msg_id = str(uuid.uuid4())
+ mq.log_user_message(context, user_msg, msg.attachments or [], message_id=msg_id, source=" (email)")
context.communicate(UserMessage(
message=user_msg,
system_message=[system_ctx],
attachments=msg.attachments,
+ id=msg_id,
))
PrintStyle.success(f"Email: new chat {context.id} for '{msg.subject}' from {msg.sender}")
@@ -322,10 +325,12 @@ async def _route_to_chat(
context.data[disp.CTX_EMAIL_REFERENCES] = " ".join(refs_list)
user_msg = _build_user_message(agent, msg, handler_cfg)
- mq.log_user_message(context, user_msg, msg.attachments or [], source=" (email)")
+ msg_id = str(uuid.uuid4())
+ mq.log_user_message(context, user_msg, msg.attachments or [], message_id=msg_id, source=" (email)")
context.communicate(UserMessage(
message=user_msg,
attachments=msg.attachments,
+ id=msg_id,
))
save_tmp_chat(context)
diff --git a/plugins/_error_retry/extensions/python/_functions/agent/Agent/handle_exception/end/_80_retry_critical_exception.py b/plugins/_error_retry/extensions/python/_functions/agent/Agent/handle_exception/end/_80_retry_critical_exception.py
index e061e4516..91c2ca344 100644
--- a/plugins/_error_retry/extensions/python/_functions/agent/Agent/handle_exception/end/_80_retry_critical_exception.py
+++ b/plugins/_error_retry/extensions/python/_functions/agent/Agent/handle_exception/end/_80_retry_critical_exception.py
@@ -35,10 +35,13 @@ class RetryCriticalException(Extension):
self.agent.set_data(DATA_NAME_COUNTER, counter + 1)
error_message = errors.format_error(exception)
+ import uuid as _uuid
+ msg_id = str(_uuid.uuid4())
self.agent.context.log.log(
type="warning",
heading="Critical error occurred, retrying...",
content=error_message,
+ id=msg_id,
)
PrintStyle(font_color="orange", padding=True).print(
"Critical error occurred, retrying..."
@@ -48,7 +51,7 @@ class RetryCriticalException(Extension):
agent_facing_error = self.agent.read_prompt(
"fw.msg_critical_error.md", error_message=error_message
)
- self.agent.hist_add_warning(message=agent_facing_error)
+ self.agent.hist_add_warning(message=agent_facing_error, id=msg_id)
PrintStyle(font_color="orange", padding=True).print(agent_facing_error)
data["exception"] = None
diff --git a/plugins/_infection_check/helpers/checker.py b/plugins/_infection_check/helpers/checker.py
index a85845c5e..59b219dd2 100644
--- a/plugins/_infection_check/helpers/checker.py
+++ b/plugins/_infection_check/helpers/checker.py
@@ -328,11 +328,14 @@ class InfectionChecker:
return "terminate", "Max clarifications exceeded.", "\n\n".join(cot_parts)
def _do_terminate(self, agent: "Agent", detail: str, cot: str):
+ import uuid as _uuid
content = cot or detail or "Malicious behavior detected."
+ msg_id = str(_uuid.uuid4())
agent.context.log.log(
type="warning",
heading="Infection check: TERMINATED",
content=content,
+ id=msg_id,
)
# Replace last AI message with a blocked marker
@@ -341,7 +344,8 @@ class InfectionChecker:
if msgs and msgs[-1].ai:
msgs.pop()
agent.history.add_message(
- ai=True, content="[BLOCKED] Response terminated by security policy."
+ ai=True, content="[BLOCKED] Response terminated by security policy.",
+ id=msg_id,
)
except Exception:
pass
diff --git a/plugins/_telegram_integration/helpers/handler.py b/plugins/_telegram_integration/helpers/handler.py
index dd8cfda53..5ea7ec6e8 100644
--- a/plugins/_telegram_integration/helpers/handler.py
+++ b/plugins/_telegram_integration/helpers/handler.py
@@ -246,10 +246,12 @@ async def handle_message(message: TgMessage, bot_name: str, bot_cfg: dict):
body=text,
)
- mq.log_user_message(context, user_msg, attachments, source=" (telegram)")
+ msg_id = str(uuid.uuid4())
+ mq.log_user_message(context, user_msg, attachments, message_id=msg_id, source=" (telegram)")
context.communicate(UserMessage(
message=user_msg,
attachments=attachments,
+ id=msg_id,
))
save_tmp_chat(context)
@@ -298,8 +300,9 @@ async def handle_callback_query(query: CallbackQuery, bot_name: str, bot_cfg: di
body=f"[Button pressed: {text}]",
)
- mq.log_user_message(context, user_msg, [], source=" (telegram)")
- context.communicate(UserMessage(message=user_msg))
+ msg_id = str(uuid.uuid4())
+ mq.log_user_message(context, user_msg, [], message_id=msg_id, source=" (telegram)")
+ context.communicate(UserMessage(message=user_msg, id=msg_id))
save_tmp_chat(context)
diff --git a/tools/vision_load.py b/tools/vision_load.py
index ae654419a..ee89e69ec 100644
--- a/tools/vision_load.py
+++ b/tools/vision_load.py
@@ -75,7 +75,7 @@ class VisionLoad(Tool):
f"Skipped images (max {self._get_max_embeds()} loaded at a time according to model configuration):\n{skipped_summary}"
)
if self.images_dict:
- self.agent.hist_add_tool_result(self.name, summary)
+ self.agent.hist_add_tool_result(self.name, summary, id=self.log.id if self.log else "")
for path, image in self.images_dict.items():
if image:
content.append(
@@ -97,7 +97,7 @@ class VisionLoad(Tool):
False, content=msg, tokens=TOKENS_ESTIMATE * len(content)
)
else:
- self.agent.hist_add_tool_result(self.name, summary if self.skipped_paths else "No images processed")
+ self.agent.hist_add_tool_result(self.name, summary if self.skipped_paths else "No images processed", id=self.log.id if self.log else "")
# print and log short version
message = (