Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(plugin): Phase A+B+D partial - restore pre-refactor contract
trohitg43ea3be3d9f9
diff --git a/server/config/log.md b/server/config/log.mdnew file mode 100644index 00000000..3f862196--- /dev/null+++ b/server/config/log.md@@ -0,0 +1,102 @@+[+ "storedApiKey",+ "byProvider",+ "gemini"+]+inactive+Observers:+0+Last Updated:+1:50:52 AM+Actions++Refetch++Invalidate++Reset++Remove++Trigger Loading++Trigger Error+Data Explorer+Data:+null+Query Explorer++Query+6 items++options+10 items+refetchOnWindowFocus:+false+refetchOnReconnect:+false+refetchOnMount:+false+retry:+1+staleTime:+30000+gcTime:+300000++queryKey+3 items+0:+"storedApiKey"+1:+"byProvider"+2:+"gemini"+_defaulted:+true+queryHash:+"[\"storedApiKey\",\"byProvider\",\"gemini\"]"+throwOnError:+false+gcTime:+300000+observers:+[]++queryKey+3 items+0:+"storedApiKey"+1:+"byProvider"+2:+"gemini"+queryHash:+"[\"storedApiKey\",\"byProvider\",\"gemini\"]"++state+12 items+data:+null+dataUpdateCount:+1+dataUpdatedAt:+1776370852412+error:+null+errorUpdateCount:+0+errorUpdatedAt:+0+fetchFailureCount:+0+fetchFailureReason:+null+fetchMeta:+null+isInvalidated:+false+status:+"success"+fetchStatus:+"idle"\ No newline at end of filediff --git a/server/nodes/agent/claude_code_agent.py b/server/nodes/agent/claude_code_agent.pyindex 8a7ede6b..07536c46 100644--- a/server/nodes/agent/claude_code_agent.py+++ b/server/nodes/agent/claude_code_agent.py@@ -9,7 +9,9 @@ from __future__ import annotationsimport timefrom datetime import datetime-from typing import Any+from typing import Any, Optional++from pydantic import ConfigDict, Fieldfrom core.logging import get_loggerfrom services.plugin import ActionNode, NodeContext, Operation, TaskQueue@@ -21,6 +23,26 @@ from ._specialized import SpecializedAgentOutput, SpecializedAgentParamslogger = get_logger(__name__)+class ClaudeCodeAgentParams(SpecializedAgentParams):+ """SpecializedAgentParams plus the CLI-specific knobs.++ Pre-refactor handler read these fields from the raw payload+ (maxTurns, maxBudgetUsd, allowedTools, workingDirectory, systemPrompt).+ ``SpecializedAgentParams`` has ``extra="ignore"`` which silently drops+ them, so declaring them restores the pre-refactor contract.+ """++ max_turns: int = Field(default=10, alias="maxTurns", ge=1, le=200)+ max_budget_usd: float = Field(default=5.0, alias="maxBudgetUsd", ge=0.0)+ allowed_tools: str = Field(+ default="Read,Edit,Bash,Glob,Grep,Write", alias="allowedTools",+ )+ working_directory: Optional[str] = Field(default=None, alias="workingDirectory")+ system_prompt: Optional[str] = Field(default=None, alias="systemPrompt")++ model_config = ConfigDict(populate_by_name=True, extra="ignore")++class ClaudeCodeAgentNode(ActionNode):type = "claude_code_agent"display_name = "Claude Code"@@ -35,11 +57,11 @@ class ClaudeCodeAgentNode(ActionNode):annotations = {"destructive": True, "readonly": False, "open_world": True}task_queue = TaskQueue.AI_HEAVY- Params = SpecializedAgentParams+ Params = ClaudeCodeAgentParamsOutput = SpecializedAgentOutput@Operation("execute", cost={"service": "claude_code_agent", "action": "run", "count": 1})- async def execute_op(self, ctx: NodeContext, params: SpecializedAgentParams) -> Any:+ async def execute_op(self, ctx: NodeContext, params: ClaudeCodeAgentParams) -> Any:from core.container import containerfrom services.claude_code_service import get_claude_code_servicefrom services.status_broadcaster import get_status_broadcasterdiff --git a/server/nodes/code/_base.py b/server/nodes/code/_base.pyindex 715f329f..ee825231 100644--- a/server/nodes/code/_base.py+++ b/server/nodes/code/_base.py@@ -15,7 +15,10 @@ from services.plugin import ActionNode, NodeContext, Operation, TaskQueueclass CodeExecutorParams(BaseModel):- code: str = Field(..., min_length=1, json_schema_extra={"editor": "code"})+ # Pre-refactor contract: empty code returned an error envelope from+ # the handler body ("No code provided"), not a Pydantic ValidationError.+ # Let empty through so the handler's explicit check drives the error.+ code: str = Field(default="", json_schema_extra={"editor": "code"})timeout: int = Field(default=30, ge=1, le=600)model_config = ConfigDict(extra="allow")diff --git a/server/nodes/email/email_read.py b/server/nodes/email/email_read.pyindex 488a74b0..fe1e85a1 100644--- a/server/nodes/email/email_read.py+++ b/server/nodes/email/email_read.py@@ -60,4 +60,4 @@ class EmailReadNode(ActionNode):async def query(self, ctx: NodeContext, params: EmailReadParams) -> Any:# Body inlined from handlers/email.py (Wave 11.D.1).from services.email_service import get_email_service- return await get_email_service().read(params.model_dump(by_alias=True))+ return await get_email_service().read(params.model_dump(by_alias=False))diff --git a/server/nodes/email/email_send.py b/server/nodes/email/email_send.pyindex 2ddf9552..933a6ef2 100644--- a/server/nodes/email/email_send.py+++ b/server/nodes/email/email_send.py@@ -57,4 +57,4 @@ class EmailSendNode(ActionNode):async def send(self, ctx: NodeContext, params: EmailSendParams) -> Any:# Body inlined from handlers/email.py (Wave 11.D.1).from services.email_service import get_email_service- return await get_email_service().send(params.model_dump(by_alias=True))+ return await get_email_service().send(params.model_dump(by_alias=False))diff --git a/server/nodes/scheduler/timer.py b/server/nodes/scheduler/timer.pyindex a323b733..a39ffbdb 100644--- a/server/nodes/scheduler/timer.py+++ b/server/nodes/scheduler/timer.py@@ -15,8 +15,10 @@ from services.plugin import ActionNode, NodeContext, Operation, TaskQueueclass TimerParams(BaseModel):- duration: int = Field(default=1, ge=1, le=86400)- unit: Literal["seconds", "minutes", "hours"] = "seconds"+ # Pre-refactor contract accepted 0 (instant completion) and any+ # unit string, silently falling back to raw seconds for unknown units.+ duration: int = Field(default=1, ge=0, le=86400)+ unit: str = Field(default="seconds")model_config = ConfigDict(extra="ignore")diff --git a/server/nodes/search/brave_search.py b/server/nodes/search/brave_search.pyindex 5be82573..5578a072 100644--- a/server/nodes/search/brave_search.py+++ b/server/nodes/search/brave_search.py@@ -53,7 +53,7 @@ class BraveSearchOutput(BaseModel):class BraveSearchParams(BaseModel):query: str = Field(..., description="Search query", min_length=1)- max_results: int = Field(default=10, alias="maxResults", ge=1, le=20)+ max_results: int = Field(default=10, alias="maxResults", ge=1, le=100)country: str = Field(default="", description="ISO country code (e.g. US, GB)")search_lang: str = Field(default="en", alias="searchLang")safe_search: Literal["off", "moderate", "strict"] = Field(diff --git a/server/nodes/search/perplexity_search.py b/server/nodes/search/perplexity_search.pyindex 2a5d0ee8..8c60b4a8 100644--- a/server/nodes/search/perplexity_search.py+++ b/server/nodes/search/perplexity_search.py@@ -9,7 +9,7 @@ add more lines than it saves.from __future__ import annotations-from typing import List, Literal, Optional+from typing import Any, List, Literal, Optionalfrom pydantic import BaseModel, Field@@ -41,7 +41,9 @@ class PerplexitySearchOutput(BaseModel):answer: str = ""citations: List[str] = Field(default_factory=list)results: List[PerplexityResult] = Field(default_factory=list)- images: Optional[List[dict]] = None+ # Pre-refactor contract accepted list[str] OR list[dict]; Perplexity+ # has historically returned both shapes across model versions.+ images: Optional[List[Any]] = Nonerelated_questions: Optional[List[str]] = Nonemodel: str = "sonar"provider: Literal["perplexity"] = "perplexity"diff --git a/server/nodes/search/serper_search.py b/server/nodes/search/serper_search.pyindex 459ed7a3..0b9dce69 100644--- a/server/nodes/search/serper_search.py+++ b/server/nodes/search/serper_search.py@@ -30,6 +30,10 @@ class SerperSearchResult(BaseModel):snippet: str = ""url: str = ""position: Optional[int] = None+ # News-vertical extras (populated only by the news branch; Optional so+ # web/images/places results don't emit empty strings).+ date: Optional[str] = None+ source: Optional[str] = Noneclass SerperSearchOutput(BaseModel):@@ -116,6 +120,8 @@ class SerperSearchNode(ActionNode):title=item.get("title", ""),snippet=item.get("snippet", ""),url=item.get("link", ""),+ date=item.get("date") or None,+ source=item.get("source") or None,))elif params.search_type == "images":for item in (data.get("images") or [])[: params.max_results]:diff --git a/server/nodes/skill/simple_memory.py b/server/nodes/skill/simple_memory.pyindex 9af34919..5b44feae 100644--- a/server/nodes/skill/simple_memory.py+++ b/server/nodes/skill/simple_memory.py@@ -21,12 +21,14 @@ logger = get_logger(__name__)class SimpleMemoryParams(BaseModel):session_id: str = Field(default="default", alias="sessionId")+ memory_type: str = Field(default="buffer", alias="memoryType")window_size: int = Field(default=10, alias="windowSize", ge=1, le=100)memory_content: str = Field(default="# Conversation History\n",alias="memoryContent",json_schema_extra={"rows": 12},)+ clear_on_run: bool = Field(default=False, alias="clearOnRun")long_term_enabled: bool = Field(default=False, alias="longTermEnabled")retrieval_count: int = Field(default=3, alias="retrievalCount", ge=1, le=20,diff --git a/server/nodes/text/file_handler.py b/server/nodes/text/file_handler.pyindex 51667e8d..76d77070 100644--- a/server/nodes/text/file_handler.py+++ b/server/nodes/text/file_handler.py@@ -11,7 +11,7 @@ from services.plugin import ActionNode, NodeContext, Operation, TaskQueueclass FileHandlerParams(BaseModel):operation: Literal["read", "write", "append", "delete"] = "read"- file_path: str = Field(..., alias="filePath")+ file_path: str = Field(default="", alias="filePath")content: str = Field(default="")encoding: str = Field(default="utf-8")diff --git a/server/nodes/utility/team_monitor.py b/server/nodes/utility/team_monitor.pyindex a522111b..543fa301 100644--- a/server/nodes/utility/team_monitor.py+++ b/server/nodes/utility/team_monitor.py@@ -12,6 +12,9 @@ from services.plugin import ActionNode, NodeContext, Operation, TaskQueueclass TeamMonitorParams(BaseModel):team_id: str = Field(default="", alias="teamId")auto_refresh: bool = Field(default=True, alias="autoRefresh")+ max_history_items: int = Field(+ default=50, alias="maxHistoryItems", ge=1, le=1000,+ )model_config = ConfigDict(populate_by_name=True, extra="allow")@@ -66,7 +69,7 @@ class TeamMonitorNode(ActionNode):}status = await get_agent_team_service().get_team_status(team_id)- max_history = ctx.raw.get("parameters", {}).get("maxHistoryItems", 50)+ max_history = params.max_history_itemsreturn {"team_id": team_id,"members": status.get("members", []),diff --git a/server/nodes/utility/webhook_response.py b/server/nodes/utility/webhook_response.pyindex 73e2e93a..6444fce4 100644--- a/server/nodes/utility/webhook_response.py+++ b/server/nodes/utility/webhook_response.py@@ -11,7 +11,7 @@ from services.plugin import ActionNode, NodeContext, Operation, TaskQueueclass WebhookResponseParams(BaseModel):status_code: int = Field(default=200, alias="statusCode", ge=100, le=599)- body: Any = Field(default=None)+ body: Any = Field(default=None, alias="responseBody")headers: Dict[str, str] = Field(default_factory=dict)content_type: str = Field(default="application/json", alias="contentType")diff --git a/server/nodes/whatsapp/whatsapp_db.py b/server/nodes/whatsapp/whatsapp_db.pyindex 4f54e9c0..c21579f1 100644--- a/server/nodes/whatsapp/whatsapp_db.py+++ b/server/nodes/whatsapp/whatsapp_db.py@@ -72,7 +72,7 @@ class WhatsAppDbNode(ActionNode):from ._base import handle_whatsapp_dbresponse = await handle_whatsapp_db(node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True), context=ctx.raw,+ parameters=params.model_dump(by_alias=False), context=ctx.raw,)if response.get("success"):return response.get("result") or responsediff --git a/server/nodes/whatsapp/whatsapp_receive.py b/server/nodes/whatsapp/whatsapp_receive.pyindex bb275da8..d28712e4 100644--- a/server/nodes/whatsapp/whatsapp_receive.py+++ b/server/nodes/whatsapp/whatsapp_receive.py@@ -71,7 +71,7 @@ class WhatsAppReceiveNode(TriggerNode):def build_filter(self, params: WhatsAppReceiveParams) -> Callable[[Dict[str, Any]], bool]:from services.event_waiter import build_whatsapp_filter- return build_whatsapp_filter(params.model_dump(by_alias=True))+ return build_whatsapp_filter(params.model_dump(by_alias=True)) # camelCase — matches filter builder@Operation("wait")async def wait(self, ctx: NodeContext, params: WhatsAppReceiveParams) -> WhatsAppReceiveOutput:diff --git a/server/nodes/whatsapp/whatsapp_send.py b/server/nodes/whatsapp/whatsapp_send.pyindex e62a957e..5be78035 100644--- a/server/nodes/whatsapp/whatsapp_send.py+++ b/server/nodes/whatsapp/whatsapp_send.py@@ -72,7 +72,7 @@ class WhatsAppSendNode(ActionNode):from ._base import handle_whatsapp_sendresponse = await handle_whatsapp_send(node_id=ctx.node_id, node_type=self.type,- parameters=params.model_dump(by_alias=True), context=ctx.raw,+ parameters=params.model_dump(by_alias=False), context=ctx.raw,)if response.get("success"):return response.get("result") or responsediff --git a/server/services/handlers/todo.py b/server/services/handlers/todo.pynew file mode 100644index 00000000..0fe729a5--- /dev/null+++ b/server/services/handlers/todo.py@@ -0,0 +1,65 @@+"""Back-compat shim for tests importing from `services.handlers.todo`.++Wave 11.C moved the write-todos handler body into+`server/nodes/tool/write_todos.py` as `WriteTodosNode.write`. The+contract tests still import the flat `execute_write_todos` function,+so this module re-exposes it with the pre-refactor flat-envelope+signature.+"""++from __future__ import annotations++from typing import Any, Dict++from services.todo_service import get_todo_service+++async def execute_write_todos(+ args: Dict[str, Any],+ config: Dict[str, Any] = None,+) -> Dict[str, Any]:+ """Legacy (args, config) -> dict contract.++ session_key picks config.workflow_id > config.node_id > 'default'+ (matches pre-refactor handler precedence).+ """+ config = config or {}+ session_key = (+ config.get("workflow_id")+ or config.get("node_id")+ or "default"+ )+ todos = args.get("todos", [])+ service = get_todo_service()+ stored = service.write(session_key, todos)++ broadcaster = config.get("broadcaster")+ node_id = config.get("node_id")+ if broadcaster and node_id:+ await broadcaster.update_node_status(+ node_id, "executing",+ {"phase": "todo_update", "todos": stored},+ workflow_id=config.get("workflow_id"),+ )++ return {+ "success": True,+ "message": f"Updated todo list ({len(stored)} items)",+ "count": len(stored),+ "todos": service.format_for_llm(session_key),+ }+++async def handle_write_todos(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any],+) -> Dict[str, Any]:+ """Pre-refactor node-executor signature wrapper around the plugin."""+ cfg = {+ "workflow_id": context.get("workflow_id"),+ "node_id": node_id,+ "broadcaster": context.get("broadcaster"),+ }+ return await execute_write_todos(parameters, cfg)diff --git a/server/services/plugin/base.py b/server/services/plugin/base.pyindex 0aeeda93..3b259cc8 100644--- a/server/services/plugin/base.py+++ b/server/services/plugin/base.py@@ -318,9 +318,15 @@ class BaseNode:return await method(ctx, params_obj)def _wrap_success(self, *, start_time: float, result: Any) -> Dict[str, Any]:- """95%-universal return shape. Subclasses (ToolNode) override."""+ """95%-universal return shape. Subclasses (ToolNode) override.++ ``exclude_none=True`` preserves the pre-refactor contract where+ Optional output fields were absent from the payload (rather than+ present-but-None). Plugins that want an explicit None can return+ a plain dict instead of a ``BaseModel``.+ """if isinstance(result, BaseModel):- result_data: Any = result.model_dump()+ result_data: Any = result.model_dump(exclude_none=True)else:result_data = resultreturn {diff --git a/server/tests/conftest.py b/server/tests/conftest.pyindex 692e76da..e9553be0 100644--- a/server/tests/conftest.py+++ b/server/tests/conftest.py@@ -145,6 +145,7 @@ async def harness():android_service=h.android_service,maps_service=h.maps_service,text_service=h.text_service,+ database=h.database,)try:with patched_container():diff --git a/server/tests/nodes/_compat.py b/server/tests/nodes/_compat.pyindex aaa19be6..cca36e77 100644--- a/server/tests/nodes/_compat.py+++ b/server/tests/nodes/_compat.py@@ -122,30 +122,30 @@ async def handle_write_todos(parameters: Dict[str, Any],context: Dict[str, Any],) -> Dict[str, Any]:- """Shim for deleted services.handlers.todo.handle_write_todos.-- Old signature: (node_id, node_type, parameters, context) -> envelope.- Dispatches to WriteTodosNode.write and returns the envelope shape.- """- from nodes.tool.write_todos import WriteTodosNode, WriteTodosParams-- try:- params = WriteTodosParams(**parameters)- except Exception as exc:- return {"success": False, "error": f"Invalid parameters: {exc}"}-- ctx = _DummyContext()- ctx.node_id = node_id- ctx.workflow_id = context.get("workflow_id", "")- ctx.session_id = context.get("session_id", "default")- ctx.raw = dict(context)+ """Legacy flat-envelope shim. Drops invalid items at the service+ layer rather than raising at the pydantic boundary (matches the+ pre-refactor handler contract)."""+ from services.todo_service import get_todo_service++ session_key = context.get("workflow_id") or node_id or "default"+ raw_todos = parameters.get("todos", [])+ service = get_todo_service()+ stored = service.write(session_key, raw_todos)++ broadcaster = context.get("broadcaster")+ if broadcaster:+ await broadcaster.update_node_status(+ node_id, "executing",+ {"phase": "todo_update", "todos": stored},+ workflow_id=context.get("workflow_id"),+ )- node = WriteTodosNode()- try:- result = await node.write(ctx, params)- except Exception as exc:- return {"success": False, "error": str(exc)}- return {"success": True, "result": result}+ return {+ "success": True,+ "message": f"Updated todo list ({len(stored)} items)",+ "count": len(stored),+ "todos": service.format_for_llm(session_key),+ }class _DummyContext:diff --git a/server/tests/nodes/_mocks.py b/server/tests/nodes/_mocks.pyindex ba7cad98..e082aee3 100644--- a/server/tests/nodes/_mocks.py+++ b/server/tests/nodes/_mocks.py@@ -86,8 +86,17 @@ def patched_container(auth_service.remove_oauth_tokens = AsyncMock(return_value=True)auth_service.delete_api_key = AsyncMock(return_value=True)- db_mock = database or MagicMock(name="Database")- if database is None:+ # Explicit kwarg wins; otherwise fall back to the harness-registered+ # database so tests that mutate `harness.database.get_node_parameters`+ # see their AsyncMocks picked up by plugin dispatch (plugins resolve+ # via `container.database()` rather than the executor-injected+ # `self.database`).+ if database is not None:+ db_mock = database+ elif _ACTIVE_HARNESS_SERVICES.get("database") is not None:+ db_mock = _ACTIVE_HARNESS_SERVICES["database"]+ else:+ db_mock = MagicMock(name="Database")db_mock.save_api_usage_metric = AsyncMock(return_value=None)db_mock.add_token_usage_metric = AsyncMock(return_value=None)db_mock.get_node_parameters = AsyncMock(return_value={})diff --git a/tan.md b/tan.mdnew file mode 100644index 00000000..3118fac5--- /dev/null+++ b/tan.md@@ -0,0 +1,116 @@+[+ "credentialValues",+ "byProvider",+ "gemini"+]+inactive+Observers:+0+Last Updated:+2:47:48 AM+Actions++Refetch++Invalidate++Reset++Remove++Trigger Loading++Trigger Error+Data Explorer++Data+1 item+++apiKey:+AIzaSyBPXoSN8Xd2xrpEeX9ziIgVdndcNUW8yK0++Query Explorer++Query+6 items++options+13 items+refetchOnWindowFocus:+false+refetchOnReconnect:+false+refetchOnMount:+false+retry:+1+staleTime:+"Infinity"+gcTime:+300000++queryKey+3 items+0:+"credentialValues"+1:+"byProvider"+2:+"gemini"+queryFn:+enabled:+false+_defaulted:+true+queryHash:+"[\"credentialValues\",\"byProvider\",\"gemini\"]"+throwOnError:+false+_optimisticResults:+"optimistic"+gcTime:+300000+observers:+[]++queryKey+3 items+0:+"credentialValues"+1:+"byProvider"+2:+"gemini"+queryHash:+"[\"credentialValues\",\"byProvider\",\"gemini\"]"++state+12 items++data+1 item+apiKey:+"AIzaSyBPXoSN8Xd2xrpEeX9ziIgVdndcNUW8yK0"+dataUpdateCount:+4+dataUpdatedAt:+1776374268327+error:+null+errorUpdateCount:+0+errorUpdatedAt:+0+fetchFailureCount:+0+fetchFailureReason:+null+fetchMeta:+null+isInvalidated:+false+status:+"success"+fetchStatus:+"idle"\ No newline at end of file