diff --git a/helpers/parallel_tools.py b/helpers/parallel_tools.py index 82dbe5560..c4a0617fc 100644 --- a/helpers/parallel_tools.py +++ b/helpers/parallel_tools.py @@ -8,6 +8,7 @@ from dataclasses import dataclass, field, replace from typing import Any, Literal, TYPE_CHECKING from helpers import extract_tools +from helpers.tool import coerce_bool from helpers.defer import DeferredTask, THREAD_BACKGROUND from helpers.extension import call_extensions_async from helpers.print_style import PrintStyle @@ -141,20 +142,6 @@ def normalize_job_ids(raw_job_ids: Any) -> list[str]: raise ValueError("`job_ids` must be a string or an array of strings.") -def coerce_bool(value: Any, default: bool) -> bool: - if value is None: - return default - if isinstance(value, bool): - return value - if isinstance(value, str): - normalized = value.strip().lower() - if normalized in {"1", "true", "yes", "on"}: - return True - if normalized in {"0", "false", "no", "off"}: - return False - return bool(value) - - def coerce_timeout(value: Any) -> int: if value in (None, ""): return DEFAULT_TIMEOUT_SECONDS diff --git a/helpers/tool.py b/helpers/tool.py index 820164d59..b30ae69c0 100644 --- a/helpers/tool.py +++ b/helpers/tool.py @@ -14,6 +14,20 @@ class Response: break_loop: bool additional: dict[str, Any] | None = None +def coerce_bool(value: Any, default: bool) -> bool: + """Coerce a tool argument to bool: booleans pass, common true/false strings map, unknown values fall back to truthiness.""" + if value is None: + return default + if isinstance(value, bool): + return value + if isinstance(value, str): + normalized = value.strip().lower() + if normalized in {"1", "true", "yes", "on"}: + return True + if normalized in {"0", "false", "no", "off"}: + return False + return bool(value) + class Tool: def __init__(self, agent: Agent, name: str, method: str | None, args: dict[str,str], message: str, loop_data: LoopData | None, **kwargs) -> None: diff --git a/helpers/tool.py.dox.md b/helpers/tool.py.dox.md index 5577d7fbc..36f03ea2a 100644 --- a/helpers/tool.py.dox.md +++ b/helpers/tool.py.dox.md @@ -11,6 +11,7 @@ - `tool.py` owns the runtime implementation. - `tool.py.dox.md` owns durable notes about responsibilities, contracts, side effects, and verification for that implementation. - Classes: +- `coerce_bool(value: Any, default: bool) -> bool` (module-level function shared by tools and plugins) - `Response` (no explicit base class) - `Tool` (no explicit base class) - `async execute(self, **kwargs) -> Response` diff --git a/plugins/_a0_connector/tools/code_execution_remote.py b/plugins/_a0_connector/tools/code_execution_remote.py index 73bfa585f..c69ddfe13 100644 --- a/plugins/_a0_connector/tools/code_execution_remote.py +++ b/plugins/_a0_connector/tools/code_execution_remote.py @@ -5,7 +5,7 @@ import asyncio import uuid from typing import Any -from helpers.tool import Response, Tool +from helpers.tool import Response, Tool, coerce_bool from helpers.ws_manager import ( ConnectionNotFoundError, WsPayloadTooLargeError, @@ -44,16 +44,6 @@ class CodeExecutionRemote(Tool): def _runtime_requires_write_access(runtime: str) -> bool: return runtime in {"terminal", "python", "nodejs"} - @staticmethod - def _coerce_bool(value: Any) -> bool: - if isinstance(value, bool): - return value - if isinstance(value, (int, float)): - return bool(value) - if isinstance(value, str): - return value.strip().lower() in {"1", "true", "yes", "on"} - return False - @staticmethod def _timeout_group_for_runtime( runtime: str, @@ -169,7 +159,7 @@ class CodeExecutionRemote(Tool): "session": session, "context_id": context_id, } - if runtime != "reset" and self._coerce_bool(self.args.get("reset")): + if runtime != "reset" and coerce_bool(self.args.get("reset"), False): payload["reset"] = True if runtime in {"terminal", "python", "nodejs"}: diff --git a/plugins/_a0_connector/tools/computer_use_remote.py b/plugins/_a0_connector/tools/computer_use_remote.py index b3d39b4c6..639f34db4 100644 --- a/plugins/_a0_connector/tools/computer_use_remote.py +++ b/plugins/_a0_connector/tools/computer_use_remote.py @@ -8,7 +8,7 @@ from typing import Any from helpers import chat_media, history, media_artifacts from helpers.print_style import PrintStyle -from helpers.tool import Response, Tool +from helpers.tool import Response, Tool, coerce_bool from helpers.ws_manager import ConnectionNotFoundError, get_shared_ws_manager from plugins._a0_connector.helpers.ws_runtime import ( @@ -309,7 +309,7 @@ class ComputerUseRemote(Tool): return _SETTLE_DELAY_AX_ACTION if action == "uia_action": return _SETTLE_DELAY_UIA_ACTION - if action == "type" and self._coerce_bool(self.args.get("submit")): + if action == "type" and coerce_bool(self.args.get("submit"), False): return _SETTLE_DELAY_SUBMIT if action == "type": return _SETTLE_DELAY_TYPE @@ -364,7 +364,7 @@ class ComputerUseRemote(Tool): payload["text"] = self.args.get("text", "") if "window_id" in self.args: payload["window_id"] = self.args.get("window_id") - if self._coerce_bool(self.args.get("submit")): + if coerce_bool(self.args.get("submit"), False): payload["submit"] = True elif action == "list_windows": for key in ("include_hidden", "include_offscreen", "max_windows"): @@ -438,7 +438,7 @@ class ComputerUseRemote(Tool): payload["value"] = self.args.get("value") if "text" in self.args: payload["text"] = self.args.get("text", "") - if self._coerce_bool(self.args.get("submit")): + if coerce_bool(self.args.get("submit"), False): payload["submit"] = True return payload @@ -1052,13 +1052,6 @@ class ComputerUseRemote(Tool): except (TypeError, ValueError) as exc: raise ValueError(f"{name} must be an integer") from exc - def _coerce_bool(self, value: object) -> bool: - if isinstance(value, bool): - return value - if isinstance(value, (int, float)): - return bool(value) - return str(value or "").strip().lower() in {"1", "true", "yes", "on"} - def _sanitize_tool_text(value: str) -> str: try: diff --git a/plugins/_a2a_chat/AGENTS.md b/plugins/_a2a_chat/AGENTS.md index 141003dcf..b4f6d1a2d 100644 --- a/plugins/_a2a_chat/AGENTS.md +++ b/plugins/_a2a_chat/AGENTS.md @@ -9,12 +9,13 @@ - `tools/a2a_chat.py` owns session caching, message extraction, and remote dispatch. - The tool logs its message as type `a2a_chat` with an `icon://hub Chatting: ` headline; `extensions/webui/get_message_handler/` owns the `A2A` badge presentation and `extensions/webui/get_process_step_types/` registers the type. - `helpers/fasta2a_client.py` owns the FastA2A client connection, message dispatch, and task polling. -- `prompts/` owns the tool prompt and the framework messages for failures and repair hints. +- `prompts/` owns the tool prompt and the framework messages for failures. - `plugin.yaml` and `README.md` own metadata and docs. ## Local Contracts - Session state is stored on `agent.data["_a2a_sessions"]`, keyed by a normalized agent URL that strips an explicit `/a2a` suffix. +- The `reset` argument coerces through the shared `coerce_bool` helper instead of returning a repairable error; absent values default to `false`, other unrecognized values fall back to truthiness. - Remote text extraction prefers the newest assistant history message, then status message, then artifacts; an empty extraction returns a distinct failed-response error instead of success. - The tool reports a2a unavailability without raising. diff --git a/plugins/_a2a_chat/prompts/fw.a2a_chat.invalid_reset.md b/plugins/_a2a_chat/prompts/fw.a2a_chat.invalid_reset.md deleted file mode 100644 index 330cde21f..000000000 --- a/plugins/_a2a_chat/prompts/fw.a2a_chat.invalid_reset.md +++ /dev/null @@ -1 +0,0 @@ -Invalid reset value: {{reset}}. Use a JSON boolean. diff --git a/plugins/_a2a_chat/tools/a2a_chat.py b/plugins/_a2a_chat/tools/a2a_chat.py index 4e4b00e76..873e1760a 100644 --- a/plugins/_a2a_chat/tools/a2a_chat.py +++ b/plugins/_a2a_chat/tools/a2a_chat.py @@ -1,7 +1,7 @@ import uuid from typing import Any -from helpers.tool import Tool, Response +from helpers.tool import Tool, Response, coerce_bool from helpers.print_style import PrintStyle from helpers.strings import truncate_text from plugins._a2a_chat.helpers.fasta2a_client import connect_to_agent, is_client_available @@ -92,17 +92,7 @@ class A2AChatTool(Tool): agent_url: str | None = kwargs.get("agent_url") # required user_message: str | None = kwargs.get("message") # required attachments = kwargs.get("attachments", None) # optional list[str] - reset = kwargs.get("reset", False) - if not isinstance(reset, bool): - if isinstance(reset, str) and reset.strip().lower() in {"true", "1", "yes"}: - reset = True - elif isinstance(reset, str) and reset.strip().lower() in {"false", "0", "no", "", "none", "null"}: - reset = False - else: - return Response( - message=self.agent.read_prompt("fw.a2a_chat.invalid_reset.md", reset=reset), - break_loop=False, - ) + reset = coerce_bool(kwargs.get("reset", False), False) if not agent_url or not isinstance(agent_url, str): return Response( message=self.agent.read_prompt("fw.a2a_chat.agent_url_missing.md"), diff --git a/plugins/_a2a_chat/tools/a2a_chat.py.dox.md b/plugins/_a2a_chat/tools/a2a_chat.py.dox.md index aecaa9dfa..4923e94f2 100644 --- a/plugins/_a2a_chat/tools/a2a_chat.py.dox.md +++ b/plugins/_a2a_chat/tools/a2a_chat.py.dox.md @@ -26,7 +26,7 @@ - `A2AChatTool` is a `Tool`. - `A2AChatTool` defines `execute(...)`. - Observed side-effect areas: agent state in `agent.data["_a2a_sessions"]`. -- Agent-facing failure and repair messages render from `prompts/` framework message files. +- Agent-facing failure messages render from `prompts/` framework message files. - Imported dependency areas include: `plugins._a2a_chat.helpers.fasta2a_client`, `helpers.print_style`, `helpers.tool`, `typing`. ## Key Concepts diff --git a/plugins/_code_execution/tools/code_execution_tool.py b/plugins/_code_execution/tools/code_execution_tool.py index ad545c91f..9732cd4fc 100644 --- a/plugins/_code_execution/tools/code_execution_tool.py +++ b/plugins/_code_execution/tools/code_execution_tool.py @@ -5,7 +5,7 @@ import re import shlex import time -from helpers.tool import Tool, Response +from helpers.tool import Tool, Response, coerce_bool from helpers import files, rfc_exchange, projects, runtime, secrets, settings from helpers.print_style import PrintStyle from helpers.strings import truncate_text as truncate_text_string @@ -69,8 +69,8 @@ class CodeExecution(Tool): runtime_arg = self.args.get("runtime", "").lower().strip() session = int(self.args.get("session", 0)) - self.allow_running = bool(self.args.get("allow_running", False)) - reset = bool(self.args.get("reset", False) or runtime_arg == "reset") + self.allow_running = coerce_bool(self.args.get("allow_running", False), False) + reset = coerce_bool(self.args.get("reset", False), False) or runtime_arg == "reset" cfg = _get_config(self.agent) diff --git a/plugins/_scheduler/prompts/fw.scheduler.invalid_dedicated_context.md b/plugins/_scheduler/prompts/fw.scheduler.invalid_dedicated_context.md deleted file mode 100644 index 6d61b9a59..000000000 --- a/plugins/_scheduler/prompts/fw.scheduler.invalid_dedicated_context.md +++ /dev/null @@ -1 +0,0 @@ -Invalid dedicated_context value: {{dedicated_context}}. Use a JSON boolean. \ No newline at end of file diff --git a/plugins/_scheduler/tools/scheduler.py b/plugins/_scheduler/tools/scheduler.py index 1a431ea85..985da81d8 100644 --- a/plugins/_scheduler/tools/scheduler.py +++ b/plugins/_scheduler/tools/scheduler.py @@ -6,7 +6,7 @@ import random import re from typing import Any import pytz -from helpers.tool import Tool, Response +from helpers.tool import Tool, Response, coerce_bool from helpers.task_scheduler import ( TaskScheduler, ScheduledTask, AdHocTask, PlannedTask, serialize_task, TaskState, TaskSchedule, TaskPlan, parse_datetime, @@ -91,19 +91,6 @@ def _task_schedule_from_input(schedule: Any, timezone: str | None = None) -> Tas return TaskSchedule(**task_schedule_kwargs) -def parse_bool_arg(value: Any) -> bool | None: - """Coerce JSON-style boolean args; strings true/false are accepted, anything else is invalid.""" - if isinstance(value, bool): - return value - if isinstance(value, str): - lowered = value.strip().lower() - if lowered in {"true", "1", "yes", "y"}: - return True - if lowered in {"false", "0", "no", "n"}: - return False - return None - - def _validate_task_schedule(task_schedule: TaskSchedule) -> str: # Validate cron expression, agent might hallucinate cron_regex = r"^((((\d+,)+\d+|(\d+(\/|-|#)\d+)|(\d+-\d+(\/\d+)?)|\d+L?|\*(\/\d+)?|L(-\d+)?|\?|[A-Z]{3}(-[A-Z]{3})?) ?){5,7})$" @@ -295,15 +282,7 @@ class SchedulerTool(Tool): update_params["state"] = state_value if "dedicated_context" in kwargs: - dedicated_context = parse_bool_arg(kwargs.get("dedicated_context")) - if dedicated_context is None: - return Response( - message=self.agent.read_prompt( - "fw.scheduler.invalid_dedicated_context.md", - dedicated_context=kwargs.get("dedicated_context"), - ), - break_loop=False, - ) + dedicated_context = coerce_bool(kwargs.get("dedicated_context"), False) update_params["context_id"] = task.uuid if dedicated_context else self.agent.context.id try: diff --git a/plugins/_wait/helpers/wait.py b/plugins/_wait/helpers/wait.py index a777dfa73..c37a2a419 100644 --- a/plugins/_wait/helpers/wait.py +++ b/plugins/_wait/helpers/wait.py @@ -28,7 +28,6 @@ def format_remaining_time(total_seconds: float) -> str: async def managed_wait(agent, target_time, is_duration_wait, log, get_heading_callback): - # Anchor updates to absolute 1s ticks so overhead cannot shift the countdown phase. next_tick = Localization.get().now() diff --git a/tests/test_browser_agent_regressions.py b/tests/test_browser_agent_regressions.py index f33882074..0d4dabccf 100644 --- a/tests/test_browser_agent_regressions.py +++ b/tests/test_browser_agent_regressions.py @@ -16,6 +16,13 @@ PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) +# Import real modules first so setdefault stubs below never shadow them for later collectors. +import agent +import helpers.tool +import helpers.ws +import helpers.ws_manager +import plugins._model_config.helpers.model_config + class _TestAgentContext: @staticmethod @@ -4716,7 +4723,7 @@ async def test_browser_runtime_screenshot_file_defaults_to_chat_scoped_artifact( @pytest.mark.anyio async def test_vision_load_materializes_ephemeral_browser_refs(monkeypatch, tmp_path): - monkeypatch.setitem(sys.modules, "helpers.tool", SimpleNamespace(Response=_TestResponse, Tool=_TestTool)) + monkeypatch.setitem(sys.modules, "helpers.tool", SimpleNamespace(Response=_TestResponse, Tool=_TestTool, coerce_bool=helpers.tool.coerce_bool)) history_stub = ModuleType("helpers.history") class _RawMessage(dict): diff --git a/tests/test_tool_action_contracts.py b/tests/test_tool_action_contracts.py index 1110090de..804112c3a 100644 --- a/tests/test_tool_action_contracts.py +++ b/tests/test_tool_action_contracts.py @@ -115,10 +115,25 @@ def _skill_instruction_name(message) -> str: return "" +def _fake_coerce_bool(value, default): + if value is None: + return default + if isinstance(value, bool): + return value + if isinstance(value, str): + normalized = value.strip().lower() + if normalized in {"1", "true", "yes", "on"}: + return True + if normalized in {"0", "false", "no", "off"}: + return False + return bool(value) + + def _install_tool_stub(monkeypatch) -> None: tool_stub = types.ModuleType("helpers.tool") tool_stub.Tool = _FakeTool tool_stub.Response = _FakeResponse + tool_stub.coerce_bool = _fake_coerce_bool monkeypatch.setitem(sys.modules, "helpers.tool", tool_stub) diff --git a/tools/call_subordinate.py b/tools/call_subordinate.py index 5f233ace7..4871bd9be 100644 --- a/tools/call_subordinate.py +++ b/tools/call_subordinate.py @@ -3,7 +3,7 @@ import asyncio from agent import Agent, AgentContext, UserMessage from helpers import message_queue, persist_chat, projects, subagents from helpers.errors import RepairableException -from helpers.tool import Tool, Response +from helpers.tool import Tool, Response, coerce_bool from initialize import initialize_agent from extensions.python.hist_add_tool_result import _90_save_tool_call_file as save_tool_call_file from plugins._model_config.helpers.model_config import DEFAULT_PRESET_NAME, get_configured_preset_name @@ -131,7 +131,7 @@ def get_or_create_subordinate( ) -> Agent: requested_profile = _validate_subordinate_profile(parent, profile) target_context_id = str(context_id or "").strip() - reset_requested = str(reset).lower().strip() == "true" + reset_requested = coerce_bool(reset, False) if target_context_id and reset_requested: raise RepairableException( "`context_id` continues an existing subordinate and requires reset=false. " diff --git a/tools/parallel.py b/tools/parallel.py index cf83bc823..788d5934e 100644 --- a/tools/parallel.py +++ b/tools/parallel.py @@ -1,4 +1,4 @@ -from helpers.tool import Tool, Response +from helpers.tool import Tool, Response, coerce_bool from helpers import parallel_tools from helpers.strings import sanitize_string @@ -55,7 +55,7 @@ class ParallelTool(Tool): ) wait_default = action not in {"start", "background", "collect"} - wait = parallel_tools.coerce_bool(args.get("wait"), wait_default) + wait = coerce_bool(args.get("wait"), wait_default) if action in {"await", "wait"}: wait = True