Agent Zero AI framework
Add LLMResult.non_llm sentinel and apply frdel review findings
linkliti60073f283a09
diff --git a/agent.py b/agent.pyindex e4f00ed6b..e76132650 100644--- a/agent.py+++ b/agent.py@@ -1099,7 +1099,7 @@ class Agent:self.hist_add_tool_result(last_tool.name, tool_progress)last_tool.set_progress(None)if progress.strip():- self.hist_add_ai_response(progress, llm_result=LLMResult())+ self.hist_add_ai_response(progress, llm_result=LLMResult.non_llm())# append the intervention messageself.hist_add_user_message(msg, intervention=True)raise InterventionException(msg)diff --git a/extensions/python/agent_init/AGENTS.md b/extensions/python/agent_init/AGENTS.mdindex 7bf26fd03..7d0adbcae 100644--- a/extensions/python/agent_init/AGENTS.md+++ b/extensions/python/agent_init/AGENTS.md@@ -14,7 +14,8 @@- Preserve ordering between initial message creation and profile settings loading.- Keep a placeholder user turn (`fw.initial_user_message.md`) ahead of the AI greeting (`fw.initial_message.md`) so `output_langchain` never pops the greeting as a leading `AIMessage`; do not remove either prompt without replacing the turn-order guarantee.- Minify the initial AI message JSON before storage; preserve raw text as the displayed greeting when JSON parsing fails.-- `_10_initial_message.py` passes an empty `LLMResult()` to `hist_add_ai_response` so the Responses-API state seam runs uniformly; the empty result carries no `response_id`, so state advancement is a no-op for the greeting turn.+- `_10_initial_message.py` passes `LLMResult.non_llm()` to `hist_add_ai_response` so the Responses-API state seam runs uniformly; the sentinel carries no `response_id` and marks `mode=""`/`state="off"` so stored metadata does not claim a Responses-API turn.+- The synthetic `Hello!` user turn and the AI greeting are intentionally hidden: they have no matching UI log item (branching links log↔history by ID, but these seeding turns predate the log). They serve as a few-shot example of the expected user→AI turn ordering so `output_langchain` does not pop the greeting as a leading `AIMessage`. Do not add log items for seeding turns without replacing the few-shot guarantee.## Work Guidancediff --git a/extensions/python/agent_init/_10_initial_message.py b/extensions/python/agent_init/_10_initial_message.pyindex 5d1a2bcec..2eb132b8a 100644--- a/extensions/python/agent_init/_10_initial_message.py+++ b/extensions/python/agent_init/_10_initial_message.py@@ -41,7 +41,7 @@ class InitialMessage(Extension):self.agent.loop_data = LoopData(user_message=None)# Add the message to history as an AI response- msg = self.agent.hist_add_ai_response(initial_message, llm_result=LLMResult())+ msg = self.agent.hist_add_ai_response(initial_message, llm_result=LLMResult.non_llm())# Add to log (green bubble) for immediate UI displayself.agent.context.log.log(diff --git a/helpers/llm_result.py b/helpers/llm_result.pyindex 23859871c..ab067db54 100644--- a/helpers/llm_result.py+++ b/helpers/llm_result.py@@ -168,6 +168,11 @@ class LLMResult:result.response = result.function_calls_text()return result+ @classmethod+ def non_llm(cls) -> "LLMResult":+ """Sentinel for non-LLM AI turns; no response_id, mode/state off."""+ return cls(mode="", state="off")+@propertydef function_calls(self) -> list[ResponseFunctionCall]:calls: list[ResponseFunctionCall] = []diff --git a/plugins/_context_doctor/AGENTS.md b/plugins/_context_doctor/AGENTS.mdindex d2624c457..9dd0de858 100644--- a/plugins/_context_doctor/AGENTS.md+++ b/plugins/_context_doctor/AGENTS.md@@ -17,11 +17,12 @@- Repaired and fallback JSON is always minified.- Nonempty non-tool output becomes `{"thoughts":[raw]}`; XML-like output becomes `{}` only when suppression is enabled.-- Blank-line-separated thoughts expand into separate entries after repair when the split strategy is enabled (default on).+- Blank-line-separated thoughts expand into separate entries after repair when the split strategy is enabled (default on). This rewrites model-authored thoughts for every repaired turn by design, not only the raw-text fallback branch.+- `looks_like_tool_call` returns True when the transformed output is a dict containing at least one A0 key (thoughts/headline/tool_name/tool_args). Empty dicts or dicts without any A0 key fall through to the raw-text fallback branch.- A raw-text fallback conversion must emit a `fw.msg_thoughts_fallback.md` history warning and a separate `fw.msg_thoughts_fallback_response.md` user notice, refresh the generating log and response item with the transformed thoughts JSON, and set `skip_default_processing` so the retry advances the unusable-response counter.- The fallback passes the repaired `llm_result` to `hist_add_ai_response`, which owns Responses-API state advancement (`_remember_llm_result_state`); do not call the state method directly. The fallback turn's `response_id` is recorded so the next turn's `previous_response_id` chain stays intact.- The fallback warning is counted by the core stop-unusable-response loop alongside `fw.msg_misformat.md`, `fw.msg_repeat.md`, `fw.msg_empty_response.md`, and `fw.msg_reasoning_only.md`.-- Log kvps retain streamed `reasoning` and `thoughts`, then add transformed output; `update_log` controls only View Details content.+- Log kvps retain streamed `reasoning` only; `update_log_item` does not restore `thoughts` from current kvps. `update_log` controls only View Details content.- A repaired `response` tool call refreshes the response log item when streaming did not create it.- Runtime setup reads the `json_repair` pin from root `requirements.txt`; do not duplicate its version in plugin code.diff --git a/plugins/_context_doctor/extensions/python/message_loop_result/_10_context_doctor.py b/plugins/_context_doctor/extensions/python/message_loop_result/_10_context_doctor.pyindex ef3e2e9da..5fa677521 100644--- a/plugins/_context_doctor/extensions/python/message_loop_result/_10_context_doctor.py+++ b/plugins/_context_doctor/extensions/python/message_loop_result/_10_context_doctor.py@@ -9,7 +9,7 @@ from helpers.extension import Extensionfrom helpers.plugins import get_plugin_configfrom helpers.print_style import PrintStylefrom plugins._context_doctor.helpers.context_doctor import (- is_thoughts_fallback,+ looks_like_tool_call,transform_response,update_log_item,)@@ -36,8 +36,8 @@ class ContextDoctor(Extension):)llm_result.response = transformed- # Check if response is a plain text- if is_thoughts_fallback(response, transformed):+ # Treat as raw-text fallback when no usable tool call was extracted+ if not looks_like_tool_call(response, transformed):# Manually add ai response and warningslog_item = self.agent.loop_data.params_temporary.get("log_item_generating")self.agent.hist_add_ai_response(diff --git a/plugins/_context_doctor/helpers/context_doctor.py b/plugins/_context_doctor/helpers/context_doctor.pyindex c95671dfe..52e24df75 100644--- a/plugins/_context_doctor/helpers/context_doctor.py+++ b/plugins/_context_doctor/helpers/context_doctor.py@@ -135,8 +135,8 @@ def transform_response(return _compact_json(value)-def is_thoughts_fallback(response: str, transformed: str) -> bool:- """Check whether transform produced no usable tool call."""+def looks_like_tool_call(response: str, transformed: str) -> bool:+ """Return True if transformed output is a valid A0 response JSON."""if not response:return Falsetry:@@ -145,7 +145,7 @@ def is_thoughts_fallback(response: str, transformed: str) -> bool:return Falseif not isinstance(parsed, dict) or not parsed:return False- return "tool_name" not in parsed+ return any(k in parsed for k in ("thoughts", "headline", "tool_name", "tool_args"))def update_log_item(diff --git a/plugins/_context_doctor/tests/test_context_doctor.py b/plugins/_context_doctor/tests/test_context_doctor.pyindex 0beda0dea..584563bf5 100644--- a/plugins/_context_doctor/tests/test_context_doctor.py+++ b/plugins/_context_doctor/tests/test_context_doctor.py@@ -4,7 +4,7 @@ from plugins._context_doctor.extensions.python.message_loop_result._10_context_dContextDoctor,)from plugins._context_doctor.helpers.context_doctor import (- is_thoughts_fallback,+ looks_like_tool_call,transform_response,update_log_item,)@@ -103,31 +103,39 @@ def test_updates_log_kvps_and_heading_while_preserving_raw_content():def test_converted_to_thoughts_detects_plain_text_wrap():- assert is_thoughts_fallback("plain text", '{"thoughts":["plain text"]}')+ assert looks_like_tool_call("plain text", '{"thoughts":["plain text"]}')def test_converted_to_thoughts_detects_split_multi_paragraph_wrap():response = "first\n\nsecond"transformed = '{"thoughts":["first","second"]}'- assert is_thoughts_fallback(response, transformed)+ assert looks_like_tool_call(response, transformed)def test_transform_and_fallback_agree_on_multi_paragraph_raw_text():response = "first\n\nsecond"transformed = transform_response(response, suppress_xml=False)- assert is_thoughts_fallback(response, transformed)+ assert looks_like_tool_call(response, transformed)def test_converted_to_thoughts_detects_native_thoughts_json():response = '{"thoughts":["only thoughts"]}'- assert is_thoughts_fallback(response, response)+ assert looks_like_tool_call(response, response)-def test_converted_to_thoughts_ignores_tool_calls():+def test_looks_like_tool_call_detects_tool_calls():response = '{"tool_name":"response","tool_args":{"text":"ok"}}'- assert not is_thoughts_fallback(response, response)+ assert looks_like_tool_call(response, response)+++def test_looks_like_tool_call_rejects_empty_dict():+ assert not looks_like_tool_call("<x>y</x>", "{}")+++def test_looks_like_tool_call_rejects_non_a0_dict():+ assert not looks_like_tool_call('{"foo":"bar"}', '{"foo":"bar"}')def test_extension_replaces_result_refreshes_log_and_response_item(monkeypatch):@@ -222,20 +230,16 @@ def test_extension_handles_fallback_with_warning_and_skip(monkeypatch):hist_add_ai_response=lambda message, **kwargs: ai_responses.append(message) or SimpleNamespace(id="ai"),hist_add_warning=lambda message: warnings.append(message) or SimpleNamespace(id="warning"),)- llm_result = SimpleNamespace(response="plain text")+ llm_result = SimpleNamespace(response="<xml>not a tool call</xml>")result_data = {"llm_result": llm_result}ContextDoctor(agent).execute(result_data)assert result_data["skip_default_processing"] is True- assert llm_result.response == '{"thoughts":["plain text"]}'- assert ai_responses == ['{"thoughts":["plain text"]}']+ assert llm_result.response == "{}"+ assert ai_responses == ["{}"]assert warnings == ["fallback warning"]assert logs[0]["content"] == "A0: fallback notice"assert logs[0]["id"] == "warning"- assert log_item.data["kvps"]["thoughts"] == ["plain text"]- assert log_item.data["kvps"]["reasoning"] == "thinking"- assert log_item.data["content"] == "plain text"- assert log_item.data["kvps"]["thoughts"] == ["plain text"]assert log_item.data["kvps"]["reasoning"] == "thinking"- assert log_item.data["content"] == "plain text"+ assert log_item.data["content"] == "<xml>not a tool call</xml>"diff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex 0218740e0..5c1a0da54 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -22,6 +22,7 @@- The `*.py.dox.md` file owns tool purpose, tool arguments/concepts, output and `break_loop` behavior, side effects, important helper dependencies, prompt-contract notes, and verification guidance.- When a tool module is added, removed, renamed, or behaviorally changed, update its matching `*.py.dox.md` in the same change.- Do not leave stale file-level DOX after tool deletion or rename.+- Plugin tools may duplicate `get_log_object()` implementations across independently installable plugins; a shared helper cannot be used because plugins can be disabled independently. Tool headings must not include an `A0:` prefix; heading shape is per-tool.## Work Guidancediff --git a/webui/js/AGENTS.md b/webui/js/AGENTS.mdindex 6d343f70b..7b09582de 100644--- a/webui/js/AGENTS.md+++ b/webui/js/AGENTS.md@@ -17,7 +17,8 @@- `initFw.js` owns Alpine bootstrap and custom lifecycle directives such as `x-create`, `x-destroy`, and periodic `x-every-*` hooks.- `icons.js` owns `<x-icon>`, icon-name validation, the name property/attribute bridge, and helpers that read or update both the first-party custom element and legacy plugin ligature spans.- `messages.js` owns native message/process-step rendering, safe Markdown and HTML conversion, and KaTeX delimiter handling.-- `messages.js` owns routing of unknown/non-tool message types through `drawMessageTool` (the renderer shared with explicit tool steps) for unified tool-step chrome and action-button placement; the legacy default renderer is not used.+- `messages.js` owns routing of unknown/non-tool message types through `drawMessageTool` (the renderer shared with explicit tool steps) for unified tool-step chrome and action-button placement; the legacy `drawMessageDefault` renderer has no remaining callers and is kept only for community-plugin compatibility. Do not call it from new code; do not remove it without a deprecation cycle.+- `messages.js` owns `drawMessageAgent` kvps rendering order: `thoughts`, `tool_name`, `tool_args` keys (spread per-key under actual names, not a sub-table, skipping reserved keys), then `step` at the end. Reserved keys (`thoughts`, `step`, `reasoning`, `tool_name`, `tool_args`, `args`, `headline`) win over any colliding `tool_args` key. The `response` tool check is hoisted to skip arg rendering entirely for response turns.- `messages.js` owns `Scroller` smooth-scroll suppression for `GEN` process steps (live agent responses) to prevent streamed-content jumpiness; non-`GEN` steps keep smooth scrolling.- `message-collapse.js` owns the layout-safe overflow measurement shared by collapsible user messages and responses.- `message-window.js` owns the bounded, tail-first raw-log window used by message rendering.diff --git a/webui/js/messages.js b/webui/js/messages.jsindex 07b8ea80b..11bba857e 100644--- a/webui/js/messages.js+++ b/webui/js/messages.js@@ -1884,14 +1884,16 @@ export function drawMessageAgent({...additional}) {const title = cleanStepTitle(heading);+ const reservedKeys = new Set(["thoughts", "step", "reasoning", "tool_name", "tool_args", "args", "headline"]);let displayKvps = {};if (kvps?.thoughts) displayKvps["icon://lightbulb[Thoughts]"] = kvps.thoughts;- if (preferencesStore.showToolArgs) {+ const isResponse = kvps?.tool_name === "response";+ if (preferencesStore.showToolArgs && !isResponse) {if (kvps?.tool_name) displayKvps["icon://build[Tool]"] = kvps.tool_name;const toolArgs = kvps?.tool_args ?? kvps?.args;if (toolArgs) {Object.entries(toolArgs).forEach(([key, value]) => {- if (kvps.tool_name !== "response") displayKvps[key] = value;+ if (!reservedKeys.has(key)) displayKvps[key] = value;});}}