Skip to content

Self-improving AI Employees for everyone

fix(temporal): F4.B AgentWorkflow runtime — message preservation, output store, tool dispatch, lifecycle phases

trohitg4df6c5d3b950
diff --git a/server/nodes/browser/browser/__init__.py b/server/nodes/browser/browser/__init__.py
index be0cad68..71de5efd 100644
--- a/server/nodes/browser/browser/__init__.py
+++ b/server/nodes/browser/browser/__init__.py
@@ -18,6 +18,7 @@ from pydantic import BaseModel, ConfigDict, Field
from core.logging import get_logger
from services.plugin import ActionNode, NodeContext, Operation, TaskQueue
+from services.plugin.base import NodeUserError
logger = get_logger(__name__)
@@ -85,13 +86,13 @@ def _resolve_browser(selection: str, custom_path: str) -> Optional[str]:
def _req(p: Dict[str, Any], key: str) -> str:
v = (p.get(key) or "").strip()
if not v:
- raise ValueError(f"{key} is required")
+ raise NodeUserError(f"{key} is required")
return v
def _req_sel(s: str) -> str:
if not s:
- raise ValueError("selector is required")
+ raise NodeUserError("selector is required")
return s
diff --git a/server/nodes/search/duckduckgo_search/__init__.py b/server/nodes/search/duckduckgo_search/__init__.py
index d2cddb77..a10f0b8c 100644
--- a/server/nodes/search/duckduckgo_search/__init__.py
+++ b/server/nodes/search/duckduckgo_search/__init__.py
@@ -16,6 +16,7 @@ from typing import List
from pydantic import BaseModel, Field
from services.plugin import NodeContext, Operation, TaskQueue, ToolNode
+from services.plugin.base import NodeUserError
class DuckDuckGoResult(BaseModel):
@@ -60,11 +61,19 @@ class DuckDuckGoSearchNode(ToolNode):
self, ctx: NodeContext, params: DuckDuckGoSearchParams,
) -> DuckDuckGoSearchOutput:
from ddgs import DDGS
+ from ddgs.exceptions import DDGSException
def _search_sync():
return list(DDGS().text(params.query, max_results=params.max_results))
- raw = await asyncio.get_event_loop().run_in_executor(None, _search_sync)
+ try:
+ raw = await asyncio.get_event_loop().run_in_executor(None, _search_sync)
+ except DDGSException as e:
+ # Upstream search service rejected the query (rate-limit /
+ # transient network failure / bot detection). LLM can retry
+ # with a different query — surface as NodeUserError so
+ # BaseNode logs one WARN line, no traceback.
+ raise NodeUserError(f"DuckDuckGo search failed: {e}") from e
results = [
DuckDuckGoResult(
title=item.get("title", ""),
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index a6063412..656faf19 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -321,8 +321,59 @@ class BaseNode:
try:
result = await self._run_operation(op_spec, params_obj, context)
except PermissionError as e:
+ # Credential.resolve() raises PermissionError annotated with
+ # .provider / .reason / .auth attributes (see
+ # services/plugin/credential.py). When .provider is present,
+ # emit a CloudEvents-typed broadcast via
+ # ``broadcast_credential_event`` — the existing wire used by
+ # every credential mutation. The envelope rides as a
+ # WorkflowEvent with type ``credential.{auth}.runtime_failed``
+ # so frontend consumers can glob-match ``credential.*.*``
+ # without inventing a new wire-frame key. Surface a
+ # ``credential`` block in the operation response so the user
+ # gets a structured error envelope rather than a raw string.
+ provider = getattr(e, "provider", None)
+ reason = getattr(e, "reason", "denied")
+ auth = getattr(e, "auth", "api_key")
+ # Normalize "oauth2" -> "oauth" so the event type aligns with
+ # the existing CloudEvents naming (``credential.oauth.connected``,
+ # ``credential.oauth.disconnected``, ``credential.oauth.validated``).
+ auth_kind = "oauth" if auth == "oauth2" else auth
+ workflow_id: Optional[str] = None
+ if isinstance(context.raw, dict):
+ workflow_id = context.raw.get("workflow_id")
+ if provider:
+ try:
+ from services.status_broadcaster import get_status_broadcaster
+ broadcaster = get_status_broadcaster()
+ await broadcaster.broadcast_credential_event(
+ event_type=f"credential.{auth_kind}.runtime_failed",
+ provider=provider,
+ workflow_id=workflow_id,
+ reason=reason,
+ node_id=node_id,
+ error=str(e),
+ )
+ except Exception:
+ # Broadcast failure must never mask the original error.
+ logger.debug(
+ "[%s] failed to broadcast credential runtime failure for %s",
+ self.type, provider, exc_info=True,
+ )
+ extra: Optional[Dict[str, Any]] = None
+ if provider:
+ extra = {
+ "credential": {
+ "provider": provider,
+ "reason": reason,
+ "remediation": "add_key" if reason == "missing" else "reconnect",
+ }
+ }
return self._wrap_error(
- start_time=start_time, error=str(e), error_type="PermissionDeniedError"
+ start_time=start_time,
+ error=str(e),
+ error_type="PermissionDeniedError",
+ extra=extra,
)
except NodeUserError as e:
# Expected, user-correctable: log a single WARN line so it
@@ -431,15 +482,23 @@ class BaseNode:
}
def _wrap_error(
- self, *, start_time: float, error: str, error_type: str = "Error"
+ self,
+ *,
+ start_time: float,
+ error: str,
+ error_type: str = "Error",
+ extra: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
- return {
+ envelope: Dict[str, Any] = {
"success": False,
"error": error,
"error_type": error_type,
"execution_time": round(time.time() - start_time, 3),
"timestamp": datetime.now(timezone.utc).isoformat(),
}
+ if extra:
+ envelope.update(extra)
+ return envelope
# ---- Temporal ---------------------------------------------------------
@@ -468,10 +527,11 @@ class BaseNode:
async def _node_activity(context: Dict[str, Any]) -> Dict[str, Any]:
from datetime import datetime
from core.container import container
+ from services.status_broadcaster import get_status_broadcaster
node_id = context["node_id"]
workflow_id = context.get("workflow_id")
- broadcaster = container.status_broadcaster()
+ broadcaster = get_status_broadcaster()
# Pre-executed trigger nodes — return cached output without dispatching.
if context.get("pre_executed"):
diff --git a/server/services/plugin/credential.py b/server/services/plugin/credential.py
index 7323aaad..e6beee88 100644
--- a/server/services/plugin/credential.py
+++ b/server/services/plugin/credential.py
@@ -373,9 +373,18 @@ class OAuth2Credential(Credential):
auth_service = container.auth_service()
tokens = await auth_service.get_oauth_tokens(cls.id, user_id)
if not tokens or not tokens.get("access_token"):
- raise PermissionError(
+ # Annotate the exception so BaseNode.execute can surface the
+ # failing provider in the response envelope and emit a
+ # CloudEvents-typed broadcast (credential.oauth.runtime_failed)
+ # via broadcast_credential_event. Plain attribute assignment —
+ # no new exception class.
+ err = PermissionError(
f"No OAuth tokens for '{cls.id}'. Connect via Credentials modal."
)
+ err.provider = cls.id
+ err.reason = "missing"
+ err.auth = cls.auth # "oauth2"
+ raise err
return tokens
@classmethod
@@ -442,9 +451,13 @@ class ApiKeyCredential(Credential):
auth_service = container.auth_service()
api_key = await auth_service.get_api_key(cls.id)
if not api_key:
- raise PermissionError(
+ err = PermissionError(
f"No API key for '{cls.id}'. Add via Credentials modal."
)
+ err.provider = cls.id
+ err.reason = "missing"
+ err.auth = cls.auth # "api_key"
+ raise err
secrets: Dict[str, Any] = {"api_key": api_key}
for field in cls.extra_fields:
value = await auth_service.get_api_key(field)
diff --git a/server/services/temporal/agent_activities.py b/server/services/temporal/agent_activities.py
index f771ffb4..275d9265 100644
--- a/server/services/temporal/agent_activities.py
+++ b/server/services/temporal/agent_activities.py
@@ -99,15 +99,11 @@ async def execute_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
model = payload["model"]
api_key = payload["api_key"]
messages = payload.get("messages", [])
- tools_schemas = payload.get("tools", [])
+ tool_data = payload.get("tool_data", [])
temperature = payload.get("temperature", 0.7)
max_tokens = payload.get("max_tokens", 4096)
thinking_config = payload.get("thinking_config")
- # AIService is a DI singleton — pull it from the container so its
- # constructor dependencies (auth_service / database / cache / settings)
- # are wired correctly. Direct ``AIService()`` instantiation skips DI
- # and raises ``TypeError: missing 4 required positional arguments``.
ai_service = container.ai_service()
chat_model = ai_service.create_model(
@@ -119,73 +115,34 @@ async def execute_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
thinking=thinking_config,
)
- # Bind tools so the LLM sees their schemas. Tool schemas in the
- # payload are already serialised StructuredTool definitions — we
- # rebuild LangChain StructuredTool wrappers from them. The tools
- # themselves are NOT executed here; the workflow schedules them as
- # separate activities once the LLM emits tool_calls.
- if tools_schemas:
- from langchain_core.tools import StructuredTool
- from pydantic import create_model
-
- bound_tools: List[Any] = []
- for ts in tools_schemas:
- # Materialise a no-op StructuredTool — execution is deferred
- # to the workflow's tool activity dispatch.
- def _placeholder(**kwargs): # noqa: ARG001
- raise NotImplementedError("Tool is dispatched via Temporal activity")
-
- # Recreate a minimal Pydantic args schema. The real type
- # safety lives in the plugin's Params model; here we just
- # need names + descriptions for the LLM.
- args_schema = ts.get("args_schema") or {}
- fields = {
- k: (Any, v.get("description", "") if isinstance(v, dict) else "")
- for k, v in args_schema.get("properties", {}).items()
- }
- Args = create_model(f"{ts['name']}Args", **fields) if fields else None
-
- bound_tools.append(
- StructuredTool.from_function(
- func=_placeholder,
- name=ts["name"],
- description=ts.get("description", ""),
- args_schema=Args,
- )
- )
+ # Reuse the same tool-binding path execute_agent uses. The returned
+ # StructuredTool has a proper Pydantic args_schema every provider's
+ # bind_tools knows how to convert. The tool's callback is never
+ # invoked here — the workflow schedules per-type activities for each
+ # tool_call the model emits.
+ bound_tools: List[Any] = []
+ for tool_info in tool_data:
+ tool, _config = await ai_service._build_tool_from_node(tool_info)
+ if tool is not None:
+ bound_tools.append(tool)
+ if bound_tools:
chat_model = chat_model.bind_tools(bound_tools)
- # Reconstruct LangChain message objects from the workflow's dict
- # representation. Workflow state is serialisable JSON dicts; the
- # activity rehydrates them.
- from langchain_core.messages import (
- AIMessage,
- HumanMessage,
- SystemMessage,
- ToolMessage,
- )
-
- rehydrated = []
- for m in messages:
- role = m.get("role")
- content = m.get("content", "")
- if role == "system":
- rehydrated.append(SystemMessage(content=content))
- elif role == "user":
- rehydrated.append(HumanMessage(content=content))
- elif role == "assistant":
- ai = AIMessage(content=content)
- if m.get("tool_calls"):
- ai.tool_calls = m["tool_calls"]
- rehydrated.append(ai)
- elif role == "tool":
- rehydrated.append(
- ToolMessage(
- content=content,
- tool_call_id=m.get("tool_call_id", ""),
- name=m.get("name", ""),
- )
- )
+ # Workflow state is serialisable JSON dicts. Use LangChain's own
+ # ``messages_from_dict`` / ``messages_to_dict`` helpers so
+ # provider-specific metadata (Gemini ``thought_signature``,
+ # Anthropic cache fields, OpenAI ``reasoning_content``) survives
+ # the workflow ↔ activity round-trip. Manually constructing
+ # AIMessage(content=...) from a stripped dict loses these and
+ # blows up Gemini's ``Function call is missing a thought_signature``
+ # on the next turn.
+ from langchain_core.messages import messages_from_dict
+ from services.ai import filter_empty_messages
+
+ rehydrated = messages_from_dict(messages)
+ # Same filter the legacy create_agent_node runs (services/ai.py:775)
+ # — empty-content messages trigger 400s on Gemini/Anthropic.
+ rehydrated = filter_empty_messages(rehydrated)
activity.heartbeat("LLM step: invoking model")
response = await chat_model.ainvoke(rehydrated)
@@ -200,10 +157,17 @@ async def execute_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
if meta_usage:
usage = dict(meta_usage)
- # Tool calls → return them for the workflow to schedule.
+ # Serialise the full assistant message so the workflow can append
+ # it verbatim to its messages list (preserves thought_signature,
+ # cache metadata, etc.). The workflow extracts ``tool_calls`` from
+ # ``response.tool_calls`` separately for scheduling.
+ from langchain_core.messages import messages_to_dict
+ assistant_dict = messages_to_dict([response])[0]
+
if hasattr(response, "tool_calls") and response.tool_calls:
return {
"kind": "tool_calls",
+ "assistant_message": assistant_dict,
"calls": [
{
"id": tc.get("id", ""),
@@ -219,6 +183,7 @@ async def execute_llm_step(payload: Dict[str, Any]) -> Dict[str, Any]:
text, thinking = extract_thinking_from_response(response)
return {
"kind": "final",
+ "assistant_message": assistant_dict,
"content": text or "",
"thinking": thinking,
"usage": usage,
@@ -262,11 +227,8 @@ async def persist_agent_turn(payload: Dict[str, Any]) -> Dict[str, Any]:
params = await database.get_node_parameters(memory_node_id) or {}
current = params.get("memory_content", "")
- updated = append_to_memory_markdown(
- current,
- human_text=payload.get("human_text", ""),
- assistant_text=payload.get("assistant_text", ""),
- )
+ updated = append_to_memory_markdown(current, "human", payload.get("human_text", ""))
+ updated = append_to_memory_markdown(updated, "ai", payload.get("assistant_text", ""))
window_size = int(payload.get("window_size", 10))
trimmed_content, trimmed_pairs = trim_markdown_window(updated, window_size)
@@ -378,16 +340,65 @@ async def broadcast_agent_progress(payload: Dict[str, Any]) -> Dict[str, Any]:
from services.status_broadcaster import get_status_broadcaster
broadcaster = get_status_broadcaster()
+ node_id = payload["node_id"]
+ workflow_id = payload.get("workflow_id")
+ phase = payload.get("phase")
+
+ # Optional canvas-glow status update (raw-dict, same idiom F4.A's
+ # _node_activity wrapper uses). Lets the FE swap node colors on
+ # executing/success/error without a separate CloudEvents handler.
+ status = payload.get("status")
+ if status:
+ await broadcaster.update_node_status(
+ node_id,
+ status,
+ {"agent_type": "temporal", **({"phase": phase} if phase else {})},
+ workflow_id=workflow_id,
+ )
+
+ # CloudEvents v1.0 envelope (com.machinaos.agent.progress). Drives
+ # the iteration badge + phase indicator on the canvas.
await broadcaster.broadcast_agent_progress(
- payload["node_id"],
- workflow_id=payload.get("workflow_id"),
+ node_id,
+ workflow_id=workflow_id,
iteration=int(payload.get("iteration", 0)),
max_iterations=int(payload.get("max_iterations", 0)),
- phase=payload.get("phase"),
+ phase=phase,
)
return {"emitted": True}
[email protected](name="agent.store_output.v1")
+async def store_agent_output(payload: Dict[str, Any]) -> Dict[str, Any]:
+ """Persist the agent's final ``result`` dict via the existing
+ ``WorkflowService.store_node_output`` so ``ParameterResolver`` can
+ resolve ``{{aiAgent.response}}`` template references in downstream
+ nodes. The F4.A activity path stores via ``NodeExecutor``; F4.B
+ needs this dedicated activity because ``AgentWorkflow`` doesn't go
+ through ``WorkflowService.execute_node``.
+
+ ``payload`` shape::
+
+ {
+ "node_id": str,
+ "session_id": str,
+ "result": dict, # AgentWorkflow.run() return.result
+ }
+
+ Mirrors what ``NodeExecutor.execute`` writes for every output handle
+ (``output_main`` / ``output_top`` / ``output_0``).
+ """
+ from core.container import container
+
+ workflow_service = container.workflow_service()
+ node_id = payload["node_id"]
+ session_id = payload.get("session_id", "default")
+ data = payload.get("result") or {}
+ for output_name in ("output_main", "output_top", "output_0"):
+ await workflow_service.store_node_output(session_id, node_id, output_name, data)
+ return {"stored": True}
+
+
@activity.defn(name="agent.prepare_payload.v1")
async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
"""Resolve everything ``AgentWorkflow`` needs from the canvas + DB.
@@ -464,6 +475,17 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
db_params = await database.get_node_parameters(node_id) or {}
parameters = {**(context.get("node_data") or {}), **db_params}
+ # Resolve {{node.field}} template variables — same step NodeExecutor
+ # runs before dispatching to handlers in the legacy path. Without
+ # this the agent receives literal "{{chatTrigger.message}}" strings.
+ workflow_service = container.workflow_service()
+ nodes = context.get("nodes") or []
+ edges = context.get("edges") or []
+ if nodes and edges:
+ parameters = await workflow_service._param_resolver.resolve(
+ parameters, node_id, nodes, edges, session_id,
+ )
+
options = parameters.get("options") or {}
flattened = {**parameters, **options}
@@ -544,13 +566,20 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
memory_window_size = int(memory_data.get("window_size") or 10)
# ---- Tools ----------------------------------------------------------
- # Build LangChain StructuredTool per tool entry, then serialise its
- # args_schema to JSON Schema so the AgentWorkflow's LLM step can
- # rebuild a placeholder StructuredTool from it.
+ # We call ``ai_service._build_tool_from_node`` once here ONLY to
+ # extract the LLM-visible tool name (the workflow needs it to map
+ # ``tool_call.name`` back to a node_id when scheduling the per-type
+ # activity). The actual StructuredTool — with its proper Pydantic
+ # ``args_schema`` — gets rebuilt inside ``execute_llm_step`` against
+ # the same ``tool_info`` dict via the same helper. We never serialise
+ # the schema to JSON-Schema-and-back: that round-trip strips type
+ # info and the reconstructed ``(Any, default_string)`` placeholder
+ # blew up Gemini's ``convert_to_genai_function_declarations``
+ # (``properties.<field> Input should be a valid dictionary or object``).
tools_payload: List[Dict[str, Any]] = []
for tool_info in tool_data or []:
try:
- tool, config = await ai_service._build_tool_from_node(tool_info)
+ tool, _config = await ai_service._build_tool_from_node(tool_info)
except Exception as e: # noqa: BLE001 — defensive: skip a broken tool
activity.logger.warning(
f"prepare_payload: failed to build tool {tool_info.get('node_type')!r}: {e}"
@@ -564,28 +593,18 @@ async def prepare_agent_payload(context: Dict[str, Any]) -> Dict[str, Any]:
version = getattr(cls, "version", 1) if cls else 1
task_queue = getattr(cls, "task_queue", "machina-default") if cls else "machina-default"
- # Serialise args_schema to JSON Schema. StructuredTool.args_schema
- # is a Pydantic model; .model_json_schema() returns a dict the
- # LLM activity can use to bind a placeholder tool.
- args_schema_dict: Dict[str, Any] = {}
- try:
- if tool.args_schema is not None:
- args_schema_dict = tool.args_schema.model_json_schema()
- except Exception as e: # noqa: BLE001 — defensive
- activity.logger.debug(
- f"prepare_payload: failed to serialise args_schema for "
- f"{tool_info.get('node_type')!r}: {e}"
- )
-
tools_payload.append({
"name": tool.name,
- "description": tool.description or "",
- "args_schema": args_schema_dict,
"node_type": tool_info.get("node_type", ""),
"version": version,
"task_queue": task_queue,
"tool_node_id": tool_info.get("node_id", ""),
"parameters": tool_info.get("parameters") or {},
+ # Raw tool_info — what ``collect_agent_connections`` returned
+ # and what ``_build_tool_from_node`` accepts as input. Passed
+ # through the workflow verbatim so ``execute_llm_step`` can
+ # rebuild the real StructuredTool inside the activity.
+ "tool_info": tool_info,
})
# ---- Compaction threshold ------------------------------------------
@@ -653,4 +672,5 @@ def collect_agent_activities() -> List[Any]:
compact_agent_memory,
prepare_agent_payload,
broadcast_agent_progress,
+ store_agent_output,
]
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index c918676c..d3c8810b 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -129,16 +129,15 @@ class AgentWorkflow:
"temperature": float,
"system_message": str,
"user_prompt": str,
- "tools": [ # already-resolved tool schemas
+ "tools": [
{
"name": str, # LLM-facing name
"node_type": str, # plugin type for activity dispatch
"version": int, # plugin class version
- "description": str,
- "args_schema": dict,
+ "task_queue": str, # plugin task_queue (queue routing future)
"tool_node_id": str,
"parameters": dict, # plugin params from DB
- "task_queue": str, # plugin task_queue (queue routing future)
+ "tool_info": dict, # raw collect_agent_connections entry — passed to execute_llm_step which rebuilds the StructuredTool via ai_service._build_tool_from_node
},
],
"memory_node_id": Optional[str],
@@ -163,13 +162,16 @@ class AgentWorkflow:
retry_policy=AGENT_ACTIVITY_RETRY,
)
# ---- Build initial message list ---------------------------------
- # Workflow state is JSON dicts. Activities rehydrate LangChain
- # message objects from these dicts (see agent_activities.py).
+ # Workflow state is JSON dicts in LangChain's canonical shape
+ # ({"type": "<role>", "data": {"content": "...", ...}}) so the
+ # activity's ``messages_from_dict`` round-trips preserve every
+ # provider-specific field (Gemini ``thought_signature``,
+ # Anthropic cache markers, OpenAI reasoning content).
messages: List[Dict[str, Any]] = []
system = payload.get("system_message") or ""
if system:
- messages.append({"role": "system", "content": system})
+ messages.append({"type": "system", "data": {"content": system}})
# Pre-loaded memory becomes an additional system note. The actual
# parse / append happens in the persist_turn activity, but the
@@ -177,13 +179,13 @@ class AgentWorkflow:
memory_markdown = payload.get("memory_content") or ""
if memory_markdown:
messages.append({
- "role": "system",
- "content": f"## Prior conversation:\n{memory_markdown}",
+ "type": "system",
+ "data": {"content": f"## Prior conversation:\n{memory_markdown}"},
})
user_prompt = payload.get("user_prompt") or ""
if user_prompt:
- messages.append({"role": "user", "content": user_prompt})
+ messages.append({"type": "human", "data": {"content": user_prompt}})
# Map LLM tool name -> {node_type, version, task_queue, node_id,
# parameters} so the workflow can schedule the right activity
@@ -203,6 +205,16 @@ class AgentWorkflow:
agent_node_id = payload["node_id"]
agent_workflow_id = payload.get("workflow_id")
+ # Emit "executing" + phase="starting" via the existing
+ # broadcast_agent_progress activity (CloudEvents
+ # com.machinaos.agent.progress + raw-dict node_status for
+ # canvas glow). Mirrors what F4.A's _node_activity wrapper
+ # does for non-agent plugins.
+ await self._emit_phase(
+ agent_node_id, agent_workflow_id, 0, max_iterations,
+ phase="starting", status="executing",
+ )
+
# ---- Main loop --------------------------------------------------
for iteration in range(max_iterations):
workflow.logger.info(
@@ -214,33 +226,24 @@ class AgentWorkflow:
# legacy LangGraph path's super-step broadcast (RFC §6.4).
# FE consumes the typed envelope and updates the canvas
# node's "N / max" iteration badge live.
- await workflow.execute_activity(
- "agent.broadcast_progress.v1",
- args=[{
- "node_id": agent_node_id,
- "workflow_id": agent_workflow_id,
- "iteration": iteration,
- "max_iterations": max_iterations,
- "phase": "llm_step",
- }],
- start_to_close_timeout=PERSIST_TURN_TIMEOUT,
- retry_policy=AGENT_ACTIVITY_RETRY,
+ await self._emit_phase(
+ agent_node_id, agent_workflow_id, iteration, max_iterations,
+ phase="llm_step",
)
# Strip per-turn fields the activity doesn't need.
+ # Pass raw ``tool_info`` dicts through; the activity rebuilds
+ # the real StructuredTool via ``ai_service._build_tool_from_node``
+ # — the same helper the legacy agent path uses. We never
+ # serialise/deserialise the args_schema (that round-trip was
+ # the source of the Gemini ``properties.<field> Input should be
+ # a valid dictionary`` validation crash).
llm_payload = {
"provider": payload["provider"],
"model": payload["model"],
"api_key": payload["api_key"],
"messages": messages,
- "tools": [
- {
- "name": t["name"],
- "description": t.get("description", ""),
- "args_schema": t.get("args_schema", {}),
- }
- for t in tools
- ],
+ "tool_data": [t["tool_info"] for t in tools],
"system_message": system,
"temperature": payload.get("temperature", 0.7),
"max_tokens": payload.get("max_tokens", 4096),
@@ -269,10 +272,17 @@ class AgentWorkflow:
kind = step_result.get("kind")
+ # The activity returns the FULL serialized assistant message
+ # (LangChain's canonical {type, data} shape from messages_to_dict).
+ # Appending verbatim preserves Gemini thought_signature, Anthropic
+ # cache markers, OpenAI reasoning content — everything the next
+ # turn's request needs.
+ assistant_message = step_result.get("assistant_message")
+ if assistant_message:
+ messages.append(assistant_message)
+
if kind == "final":
- # Persist the final turn and exit.
final_content = step_result.get("content", "")
- messages.append({"role": "assistant", "content": final_content})
await self._persist_turn(
payload, human_text=user_prompt, assistant_text=final_content
)
@@ -288,14 +298,6 @@ class AgentWorkflow:
calls = step_result.get("calls") or []
workflow.logger.info(f"AgentWorkflow scheduling {len(calls)} tool call(s)")
- # Append the assistant turn with tool_calls before scheduling
- # so subsequent ToolMessage entries reference back to it.
- messages.append({
- "role": "assistant",
- "content": "",
- "tool_calls": calls,
- })
-
for call in calls:
tool_info = tool_index.get(call.get("name", ""))
if tool_info is None:
@@ -304,13 +306,15 @@ class AgentWorkflow:
"returning error to model"
)
messages.append({
- "role": "tool",
- "tool_call_id": call.get("id", ""),
- "name": call.get("name", ""),
- "content": (
- f"Error: tool {call.get('name')!r} is not "
- "connected to this agent."
- ),
+ "type": "tool",
+ "data": {
+ "content": (
+ f"Error: tool {call.get('name')!r} is not "
+ "connected to this agent."
+ ),
+ "tool_call_id": call.get("id", ""),
+ "name": call.get("name", ""),
+ },
})
continue
@@ -329,6 +333,12 @@ class AgentWorkflow:
f"node.{tool_info['node_type']}.v{tool_info['version']}"
)
+ await self._emit_phase(
+ agent_node_id, agent_workflow_id, iteration, max_iterations,
+ phase="executing_tool",
+ extra={"tool_name": call.get("name", ""), "tool_node_id": tool_info["tool_node_id"]},
+ )
+
try:
tool_result = await workflow.execute_activity(
tool_activity_name,
@@ -337,6 +347,11 @@ class AgentWorkflow:
heartbeat_timeout=TOOL_HEARTBEAT_TIMEOUT,
)
tool_content = _serialise_tool_result(tool_result)
+ await self._emit_phase(
+ agent_node_id, agent_workflow_id, iteration, max_iterations,
+ phase="tool_completed",
+ extra={"tool_name": call.get("name", "")},
+ )
except Exception as e: # noqa: BLE001 — Temporal handles retries
# After all retries exhausted, surface the error to
# the LLM (per user decision: LLM sees error and
@@ -349,10 +364,12 @@ class AgentWorkflow:
)
messages.append({
- "role": "tool",
- "tool_call_id": call.get("id", ""),
- "name": call.get("name", ""),
- "content": tool_content,
+ "type": "tool",
+ "data": {
+ "content": tool_content,
+ "tool_call_id": call.get("id", ""),
+ "name": call.get("name", ""),
+ },
})
# ---- Persist this turn (append-per-turn) -------------------
@@ -408,9 +425,9 @@ class AgentWorkflow:
# plus the last user prompt — same pattern
# ``CompactionService`` uses today in services/ai.py.
messages = [
- {"role": "system", "content": system},
- {"role": "system", "content": f"## Compacted summary:\n{summary}"},
- {"role": "user", "content": user_prompt},
+ {"type": "system", "data": {"content": system}},
+ {"type": "system", "data": {"content": f"## Compacted summary:\n{summary}"}},
+ {"type": "human", "data": {"content": user_prompt}},
]
memory_markdown = summary
usage_total = {}
@@ -425,19 +442,71 @@ class AgentWorkflow:
"the model did not produce a final response]"
)
- return {
- "success": True,
- "result": {
- "response": final_content,
- "thinking": thinking_accumulated or None,
- "model": payload.get("model"),
- "provider": payload.get("provider"),
- "usage": usage_total,
- },
+ result_payload = {
+ "response": final_content,
+ "thinking": thinking_accumulated or None,
+ "model": payload.get("model"),
+ "provider": payload.get("provider"),
+ "usage": usage_total,
}
+ # Persist the result to the OutputStore via the workflow_service
+ # so ParameterResolver can resolve {{aiAgent.response}} in
+ # downstream nodes. F4.A's activity wrapper does this via
+ # NodeExecutor; F4.B needs an explicit activity because we
+ # bypass NodeExecutor entirely.
+ await workflow.execute_activity(
+ "agent.store_output.v1",
+ args=[{
+ "node_id": agent_node_id,
+ "session_id": payload.get("session_id", "default"),
+ "result": result_payload,
+ }],
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+
+ # Final lifecycle broadcast — canvas glow goes green + FE
+ # consumers of com.machinaos.agent.progress see phase="completed".
+ await self._emit_phase(
+ agent_node_id, agent_workflow_id, max_iterations, max_iterations,
+ phase="completed", status="success",
+ )
+
+ return {"success": True, "result": result_payload}
+
# ---- Private helpers ------------------------------------------------
+ async def _emit_phase(
+ self,
+ node_id: str,
+ workflow_id: Optional[str],
+ iteration: int,
+ max_iterations: int,
+ *,
+ phase: str,
+ status: Optional[str] = None,
+ extra: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ """Schedule the ``agent.broadcast_progress.v1`` activity with a
+ single ``phase`` label. When ``status`` is set, the activity
+ also broadcasts a raw-dict node_status update so the canvas
+ glows accordingly (executing / success / error)."""
+ await workflow.execute_activity(
+ "agent.broadcast_progress.v1",
+ args=[{
+ "node_id": node_id,
+ "workflow_id": workflow_id,
+ "iteration": iteration,
+ "max_iterations": max_iterations,
+ "phase": phase,
+ **({"status": status} if status else {}),
+ **(extra or {}),
+ }],
+ start_to_close_timeout=PERSIST_TURN_TIMEOUT,
+ retry_policy=AGENT_ACTIVITY_RETRY,
+ )
+
async def _persist_turn(
self,
payload: Dict[str, Any],
@@ -474,14 +543,21 @@ class AgentWorkflow:
def _serialise_tool_result(result: Any) -> str:
"""Return a string body for a ``ToolMessage``.
- LangChain's ``ToolMessage.content`` expects a string. The plugin's
- activity returned a dict; serialise it as JSON. Falls back to
- ``str(result)`` if the dict isn't JSON-serialisable (rare).
+ Mirrors the legacy ``create_tool_node`` in ``services/ai.py``: feed
+ the LLM the handler's raw return value (``json.dumps(result,
+ default=str)``), NOT the Temporal activity envelope. The F4.A
+ per-type activity wraps the handler result as
+ ``{"success": bool, "result": {...}, "node_id": ..., "node_type": ...,
+ "timestamp": ...}``; we strip the envelope so the LLM doesn't see
+ infrastructure metadata.
"""
import json as _json
if isinstance(result, str):
return result
+ if isinstance(result, dict) and "result" in result and "success" in result:
+ # F4.A activity envelope — unwrap to match legacy tool_executor.
+ result = result.get("result", {})
try:
return _json.dumps(result, default=str)
except Exception: # noqa: BLE001 — defensive
diff --git a/server/tests/temporal/test_agent_workflow.py b/server/tests/temporal/test_agent_workflow.py
index 7258cd87..7b7a3760 100644
--- a/server/tests/temporal/test_agent_workflow.py
+++ b/server/tests/temporal/test_agent_workflow.py
@@ -67,7 +67,7 @@ class TestAgentActivities:
defn = getattr(compact_agent_memory, "__temporal_activity_definition")
assert defn.name == "agent.compact_memory.v1"
- def test_collect_returns_all_five(self):
+ def test_collect_returns_all_six(self):
"""Each successive sprint added one F4.B agent activity:
infra (3) → per-agent-wiring +prepare_payload (4) → CloudEvents
cleanup +broadcast_progress (5). All five must register so the
@@ -84,6 +84,7 @@ class TestAgentActivities:
"agent.execute_llm_step.v1",
"agent.persist_turn.v1",
"agent.prepare_payload.v1",
+ "agent.store_output.v1",
]
def test_prepare_payload_registered(self):