Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
Add Vertex managed-agent nodes (Gemini Enterprise Agent Platform)
trohitg0bc81d3111ca
diff --git a/client/src/assets/icons/index.ts b/client/src/assets/icons/index.tsindex 1977c53f..0a382307 100644--- a/client/src/assets/icons/index.ts+++ b/client/src/assets/icons/index.ts@@ -50,6 +50,8 @@ import Ollama from '@lobehub/icons/es/Ollama';import LmStudio from '@lobehub/icons/es/LmStudio';import Vercel from '@lobehub/icons/es/Vercel';import Github from '@lobehub/icons/es/Github';+import VertexAI from '@lobehub/icons/es/VertexAI';+import GoogleCloud from '@lobehub/icons/es/GoogleCloud';type RawSvg = string;@@ -156,6 +158,8 @@ const LOBEHUB_BRANDS: Readonly<Record<string, any>> = {lmstudio: LmStudio,vercel: Vercel,github: Github,+ vertexai: VertexAI,+ googlecloud: GoogleCloud,};const ICON_LIBRARIES: Readonly<Record<string, LibraryResolver>> = {diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.jsonindex 61f522a9..a0593388 100644--- a/server/config/node_allowlist.json+++ b/server/config/node_allowlist.json@@ -7,6 +7,9 @@"aiAgent","chatAgent",+ "vertex_managed_agent",+ "vertex_agent_admin",+ "vertexCloudTool","simpleMemory","masterSkill",diff --git a/server/constants.py b/server/constants.pyindex d12a0adb..89cb0cb4 100644--- a/server/constants.py+++ b/server/constants.py@@ -47,6 +47,7 @@ AI_AGENT_TYPES: FrozenSet[str] = frozenset("ai_employee","rlm_agent","claude_code_agent",+ "vertex_managed_agent",])diff --git a/server/nodes/agent/_vertex.py b/server/nodes/agent/_vertex.pynew file mode 100644index 00000000..51f6a3d2--- /dev/null+++ b/server/nodes/agent/_vertex.py@@ -0,0 +1,150 @@+"""Shared helpers for the Vertex managed-agent plugins.++Local to ``nodes/agent/`` — same convention as ``_handles.py``. Used by+``vertex_managed_agent`` (Interactions API) and ``vertex_agent_admin``+(Agents API lifecycle).++Auth model (verified live against the enterprise surface):++- ``AIza...`` Gemini API keys -> ``genai.Client(api_key=...)`` on+ generativelanguage.googleapis.com.+- Enterprise Agent Platform (aiplatform.googleapis.com) -> ``genai.Client(+ enterprise=True, project=<id>, location="global")`` with Application+ Default Credentials (``gcloud auth application-default login``). ``AQ.``+ Vertex Express keys do NOT work on the interactions surface (the SDK+ builds an unprojected URL and 404s), so a project id is required there.++The enterprise surface also requires ``background=True`` on agent+interactions ("Agent interactions must set background to true."), so+:func:`create_interaction_and_wait` always creates in background mode and+polls ``interactions.get`` to a terminal status.+"""++from __future__ import annotations++import asyncio+from typing import Any, Awaitable, Callable, Optional++from core.logging import get_logger+from services.plugin import NodeUserError++logger = get_logger(__name__)++DEFAULT_MANAGED_AGENT = "antigravity-preview-05-2026"+DEFAULT_LOCATION = "global"++# Interaction statuses that stop the background poll loop.+# "requires_action" is terminal for a single create: the caller decides+# whether to answer pending function calls with a follow-up create.+TERMINAL_STATUSES = frozenset(+ {+ "completed",+ "failed",+ "cancelled",+ "incomplete",+ "budget_exceeded",+ "requires_action",+ }+)++_POLL_INTERVAL_SECONDS = 3.0+++def is_genai_error(exc: BaseException) -> bool:+ """True for any google-genai SDK error, across its two hierarchies.++ The models/agents surfaces raise ``google.genai.errors.APIError``+ while the interactions sub-client raises an OpenAI-style hierarchy+ from a private module — a module-name check covers both without+ importing private paths.+ """+ return type(exc).__module__.startswith("google.genai")+++def raise_as_user_error(exc: Exception, *, what: str) -> None:+ """Re-raise a google-genai SDK error as a user-correctable failure."""+ if not is_genai_error(exc):+ raise exc+ detail = str(exc).replace("\n", " ")+ if len(detail) > 400:+ detail = detail[:400] + "..."+ raise NodeUserError(f"{what} failed: {detail}") from exc+++def is_expired_environment_error(exc: BaseException) -> bool:+ """Heuristic for a stale environment/interaction chain (7-day TTL)."""+ if not is_genai_error(exc):+ return False+ text = str(exc).lower()+ return ("environment" in text or "interaction" in text) and (+ "not found" in text or "expired" in text or "invalid" in text+ )+++def build_genai_client(api_key: str, project_id: str, location: str = DEFAULT_LOCATION):+ """Build the google-genai client for the managed-agent surfaces."""+ from google import genai++ if project_id:+ # Enterprise Agent Platform surface — ADC auth (gcloud).+ return genai.Client(+ enterprise=True,+ project=project_id,+ location=location or DEFAULT_LOCATION,+ )+ if api_key.startswith("AIza"):+ return genai.Client(api_key=api_key)+ raise NodeUserError(+ "Vertex managed agents need either a GCP Project ID (uses gcloud "+ "Application Default Credentials on the Agent Platform surface) or "+ "a stored Gemini API key starting with 'AIza'. Vertex Express "+ "'AQ.' keys are not supported by the Interactions API."+ )+++def resolve_api_key_from_context(raw_context: dict) -> str:+ """Recover the auto-injected gemini key from the raw params.++ ``node_executor._inject_api_keys`` writes ``api_key`` into the raw+ params dict before Pydantic validation strips it. Only prefixes the+ gemini credential can produce are trusted — the injector falls back+ to provider "openai" when saved params lack ``provider``.+ """+ raw_params = (raw_context or {}).get("_raw_parameters") or {}+ key = raw_params.get("api_key") or ""+ if isinstance(key, str) and key.startswith(("AIza", "AQ.")):+ return key+ return ""+++async def resolve_gemini_api_key_from_store() -> str:+ """Fetch the stored gemini credential for nodes outside AI_MODEL_TYPES.++ ``vertex_agent_admin`` is not an agent/model type, so+ ``_inject_api_keys`` never runs for it — read the credential store+ directly (same path the delegation injector uses).+ """+ from services.plugin.deps import get_ai_service++ try:+ key = await get_ai_service().auth.get_api_key("gemini", "default")+ except Exception: # noqa: BLE001 — missing key is handled by the caller+ return ""+ return key or ""+++async def create_interaction_and_wait(+ client: Any,+ *,+ on_poll: Optional[Callable[[], Awaitable[None]]] = None,+ poll_interval: float = _POLL_INTERVAL_SECONDS,+ **kwargs: Any,+) -> Any:+ """Create a background interaction and poll it to a terminal status."""+ interaction = await client.aio.interactions.create(background=True, **kwargs)+ while getattr(interaction, "status", None) not in TERMINAL_STATUSES:+ await asyncio.sleep(poll_interval)+ if on_poll is not None:+ await on_poll()+ interaction = await client.aio.interactions.get(interaction.id)+ return interactiondiff --git a/server/nodes/agent/vertex_agent_admin/__init__.py b/server/nodes/agent/vertex_agent_admin/__init__.pynew file mode 100644index 00000000..885da74e--- /dev/null+++ b/server/nodes/agent/vertex_agent_admin/__init__.py@@ -0,0 +1,214 @@+"""Vertex Agent Admin — managed-agent lifecycle (Agents API).++Create / list / get / delete custom managed agents on the Gemini+Enterprise Agent Platform. Custom agents build on the prebuilt+Antigravity base agent with their own system instruction and built-in+tool set; run them with the ``vertex_managed_agent`` node by putting+the custom agent id in its ``agent`` parameter.++Agent creation is a long-running operation (~2-3 minutes the first+time, seconds afterwards) — the Python SDK blocks until it resolves.+"""++from __future__ import annotations++from datetime import datetime+from typing import Any, Dict, List, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field++from core.logging import get_logger+from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue++from .._vertex import (+ DEFAULT_LOCATION,+ DEFAULT_MANAGED_AGENT,+ build_genai_client,+ raise_as_user_error,+ resolve_gemini_api_key_from_store,+)++logger = get_logger(__name__)++_CREATE_ONLY = {"displayOptions": {"show": {"operation": ["create"]}}}+_NEEDS_AGENT_ID = {"displayOptions": {"show": {"operation": ["create", "get", "delete"]}}}+++class VertexAgentAdminParams(BaseModel):+ operation: Literal["create", "list", "get", "delete"] = "list"+ project_id: str = Field(+ default="",+ description=(+ "GCP project id (auth via gcloud Application Default "+ "Credentials). Leave empty to use a stored 'AIza' Gemini key."+ ),+ json_schema_extra={"placeholder": "my-gcp-project"},+ )+ agent_id: Optional[str] = Field(+ default=None,+ description="Custom agent id (lowercase letters, numbers, hyphens).",+ json_schema_extra=_NEEDS_AGENT_ID,+ )++ # Create fields+ description: Optional[str] = Field(default=None, json_schema_extra=_CREATE_ONLY)+ system_instruction: Optional[str] = Field(+ default=None,+ json_schema_extra={**_CREATE_ONLY, "rows": 3},+ )+ base_agent: str = Field(default=DEFAULT_MANAGED_AGENT, json_schema_extra=_CREATE_ONLY)+ tools: List[Literal["code_execution", "filesystem", "google_search", "url_context"]] = Field(+ default_factory=lambda: ["code_execution"],+ description="Built-in cloud tools the custom agent may use.",+ json_schema_extra=_CREATE_ONLY,+ )++ location: str = Field(+ default=DEFAULT_LOCATION,+ json_schema_extra={"group": "options"},+ )++ model_config = ConfigDict(+ extra="ignore",+ json_schema_extra={+ "groups": {+ "options": {+ "display_name": "Options",+ "placeholder": "Add Option",+ },+ },+ },+ )+++class VertexAgentAdminOutput(BaseModel):+ operation: Optional[str] = None+ agent: Optional[Dict[str, Any]] = None+ agents: Optional[List[Dict[str, Any]]] = None+ count: Optional[int] = None+ deleted: Optional[bool] = None+ timestamp: Optional[str] = None++ model_config = ConfigDict(extra="allow")+++def _agent_to_dict(agent: Any) -> Dict[str, Any]:+ if hasattr(agent, "model_dump"):+ return agent.model_dump(mode="json", exclude_none=True)+ if isinstance(agent, dict):+ return agent+ return {"id": str(agent)}+++class VertexAgentAdminNode(ActionNode):+ type = "vertex_agent_admin"+ display_name = "Vertex Agent Admin"+ subtitle = "Agent Lifecycle"+ group = ("tool",)+ description = (+ "Create, list, inspect, and delete custom managed agents on the "+ "Gemini Enterprise Agent Platform."+ )+ component_kind = "square"+ # Lifecycle CRUD (incl. delete) is operator-facing, not LLM-callable.+ usable_as_tool = False+ handles = (+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},+ )+ annotations = {"destructive": True, "readonly": False, "open_world": True}+ task_queue = TaskQueue.REST_API++ Params = VertexAgentAdminParams+ Output = VertexAgentAdminOutput++ async def _client(self, params: VertexAgentAdminParams) -> Any:+ api_key = "" if params.project_id else await resolve_gemini_api_key_from_store()+ return build_genai_client(api_key, params.project_id, params.location)++ @staticmethod+ def _require_agent_id(params: VertexAgentAdminParams) -> str:+ agent_id = (params.agent_id or "").strip()+ if not agent_id:+ raise NodeUserError(+ f"vertex_agent_admin: '{params.operation}' needs an agent_id."+ )+ return agent_id++ @Operation("create", cost={"service": "vertex_agent", "action": "create", "count": 1})+ async def create_op(self, ctx: NodeContext, params: VertexAgentAdminParams) -> Any:+ from services.status_broadcaster import get_status_broadcaster++ agent_id = self._require_agent_id(params)+ client = await self._client(params)+ await get_status_broadcaster().update_node_status(+ ctx.node_id,+ "executing",+ {"message": f"Creating agent '{agent_id}' (first create takes ~2-3 min)..."},+ workflow_id=ctx.workflow_id,+ )+ kwargs: Dict[str, Any] = {+ "id": agent_id,+ "base_agent": params.base_agent or DEFAULT_MANAGED_AGENT,+ "tools": [{"type": tool} for tool in params.tools],+ }+ if params.description:+ kwargs["description"] = params.description+ if params.system_instruction:+ kwargs["system_instruction"] = params.system_instruction+ try:+ agent = await client.aio.agents.create(**kwargs)+ except Exception as exc: # noqa: BLE001 — mapped below+ raise_as_user_error(exc, what=f"Agent create '{agent_id}'")+ return {+ "operation": "create",+ "agent": _agent_to_dict(agent),+ "timestamp": datetime.now().isoformat(),+ }++ @Operation("list", cost={"service": "vertex_agent", "action": "list", "count": 1})+ async def list_op(self, ctx: NodeContext, params: VertexAgentAdminParams) -> Any:+ client = await self._client(params)+ try:+ response = await client.aio.agents.list()+ except Exception as exc: # noqa: BLE001 — mapped below+ raise_as_user_error(exc, what="Agent list")+ items = getattr(response, "agents", None) or (+ list(response) if not isinstance(response, dict) else []+ )+ agents = [_agent_to_dict(agent) for agent in (items or [])]+ return {+ "operation": "list",+ "agents": agents,+ "count": len(agents),+ "timestamp": datetime.now().isoformat(),+ }++ @Operation("get", cost={"service": "vertex_agent", "action": "get", "count": 1})+ async def get_op(self, ctx: NodeContext, params: VertexAgentAdminParams) -> Any:+ agent_id = self._require_agent_id(params)+ client = await self._client(params)+ try:+ agent = await client.aio.agents.get(id=agent_id)+ except Exception as exc: # noqa: BLE001 — mapped below+ raise_as_user_error(exc, what=f"Agent get '{agent_id}'")+ return {+ "operation": "get",+ "agent": _agent_to_dict(agent),+ "timestamp": datetime.now().isoformat(),+ }++ @Operation("delete", cost={"service": "vertex_agent", "action": "delete", "count": 1})+ async def delete_op(self, ctx: NodeContext, params: VertexAgentAdminParams) -> Any:+ agent_id = self._require_agent_id(params)+ client = await self._client(params)+ try:+ await client.aio.agents.delete(id=agent_id)+ except Exception as exc: # noqa: BLE001 — mapped below+ raise_as_user_error(exc, what=f"Agent delete '{agent_id}'")+ return {+ "operation": "delete",+ "deleted": True,+ "agent": {"id": agent_id},+ "timestamp": datetime.now().isoformat(),+ }diff --git a/server/nodes/agent/vertex_agent_admin/meta.json b/server/nodes/agent/vertex_agent_admin/meta.jsonnew file mode 100644index 00000000..c27f75aa--- /dev/null+++ b/server/nodes/agent/vertex_agent_admin/meta.json@@ -0,0 +1,3 @@+{+ "color": "#669DF6"+}diff --git a/server/nodes/agent/vertex_cloud_tool/__init__.py b/server/nodes/agent/vertex_cloud_tool/__init__.pynew file mode 100644index 00000000..2bc3c3c7--- /dev/null+++ b/server/nodes/agent/vertex_cloud_tool/__init__.py@@ -0,0 +1,46 @@+"""Vertex Cloud Tool — display-only canvas node.++Minted dynamically by ``vertex_managed_agent`` (see its ``_ops.py``) to+show which cloud-side tools the managed agent used during a run+(sandbox commands, Google Search, URL context, ...). The managed agent+runs entirely in Google's cloud, so these nodes are the canvas-visible+trace of that remote activity: one node per distinct tool, pulsed+executing->success after each turn that used it.++Pure display: default ``_EmptyParams`` / ``_EmptyOutput`` and no+``@Operation`` (the plugin contract explicitly exempts pure-display+plugins). It is never scheduled by the executor — nodes wired to an+agent's ``input-tools`` handle are excluded as sub-nodes.+"""++from __future__ import annotations++from services.plugin import ActionNode+++class VertexCloudToolNode(ActionNode):+ type = "vertexCloudTool"+ display_name = "Cloud Tool"+ subtitle = "Vertex Activity"+ group = ("tool",)+ description = (+ "Shows a cloud-side tool the Vertex managed agent used. Created "+ "automatically; safe to delete."+ )+ # "square" (not "tool"): renders identically via SquareNode but skips+ # the ToolSchemaEditor panel — there is no schema to edit on a+ # display-only node. group=("tool",) still auto-derives isConfigNode.+ component_kind = "square"+ ui_hints = {"hideRunButton": True}+ # Never expose to LLMs as a callable tool — it has no behavior.+ usable_as_tool = False+ handles = (+ {+ "name": "output-main",+ "kind": "output",+ "position": "right",+ "label": "Tool",+ "role": "tools",+ },+ )+ annotations = {"destructive": False, "readonly": True, "open_world": False}diff --git a/server/nodes/agent/vertex_cloud_tool/meta.json b/server/nodes/agent/vertex_cloud_tool/meta.jsonnew file mode 100644index 00000000..a501568d--- /dev/null+++ b/server/nodes/agent/vertex_cloud_tool/meta.json@@ -0,0 +1,3 @@+{+ "color": "#34A853"+}diff --git a/server/nodes/agent/vertex_managed_agent/__init__.py b/server/nodes/agent/vertex_managed_agent/__init__.pynew file mode 100644index 00000000..6a3ee864--- /dev/null+++ b/server/nodes/agent/vertex_managed_agent/__init__.py@@ -0,0 +1,578 @@+"""Vertex Managed Agent — Google Gemini Enterprise Agent Platform.++Runs a cloud-hosted managed agent (default: Antigravity) through the+Interactions API and bridges the MachinaOS canvas into it:++- Connected tool nodes are declared as custom ``function`` tools; the+ cloud agent hands control back with ``status == "requires_action"``+ and the pending calls are dispatched through the standard+ ``execute_tool`` path (so tool nodes glow exactly like they do for+ the local aiAgent loop), then answered via ``function_result`` inputs+ on a chained follow-up create.+- Conversation + sandbox continuity rides the connected simpleMemory+ node: ``vertex_interaction_id`` / ``vertex_environment_id`` are stored+ in its params and the turn is appended to ``memory_content``.+- Cloud-side tool usage (sandbox commands, google_search, ...) is+ surfaced post-turn as dynamic ``vertexCloudTool`` canvas nodes via the+ workflow-ops protocol (agentBuilder pattern) — see ``_ops.py``.++No SSE streaming in v1: the enterprise surface requires background+interactions, so each turn is create(background=True) + poll.+"""++from __future__ import annotations++import time+from datetime import datetime+from typing import Any, Dict, List, Literal, Optional, Tuple++from pydantic import BaseModel, ConfigDict, Field++from core.logging import get_logger+from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue+from services.plugin.edge_walker import collect_agent_connections+from services.plugin.scaling import AI_START_TO_CLOSE++from .._handles import STD_AGENT_HINTS, std_agent_handles+from .._vertex import (+ DEFAULT_LOCATION,+ DEFAULT_MANAGED_AGENT,+ build_genai_client,+ create_interaction_and_wait,+ is_expired_environment_error,+ raise_as_user_error,+ resolve_api_key_from_context,+)++logger = get_logger(__name__)++# Cloud-side step types surfaced as dynamic canvas nodes. The enterprise+# surface also reports sandbox activity as function_call steps whose+# names were never declared by us (e.g. run_command) — those are keyed+# by name. provision_sandbox is infrastructure noise, not a tool.+_CLOUD_STEP_LABELS = {+ "code_execution_call": "Code Execution",+ "google_search_call": "Google Search",+ "url_context_call": "URL Context",+ "mcp_server_tool_call": "MCP Tool",+}+_CLOUD_NOISE_NAMES = frozenset({"provision_sandbox"})+++class VertexManagedAgentParams(BaseModel):+ """Managed-agent tuning surface (aiAgent-parity minimal).++ ``api_key`` is intentionally NOT a field — the gemini credential is+ auto-injected by ``node_executor._inject_api_keys`` and recovered+ from ``_raw_parameters`` (same convention as the other agents).+ """++ prompt: str = Field(+ default="",+ json_schema_extra={+ "placeholder": "Enter your prompt or use template variables...",+ "rows": 4,+ },+ )+ agent: str = Field(+ default=DEFAULT_MANAGED_AGENT,+ description=(+ "Managed agent to run: the prebuilt Antigravity agent or a "+ "custom agent id created via the Vertex Agent Admin node."+ ),+ )+ project_id: str = Field(+ default="",+ description=(+ "GCP project id for the Agent Platform surface (auth via "+ "gcloud Application Default Credentials). Leave empty to use "+ "a stored 'AIza' Gemini API key instead."+ ),+ json_schema_extra={"placeholder": "my-gcp-project"},+ )+ # Single-valued on purpose: keeps detect_ai_provider/_inject_api_keys+ # resolving the gemini credential for this node type.+ provider: Literal["gemini"] = "gemini"++ # ---- "Options" group (collapsed by default) ----+ system_instruction: Optional[str] = Field(+ default=None,+ json_schema_extra={"rows": 3, "group": "options"},+ )+ location: str = Field(+ default=DEFAULT_LOCATION,+ json_schema_extra={"group": "options"},+ )+ max_turns: int = Field(+ default=25,+ ge=1,+ le=100,+ description="Cap on requires_action tool round-trips per run.",+ json_schema_extra={"group": "options"},+ )+ visualize_cloud_tools: bool = Field(+ default=True,+ description=(+ "Mint canvas nodes showing which cloud-side tools the "+ "managed agent used (sandbox commands, search, ...)."+ ),+ json_schema_extra={"group": "options"},+ )++ model_config = ConfigDict(+ extra="ignore",+ json_schema_extra={+ "groups": {+ "options": {+ "display_name": "Options",+ "placeholder": "Add Option",+ },+ },+ },+ )+++class VertexManagedAgentOutput(BaseModel):+ response: Optional[str] = None+ interaction_id: Optional[str] = None+ environment_id: Optional[str] = None+ status: Optional[str] = None+ agent: Optional[str] = None+ provider: str = "gemini"+ turns: Optional[int] = None+ cloud_tools_used: Optional[List[str]] = None+ usage: Optional[Dict[str, Any]] = None+ timestamp: Optional[str] = None++ model_config = ConfigDict(extra="allow")+++class VertexManagedAgentNode(ActionNode):+ type = "vertex_managed_agent"+ display_name = "Vertex Agent"+ subtitle = "Managed Agent"+ group = ("agent",)+ description = (+ "Google cloud-hosted managed agent (Antigravity) with sandboxed "+ "code execution. Bridges connected tool nodes into the cloud via "+ "function calling and shows cloud tool usage on the canvas."+ )+ component_kind = "agent"+ tool_name = "delegate_to_vertex_managed_agent"+ handles = std_agent_handles()+ ui_hints = STD_AGENT_HINTS+ annotations = {"destructive": False, "readonly": False, "open_world": True}+ task_queue = TaskQueue.AI_HEAVY+ # 30m: managed-agent sandbox turns (provision + code execution ++ # multi-round tool bridging) routinely exceed the 10m action default.+ start_to_close_timeout = AI_START_TO_CLOSE+ # Canvas nodes/edges must reach ctx under Temporal per-tool dispatch+ # (tool discovery + workflow-ops minting are canvas-aware).+ needs_canvas = True++ Params = VertexManagedAgentParams+ Output = VertexManagedAgentOutput++ @Operation(+ "execute",+ cost={"service": "vertex_agent", "action": "interact", "count": 1},+ )+ async def execute_op(+ self,+ ctx: NodeContext,+ params: VertexManagedAgentParams,+ ) -> Any:+ from services.plugin.deps import get_database+ from services.status_broadcaster import get_status_broadcaster++ start_time = time.time()+ broadcaster = get_status_broadcaster()+ database = get_database()+ node_id = ctx.node_id+ workflow_id = ctx.workflow_id++ async def phase(name: str, **details: Any) -> None:+ await broadcaster.update_node_status(+ node_id,+ "executing",+ {"phase": name, "agent_type": "vertex_managed", **details},+ workflow_id=workflow_id,+ )++ await phase("initializing", message="Starting Vertex managed agent...")++ memory_data, _, tool_data, input_data, _ = await collect_agent_connections(+ node_id, ctx.raw, database, log_prefix="[Vertex Agent]"+ )++ prompt = params.prompt or self._prompt_from_input(input_data)+ if not prompt:+ raise NodeUserError(+ "vertex_managed_agent: provide a prompt or connect an "+ "input node that produced a message."+ )++ api_key = resolve_api_key_from_context(ctx.raw)+ client = build_genai_client(api_key, params.project_id, params.location)++ # ---- tool bridge: connected tool nodes -> function declarations+ await phase("building_tools")+ declared_tools, tool_configs = await self._build_function_tools(tool_data)++ # ---- memory bridge: interaction/environment chain ids+ prev_interaction_id: Optional[str] = None+ environment: Any = "remote"+ memory_node_id = (memory_data or {}).get("node_id")+ if memory_node_id:+ await phase("loading_memory")+ mem_params = await database.get_node_parameters(memory_node_id) or {}+ prev_interaction_id = mem_params.get("vertex_interaction_id") or None+ environment = mem_params.get("vertex_environment_id") or "remote"++ create_kwargs: Dict[str, Any] = {+ "agent": params.agent,+ "store": True,+ }+ if params.system_instruction:+ create_kwargs["system_instruction"] = params.system_instruction+ if declared_tools:+ create_kwargs["tools"] = declared_tools++ async def run_turn(**kw: Any) -> Any:+ try:+ return await create_interaction_and_wait(client, **create_kwargs, **kw)+ except Exception as exc: # noqa: BLE001 — mapped below+ raise_as_user_error(exc, what="Vertex managed agent interaction")++ # ---- turn 1 (with one stale-chain retry)+ await phase("invoking_llm", message=f"Calling {params.agent}...")+ turn = 1+ await broadcaster.broadcast_agent_progress(+ node_id, workflow_id=workflow_id, iteration=turn, max_iterations=params.max_turns+ )+ try:+ interaction = await run_turn(+ input=prompt,+ environment=environment,+ **({"previous_interaction_id": prev_interaction_id} if prev_interaction_id else {}),+ )+ except NodeUserError as exc:+ cause = exc.__cause__+ if prev_interaction_id and cause is not None and is_expired_environment_error(cause):+ logger.warning(+ "[Vertex Agent] stale interaction chain for %s — retrying fresh", node_id+ )+ if memory_node_id:+ await self._save_chain_ids(database, memory_node_id, None, None)+ prev_interaction_id = None+ interaction = await run_turn(input=prompt, environment="remote")+ else:+ raise++ # ---- requires_action loop: answer pending local function calls+ while (+ getattr(interaction, "status", None) == "requires_action"+ and turn < params.max_turns+ ):+ results = self._pending_function_results_needed(interaction, tool_configs)+ if not results:+ logger.warning(+ "[Vertex Agent] requires_action with no answerable "+ "function calls (node=%s) — stopping",+ node_id,+ )+ break+ function_results = []+ for call in results:+ await phase("executing_tool", tool_name=call["name"])+ function_results.append(+ await self._execute_bridged_call(call, tool_configs, ctx)+ )+ turn += 1+ await broadcaster.broadcast_agent_progress(+ node_id, workflow_id=workflow_id, iteration=turn, max_iterations=params.max_turns+ )+ interaction = await run_turn(+ input=function_results,+ previous_interaction_id=interaction.id,+ environment=getattr(interaction, "environment_id", None) or environment,+ )++ response_text = getattr(interaction, "output_text", None) or ""+ status = getattr(interaction, "status", None)+ environment_id = getattr(interaction, "environment_id", None)+ usage = self._usage_dict(interaction)++ # ---- cloud tool visualization (post-turn, from steps)+ cloud_tools = self._collect_cloud_tool_usage(interaction, tool_configs)+ if cloud_tools and params.visualize_cloud_tools and workflow_id:+ from ._ops import ensure_cloud_tool_nodes++ try:+ await ensure_cloud_tool_nodes(+ workflow_id=workflow_id,+ agent_node_id=node_id,+ used=cloud_tools,+ )+ except Exception: # noqa: BLE001 — visualization is best-effort+ logger.exception("[Vertex Agent] cloud-tool minting failed")++ # ---- memory persist+ if memory_node_id:+ await phase("saving_memory")+ await self._save_chain_ids(+ database,+ memory_node_id,+ getattr(interaction, "id", None),+ environment_id,+ human=prompt,+ assistant=response_text,+ window_size=int((memory_data or {}).get("window_size") or 10),+ )++ # ---- usage bookkeeping (tokens billed by Google; recorded for stats)+ try:+ await database.save_api_usage_metric(+ {+ "session_id": ctx.raw.get("session_id", "default"),+ "node_id": node_id,+ "workflow_id": workflow_id,+ "service": "vertex_agent",+ "operation": "interaction",+ "endpoint": "interactions.create",+ "resource_count": int((usage or {}).get("total_tokens") or 1),+ "cost": 0.0,+ }+ )+ except Exception: # noqa: BLE001 — metrics are best-effort+ logger.exception("[Vertex Agent] usage metric save failed")++ success = status == "completed"+ await broadcaster.update_node_status(+ node_id,+ "success" if success else "warning",+ {+ "message": f"Vertex agent {status} in {turn} turn(s)",+ "status": status,+ "turns": turn,+ },+ workflow_id=workflow_id,+ )+ logger.info(+ "[Vertex Agent] node=%s status=%s turns=%d elapsed=%.1fs",+ node_id,+ status,+ turn,+ time.time() - start_time,+ )++ return {+ "response": response_text,+ "interaction_id": getattr(interaction, "id", None),+ "environment_id": environment_id,+ "status": status,+ "agent": params.agent,+ "provider": "gemini",+ "turns": turn,+ "cloud_tools_used": sorted(cloud_tools.values()) or None,+ "usage": usage,+ "timestamp": datetime.now().isoformat(),+ }++ # ------------------------------------------------------------------+ # helpers+ # ------------------------------------------------------------------++ @staticmethod+ def _prompt_from_input(input_data: Any) -> str:+ if isinstance(input_data, dict):+ for key in ("message", "text", "content"):+ value = input_data.get(key)+ if value:+ return str(value)+ return str(input_data) if input_data else ""+ return str(input_data) if input_data else ""++ @staticmethod+ async def _build_function_tools(+ tool_data: List[Dict[str, Any]],+ ) -> Tuple[List[Dict[str, Any]], Dict[str, Dict[str, Any]]]:+ """Convert connected tool nodes into Interactions function tools.++ Reuses ``AIService._build_tool_from_node`` so DB ToolSchema+ overrides, plugin ClassVar names, and the delegation schema gate+ all apply exactly as they do for the local agent loop.+ """+ if not tool_data:+ return [], {}+ from services.plugin.deps import get_ai_service++ ai_service = get_ai_service()+ declared: List[Dict[str, Any]] = []+ configs: Dict[str, Dict[str, Any]] = {}+ for tool_info in tool_data:+ structured, config = await ai_service._build_tool_from_node(tool_info)+ if structured is None:+ continue+ if structured.args_schema is not None:+ schema = structured.args_schema.model_json_schema()+ else:+ schema = {"type": "object", "properties": {}}+ # Function-calling APIs reject schema indirection; the plugin+ # contract already forbids $defs in tool Params schemas.+ schema.pop("$defs", None)+ schema.pop("definitions", None)+ declared.append(+ {+ "type": "function",+ "name": structured.name,+ "description": structured.description or structured.name,+ "parameters": schema,+ }+ )+ configs[structured.name] = config or {}+ return declared, configs++ @staticmethod+ def _pending_function_results_needed(+ interaction: Any,+ tool_configs: Dict[str, Dict[str, Any]],+ ) -> List[Dict[str, Any]]:+ """Function calls we declared that have no matching result yet.++ Cloud-internal calls (sandbox provisioning, run_command, ...)+ also surface as function_call steps but are answered server-side+ — only names we declared are ours to execute.+ """+ steps = list(getattr(interaction, "steps", None) or [])+ answered = {+ getattr(step, "call_id", None)+ for step in steps+ if getattr(step, "type", "") == "function_result"+ }+ pending = []+ for step in steps:+ if getattr(step, "type", "") != "function_call":+ continue+ name = getattr(step, "name", "") or ""+ if name not in tool_configs:+ continue+ call_id = getattr(step, "id", None)+ if call_id in answered:+ continue+ pending.append(+ {+ "name": name,+ "call_id": call_id,+ "arguments": getattr(step, "arguments", None) or {},+ }+ )+ return pending++ @staticmethod+ async def _execute_bridged_call(+ call: Dict[str, Any],+ tool_configs: Dict[str, Dict[str, Any]],+ ctx: NodeContext,+ ) -> Dict[str, Any]:+ """Dispatch one bridged function call through execute_tool."""+ from pydantic_core import to_jsonable_python++ from services.handlers.tools import execute_tool+ from services.plugin.deps import get_ai_service, get_database++ config = dict(tool_configs.get(call["name"], {}))+ config["workflow_id"] = ctx.workflow_id+ config["parent_node_id"] = ctx.node_id+ config["ai_service"] = get_ai_service()+ config["database"] = get_database()+ for key in ("nodes", "edges", "workspace_dir", "execution_id"):+ if ctx.raw.get(key) is not None:+ config[key] = ctx.raw[key]++ try:+ result = await execute_tool(call["name"], dict(call["arguments"]), config)+ return {+ "type": "function_result",+ "name": call["name"],+ "call_id": call["call_id"],+ "result": to_jsonable_python(result),+ }+ except Exception as exc: # noqa: BLE001 — surfaced to the cloud agent+ logger.warning(+ "[Vertex Agent] bridged tool %s failed: %s", call["name"], exc+ )+ return {+ "type": "function_result",+ "name": call["name"],+ "call_id": call["call_id"],+ "result": {"error": str(exc)},+ "is_error": True,+ }++ @staticmethod+ def _collect_cloud_tool_usage(+ interaction: Any,+ tool_configs: Dict[str, Dict[str, Any]],+ ) -> Dict[str, str]:+ """Map of cloud_tool_key -> display label from the turn's steps."""+ used: Dict[str, str] = {}+ for step in getattr(interaction, "steps", None) or []:+ step_type = getattr(step, "type", "") or ""+ if step_type in _CLOUD_STEP_LABELS:+ used[f"type:{step_type}"] = _CLOUD_STEP_LABELS[step_type]+ continue+ if step_type == "function_call":+ name = getattr(step, "name", "") or ""+ if name and name not in tool_configs and name not in _CLOUD_NOISE_NAMES:+ used[f"fn:{name}"] = name+ return used++ @staticmethod+ def _usage_dict(interaction: Any) -> Optional[Dict[str, Any]]:+ usage = getattr(interaction, "usage", None)+ if usage is None:+ return None+ if hasattr(usage, "model_dump"):+ data = usage.model_dump(mode="json", exclude_none=True)+ elif isinstance(usage, dict):+ data = usage+ else:+ return None+ return data or None++ @staticmethod+ async def _save_chain_ids(+ database: Any,+ memory_node_id: str,+ interaction_id: Optional[str],+ environment_id: Optional[str],+ *,+ human: Optional[str] = None,+ assistant: Optional[str] = None,+ window_size: int = 10,+ ) -> None:+ """Persist chain ids (and optionally the turn) onto simpleMemory."""+ from services.memory.markdown import (+ append_to_memory_markdown,+ trim_markdown_window,+ )++ params = await database.get_node_parameters(memory_node_id) or {}+ if interaction_id:+ params["vertex_interaction_id"] = interaction_id+ else:+ params.pop("vertex_interaction_id", None)+ if environment_id:+ params["vertex_environment_id"] = environment_id+ else:+ params.pop("vertex_environment_id", None)++ if human and assistant:+ content = params.get("memory_content") or ""+ content = append_to_memory_markdown(content, "human", human)+ content = append_to_memory_markdown(content, "assistant", assistant)+ content, _removed = trim_markdown_window(content, window_size)+ params["memory_content"] = content++ await database.save_node_parameters(memory_node_id, params)diff --git a/server/nodes/agent/vertex_managed_agent/_ops.py b/server/nodes/agent/vertex_managed_agent/_ops.pynew file mode 100644index 00000000..ecd9fa6c--- /dev/null+++ b/server/nodes/agent/vertex_managed_agent/_ops.py@@ -0,0 +1,178 @@+"""Dynamic cloud-tool canvas nodes for the Vertex managed agent.++agentBuilder pattern: mint ``vertexCloudTool`` display nodes for each+distinct cloud-side tool the managed agent used, wire them to the+agent's ``input-tools`` handle, persist into ``workflow.data`` FIRST+(DB is source of truth on the next run) and then broadcast the ops+batch on the ``workflow_ops_apply`` wire key so an open canvas applies+them live. Finally each used node gets a one-shot executing->success+pulse (the frontend's 500ms minimum glow makes it visible).+"""++from __future__ import annotations++import secrets+import time+from typing import Dict, List++from core.logging import get_logger+from services import workflow_ops as wf_ops+from services.plugin.deps import get_database+from services.status_broadcaster import get_status_broadcaster++logger = get_logger(__name__)++_DISPLAY_NODE_TYPE = "vertexCloudTool"+_WIRE_ROUTING_KEY = "workflow_ops_apply"+++def _mint_node_id(prefix: str) -> str:+ """Same id shape the frontend mints: <type>-<epoch_ms>-<hex6>."""+ return f"{prefix}-{int(time.time() * 1000)}-{secrets.token_hex(3)}"+++async def ensure_cloud_tool_nodes(+ *,+ workflow_id: str,+ agent_node_id: str,+ used: Dict[str, str],+) -> List[str]:+ """Mint/dedupe display nodes for ``{cloud_tool_key: label}`` usage.++ Returns the canvas node ids that were pulsed (existing + minted).+ """+ if not used:+ return []++ database = get_database()+ workflow = await database.get_workflow(workflow_id)+ if workflow is None:+ return []++ data = dict(workflow.data or {})+ nodes = list(data.get("nodes") or [])+ edges = list(data.get("edges") or [])++ # Dedupe against the LIVE canvas: display nodes already wired to+ # this agent's input-tools, keyed by label (labels are tool names).+ wired_sources = {+ edge.get("source")+ for edge in edges+ if edge.get("target") == agent_node_id+ and edge.get("targetHandle") == "input-tools"+ }+ existing: Dict[str, str] = {}+ for node in nodes:+ if node.get("type") == _DISPLAY_NODE_TYPE and node.get("id") in wired_sources:+ label = str((node.get("data") or {}).get("label") or "")+ if label:+ existing[label] = node.get("id")++ operations: List[dict] = []+ pulse_ids: List[str] = [+ existing[label] for label in used.values() if label in existing+ ]++ fan_index = 0+ for key, label in used.items():+ if label in existing:+ continue+ minted_id = _mint_node_id(_DISPLAY_NODE_TYPE)+ client_ref = f"new_{key}"+ add_node_op = wf_ops.add_node(+ client_ref,+ _DISPLAY_NODE_TYPE,+ {"cloud_tool_key": key},+ label=label,+ position=wf_ops.anchored(+ agent_node_id,+ offset_x=-260,+ offset_y=140 + 90 * fan_index,+ ),+ )+ # Shared id so backend status broadcasts glow the exact node the+ # frontend applier creates.+ add_node_op["minted_id"] = minted_id+ operations.append(add_node_op)+ operations.append(+ wf_ops.add_edge(+ {"client_ref": client_ref},+ agent_node_id,+ source_handle="output-main",+ target_handle="input-tools",+ )+ )++ # Server-side persistence (position resolves on the frontend;+ # {0,0} placeholder matches the agentBuilder asymmetry).+ nodes.append(+ {+ "id": minted_id,+ "type": _DISPLAY_NODE_TYPE,+ "position": {"x": 0, "y": 0},+ "data": {+ "label": label,+ "parameters": {"cloud_tool_key": key, "label": label},+ },+ }+ )+ edges.append(+ {+ "id": f"e-{minted_id}-{agent_node_id}",+ "source": minted_id,+ "target": agent_node_id,+ "sourceHandle": "output-main",+ "targetHandle": "input-tools",+ }+ )+ await database.save_node_parameters(+ minted_id, {"label": label, "cloud_tool_key": key}+ )+ pulse_ids.append(minted_id)+ fan_index += 1++ broadcaster = get_status_broadcaster()++ if operations:+ data["nodes"] = nodes+ data["edges"] = edges+ # Persist-then-broadcast: the DB write must land before any+ # consumer re-reads the canvas (agentBuilder invariant).+ await database.save_workflow(+ workflow_id=workflow_id,+ name=workflow.name,+ slug=workflow.slug,+ data=data,+ description=workflow.description,+ )+ await broadcaster.broadcast(+ {+ "type": _WIRE_ROUTING_KEY,+ "data": {+ "workflow_id": workflow_id,+ "caller_node_id": agent_node_id,+ "operations": operations,+ },+ }+ )+ logger.info(+ "[Vertex Agent] minted %d cloud-tool node(s) for %s",+ len(operations) // 2,+ agent_node_id,+ )++ for node_id in pulse_ids:+ await broadcaster.update_node_status(+ node_id,+ "executing",+ {"message": "Used by Vertex agent"},+ workflow_id=workflow_id,+ )+ await broadcaster.update_node_status(+ node_id,+ "success",+ {"message": "Used by Vertex agent"},+ workflow_id=workflow_id,+ )++ return pulse_idsdiff --git a/server/nodes/agent/vertex_managed_agent/meta.json b/server/nodes/agent/vertex_managed_agent/meta.jsonnew file mode 100644index 00000000..02d3bbf5--- /dev/null+++ b/server/nodes/agent/vertex_managed_agent/meta.json@@ -0,0 +1,3 @@+{+ "color": "#4285F4"+}diff --git a/server/nodes/visuals.json b/server/nodes/visuals.jsonindex 236a85dc..e391d42a 100644--- a/server/nodes/visuals.json+++ b/server/nodes/visuals.json@@ -341,5 +341,14 @@},"stripeAction": {"skill": "stripe-skill"+ },+ "vertex_managed_agent": {+ "icon": "lobehub:vertexai"+ },+ "vertex_agent_admin": {+ "icon": "lobehub:googlecloud"+ },+ "vertexCloudTool": {+ "icon": "lobehub:gemini"}}diff --git a/server/pyproject.toml b/server/pyproject.tomlindex 50f4c74b..966dc016 100644--- a/server/pyproject.toml+++ b/server/pyproject.toml@@ -61,8 +61,14 @@ dependencies = ["langchain-openai==1.1.14","langchain-anthropic==1.4.0","anthropic==0.94.0",- "langchain-google-genai==4.2.1",- "google-genai==1.72.0",+ # langchain-google-genai 4.2.4+ widens its google-genai pin to <3.0.0,+ # unblocking google-genai 2.x — required for the Interactions API+ # (client.interactions with environment= + client.agents) used by the+ # vertex_managed_agent / vertex_agent_admin plugins. 4.2.5 is the last+ # version compatible with the langchain-core==1.3.3 pin above (4.2.6++ # requires langchain-core>=1.4.7).+ "langchain-google-genai==4.2.5",+ "google-genai==2.11.0","langchain-groq==1.1.2","langchain-cerebras==0.8.2",# textChunker plugin (recursive / markdown / token strategies). Bumpeddiff --git a/server/requirements.txt b/server/requirements.txtindex f2ecd17a..6fb6cb01 100644--- a/server/requirements.txt+++ b/server/requirements.txt@@ -1,6 +1,6 @@# This file was autogenerated by uv via the following command:# uv export --frozen --no-emit-project --no-hashes --no-dev -o requirements.txt-aiohappyeyeballs==2.6.1+aiohappyeyeballs==2.7.1# via aiohttpaiohttp==3.14.1# via machinaos-server@@ -17,13 +17,14 @@ anthropic==0.94.0# langchain-anthropic# machinaos-server# rlms-anyio==4.13.0+anyio==4.14.1# via# anthropic# google-genai# groq# httpx# httpx-ws+ # langsmith# lmstudio# mcp# openai@@ -31,10 +32,8 @@ anyio==4.13.0# sse-starlette# starlette# watchfiles-apify-client==2.5.0+apify-client==3.0.5# via machinaos-server-apify-shared==2.2.0- # via apify-clientasync-timeout==5.0.1# via crawleeattrs==26.1.0@@ -44,24 +43,30 @@ attrs==26.1.0# referencingbcrypt==5.0.0# via machinaos-server-beautifulsoup4==4.14.3+beautifulsoup4==4.15.0# via crawlee-bracex==2.6+bracex==3.0# via wcmatch+brotli==1.2.0 ; platform_python_implementation == 'CPython'+ # via httpx+brotlicffi==1.2.0.1 ; platform_python_implementation != 'CPython'+ # via httpxcached-property==2.0.1# via portkey-ai-cachetools==7.0.5+cachetools==7.1.4# via crawlee-certifi==2026.2.25+certifi==2026.6.17# via# httpcore# httpx# requests-cffi==2.0.0 ; platform_python_implementation != 'PyPy'- # via cryptography-charset-normalizer==3.4.7+cffi==2.1.0+ # via+ # brotlicffi+ # cryptography+charset-normalizer==3.4.9# via requests-click==8.3.2+click==8.4.2# via# ddgs# uvicorn@@ -73,36 +78,40 @@ colorama==0.4.6# pytest# qrcode# tqdm- # uvicorn-crawlee==1.7.2+crawlee==1.8.1# via machinaos-server-cryptography==46.0.7+cryptography==49.0.0# via# google-auth# machinaos-server# pyjwt-ddgs==9.13.0+ddgs==9.14.4# via machinaos-serverdeepagents==0.5.2# via machinaos-server-dependency-injector==4.49.0+dependency-injector==4.49.1# via machinaos-serverdistro==1.9.0# via# anthropic# google-genai# groq+ # langsmith# openai# portkey-aidnspython==2.8.0# via email-validator-docstring-parser==0.17.0+docstring-parser==0.18.0# via anthropicemail-validator==2.3.0+ # via+ # machinaos-server+ # pydantic+fake-useragent==2.2.0+ # via ddgs+fastapi==0.139.0# via machinaos-server-fastapi==0.135.3- # via machinaos-server-filelock==3.25.2+filelock==3.29.7# via tldextractfiletype==1.2.0# via langchain-google-genai@@ -110,11 +119,11 @@ frozenlist==1.8.0# via# aiohttp# aiosignal-google-api-core==2.30.3+google-api-core==2.31.0# via google-api-python-client-google-api-python-client==2.194.0+google-api-python-client==2.198.0# via machinaos-server-google-auth==2.49.2+google-auth==2.55.2# via# google-api-core# google-api-python-client@@ -122,22 +131,22 @@ google-auth==2.49.2# google-auth-oauthlib# google-genai# machinaos-server-google-auth-httplib2==0.3.1+google-auth-httplib2==0.4.0# via# google-api-python-client# machinaos-server-google-auth-oauthlib==1.3.1+google-auth-oauthlib==1.4.0# via machinaos-server-google-genai==1.72.0+google-genai==2.11.0# via# langchain-google-genai# machinaos-server# rlms-googleapis-common-protos==1.74.0+googleapis-common-protos==1.75.0# via google-api-coregooglemaps==4.10.0# via machinaos-server-greenlet==3.4.0+greenlet==3.5.3# via# machinaos-server# sqlalchemy@@ -148,6 +157,10 @@ h11==0.16.0# httpcore# uvicorn# wsproto+h2==4.3.0+ # via httpx+hpack==4.2.0+ # via h2html2text==2025.4.15# via machinaos-serverhtml5lib==1.1@@ -156,15 +169,16 @@ httpcore==1.0.9# via# httpx# httpx-ws-httplib2==0.31.2+httplib2==0.32.0# via# google-api-python-client# google-auth-httplib2-httptools==0.7.1+httptools==0.8.0# via uvicornhttpx==0.28.1# via# anthropic+ # ddgs# google-genai# groq# httpx-ws@@ -181,6 +195,8 @@ httpx-sse==0.4.3# via mcphttpx-ws==0.9.0# via lmstudio+hyperframe==6.1.0+ # via h2idna==3.18# via# anyio@@ -189,15 +205,13 @@ idna==3.18# requests# tldextract# yarl-impit==0.12.0+impit==0.13.1# via# apify-client# crawlee-importlib-metadata==8.7.1- # via opentelemetry-apiiniconfig==2.3.0# via pytest-jiter==0.14.0+jiter==0.16.0# via# anthropic# openai@@ -210,7 +224,7 @@ jsonschema==4.26.0# via mcpjsonschema-specifications==2025.9.1# via jsonschema-langchain==1.2.15+langchain==1.2.18# via deepagentslangchain-anthropic==1.4.0# via@@ -232,7 +246,7 @@ langchain-core==1.3.3# langgraph-checkpoint# langgraph-prebuilt# machinaos-server-langchain-google-genai==4.2.1+langchain-google-genai==4.2.5# via# deepagents# machinaos-server@@ -242,21 +256,21 @@ langchain-openai==1.1.14# via# langchain-cerebras# machinaos-server-langchain-protocol==0.0.15+langchain-protocol==0.0.18# via langchain-corelangchain-text-splitters==1.1.2# via machinaos-server-langgraph==1.1.6+langgraph==1.1.10# via langchainlanggraph-checkpoint==4.1.1# via# langgraph# langgraph-prebuilt-langgraph-prebuilt==1.0.9+langgraph-prebuilt==1.0.13# via langgraphlanggraph-sdk==0.3.15# via langgraph-langsmith==0.8.14+langsmith==0.10.2# via# deepagents# langchain-core@@ -266,15 +280,15 @@ lxml==6.1.1# via# beautifulsoup4# ddgs-markdown-it-py==4.0.0+markdown-it-py==4.2.0# via# machinaos-server# rich-mcp==1.27.0+mcp==1.28.1# via machinaos-servermdurl==0.1.2# via markdown-it-py-more-itertools==11.0.2+more-itertools==11.1.0# via# apify-client# crawlee@@ -290,53 +304,53 @@ oauthlib==3.3.1# via requests-oauthlibollama==0.6.2# via machinaos-server-openai==2.31.0+openai==2.45.0# via# langchain-openai# rlms-opentelemetry-api==1.41.1+opentelemetry-api==1.43.0# via# machinaos-server# opentelemetry-sdk# opentelemetry-semantic-conventions-opentelemetry-sdk==1.41.1+opentelemetry-sdk==1.43.0# via machinaos-server-opentelemetry-semantic-conventions==0.62b1+opentelemetry-semantic-conventions==0.64b0# via opentelemetry-sdk-orjson==3.11.8+orjson==3.11.9# via# langgraph-sdk# langsmith# machinaos-serverormsgpack==1.12.2# via langgraph-checkpoint-packaging==26.0+packaging==26.2# via# langchain-core# langsmith# pooch# pytest-pillow==12.2.0+pillow==12.3.0# via qrcode-platformdirs==4.9.6+platformdirs==4.10.0# via poochpluggy==1.6.0# via pytestpooch==1.9.0# via machinaos-server-portkey-ai==2.2.0+portkey-ai==2.3.2# via rlms-primp==1.2.2+primp==1.3.1# via ddgs-propcache==0.4.1+propcache==0.5.2# via# aiohttp# yarl-protego==0.6.0+protego==0.6.2# via crawlee-proto-plus==1.27.2+proto-plus==1.28.1# via google-api-core-protobuf==6.33.6+protobuf==7.35.1# via# google-api-core# googleapis-common-protos@@ -348,15 +362,16 @@ psutil==7.2.2# machinaos-serverptyprocess==0.7.0 ; sys_platform != 'win32'# via machinaos-server-pyasn1==0.6.3+pyasn1==0.6.4# via pyasn1-modulespyasn1-modules==0.4.2# via google-auth-pycparser==3.0 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy'+pycparser==3.0 ; implementation_name != 'PyPy'# via cffipydantic==2.12.5# via# anthropic+ # apify-client# crawlee# fastapi# google-genai@@ -379,7 +394,7 @@ pydantic-core==2.41.5# via pydanticpydantic-monty==0.0.18# via machinaos-server-pydantic-settings==2.13.1+pydantic-settings==2.14.2# via# crawlee# machinaos-server@@ -396,7 +411,7 @@ pyjwt==2.13.0# mcppyparsing==3.3.2# via httplib2-pytest==9.0.3+pytest==9.1.1# via rlmspython-dotenv==1.2.2# via@@ -404,17 +419,17 @@ python-dotenv==1.2.2# pydantic-settings# rlms# uvicorn-python-multipart==0.0.27+python-multipart==0.0.32# via mcppython-slugify==8.0.4# via machinaos-server-python-telegram-bot==22.7+python-telegram-bot==22.8# via machinaos-server-pytz==2026.1.post1+pytz==2026.2# via machinaos-server-pywin32==311 ; sys_platform == 'win32'+pywin32==312 ; sys_platform == 'win32'# via mcp-pywinpty==3.0.3 ; sys_platform == 'win32'+pywinpty==3.0.5 ; sys_platform == 'win32'# via machinaos-serverpyyaml==6.0.3# via@@ -427,9 +442,9 @@ referencing==0.37.0# via# jsonschema# jsonschema-specifications-regex==2026.4.4+regex==2026.7.10# via tiktoken-requests==2.33.1+requests==2.34.2# via# google-api-core# google-auth@@ -452,11 +467,11 @@ requests-oauthlib==2.0.0# xdkrequests-toolbelt==1.0.0# via langsmith-rich==14.3.4+rich==15.0.0# via rlms-rlms==0.1.1+rlms==0.1.3# via machinaos-server-rpds-py==0.30.0+rpds-py==2026.6.3# via# jsonschema# referencing@@ -467,24 +482,27 @@ sniffio==1.3.1# anthropic# google-genai# groq+ # langsmith# openai# portkey-ai-soupsieve==2.8.3+socksio==1.0.0+ # via httpx+soupsieve==2.8.4# via beautifulsoup4-sqlalchemy==2.0.49+sqlalchemy==2.0.51# via sqlmodel-sqlmodel==0.0.38+sqlmodel==0.0.39# via machinaos-server-sse-starlette==3.4.1+sse-starlette==3.4.5# via mcp-starlette==1.3.0+starlette==1.3.1# via# fastapi# mcp# sse-starlette-structlog==25.5.0+structlog==26.1.0# via machinaos-server-temporalio==1.25.0+temporalio==1.30.0# via machinaos-servertenacity==9.1.4# via@@ -492,19 +510,19 @@ tenacity==9.1.4# langchain-coretext-unidecode==1.3# via python-slugify-tiktoken==0.12.0+tiktoken==0.13.0# via langchain-openaitldextract==5.3.1# via crawlee-tqdm==4.67.3+tqdm==4.68.4# via# openai# portkey-ai-types-protobuf==6.32.1.20260221+types-protobuf==7.34.1.20260518# via temporalio-types-requests==2.33.0.20260408+types-requests==2.33.0.20260518# via portkey-ai-typing-extensions==4.15.0+typing-extensions==4.16.0# via# aiohttp# aiosignal@@ -518,6 +536,7 @@ typing-extensions==4.15.0# groq# langchain-core# langchain-protocol+ # langsmith# lmstudio# mcp# nexus-rpc@@ -542,7 +561,7 @@ typing-inspection==0.4.2# mcp# pydantic# pydantic-settings-tzdata==2026.2+tzdata==2026.3# via machinaos-serveruritemplate==4.2.0# via google-api-python-client@@ -550,23 +569,23 @@ urllib3==2.7.0# via# requests# types-requests-uuid-utils==0.14.1+uuid-utils==0.17.0# via# langchain-core# langsmith-uvicorn==0.44.0+uvicorn==0.51.0# via# machinaos-server# mcpuvloop==0.22.1 ; platform_python_implementation != 'PyPy' and sys_platform != 'cygwin' and sys_platform != 'win32'# via uvicorn-watchfiles==1.1.1+watchfiles==1.2.0# via uvicorn-wcmatch==10.1+wcmatch==11.0# via deepagentswebencodings==0.5.1# via html5lib-websockets==16.0+websockets==16.1# via# google-genai# langsmith@@ -576,15 +595,13 @@ wsproto==1.3.2# via httpx-wsxdk==0.9.0# via machinaos-server-xxhash==3.6.0+xxhash==3.8.1# via# langgraph# langsmith-yarl==1.23.0+yarl==1.24.2# via# aiohttp# crawlee-zipp==3.23.0- # via importlib-metadatazstandard==0.25.0# via langsmithdiff --git a/server/services/ai.py b/server/services/ai.pyindex 0bb13773..26f13e40 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -2820,6 +2820,7 @@ class AIService:"ai_employee","rlm_agent","claude_code_agent",+ "vertex_managed_agent",)if node_type in _AGENT_DELEGATION_TYPES:agent_label = params.get("label", node_type)diff --git a/server/services/memory/state.py b/server/services/memory/state.pyindex ab2252cb..d0933e7d 100644--- a/server/services/memory/state.py+++ b/server/services/memory/state.py@@ -90,6 +90,11 @@ async def clear_agent_session_state(# earlier bridge revision.params["last_session_id"] = Noneparams.pop("memory_jsonl", None)+ # Wipe the Vertex managed-agent chain so the next run starts a+ # fresh interaction + sandbox instead of continuing the cleared+ # conversation (vertex_managed_agent memory bridge).+ params.pop("vertex_interaction_id", None)+ params.pop("vertex_environment_id", None)await db.save_node_parameters(memory_node_id, params)cleared_memory_node = Truelogger.info(diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.pyindex 859ef0c3..e282b9d1 100644--- a/server/services/temporal/workflow.py+++ b/server/services/temporal/workflow.py@@ -45,10 +45,11 @@ SKILL_NODE_TYPES = {# AgentWorkflow for these node types instead of an activity. Tool calls# inside the agent loop become per-type activities (F4.A path).#-# Excluded: ``rlm_agent``, ``claude_code_agent``. Their internal session-# state (RLM REPL / Claude CLI --resume with stable cwd) requires-# single-process continuity and breaks across activity boundaries. They-# continue via F4.A per-type activities.+# Excluded: ``rlm_agent``, ``claude_code_agent``, ``vertex_managed_agent``.+# Their internal session state (RLM REPL / Claude CLI --resume with stable+# cwd / Interactions API previous_interaction_id + environment chaining and+# post-turn canvas minting) requires single-process continuity and breaks+# across activity boundaries. They continue via F4.A per-type activities.AGENT_WORKFLOW_TYPES = frozenset(["aiAgent",diff --git a/server/tests/fixtures/tool_names_snapshot.json b/server/tests/fixtures/tool_names_snapshot.jsonindex 3aa05f7c..739e0e84 100644--- a/server/tests/fixtures/tool_names_snapshot.json+++ b/server/tests/fixtures/tool_names_snapshot.json@@ -38,6 +38,7 @@"ai_employee": "delegate_to_ai_employee","rlm_agent": "delegate_to_rlm_agent","claude_code_agent": "delegate_to_claude_code_agent",+ "vertex_managed_agent": "delegate_to_vertex_managed_agent","batteryMonitor": "android_battery","networkMonitor": "android_network","systemInfo": "android_system_info",diff --git a/server/tests/nodes/test_vertex_agents.py b/server/tests/nodes/test_vertex_agents.pynew file mode 100644index 00000000..f26f7dd8--- /dev/null+++ b/server/tests/nodes/test_vertex_agents.py@@ -0,0 +1,650 @@+"""Contract tests for the Vertex managed-agent plugins.++vertex_managed_agent drives Google's Interactions API (mocked here at+the ``create_interaction_and_wait`` / ``build_genai_client`` seam in the+node's module namespace):++- prompt fallback + empty-prompt NodeUserError+- memory bridge: stored chain ids flow into previous_interaction_id /+ environment and new ids persist back onto the simpleMemory params+- requires_action loop: declared function tools dispatch through+ ``execute_tool`` and answer with call_id-matched function_result inputs+- stale-chain recovery: env-expired error wipes ids and retries fresh+- cloud-tool usage detection feeds the minting helper++vertex_agent_admin maps its four operations onto ``client.aio.agents``.+"""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from tests.nodes._mocks import patched_broadcaster, patched_container++pytestmark = pytest.mark.node_contract+++# ============================================================================+# Helpers+# ============================================================================+++def _edge(source: str, target: str, target_handle: str) -> dict:+ return {"source": source, "target": target, "targetHandle": target_handle}+++def _node(node_id: str, node_type: str, label: str | None = None) -> dict:+ return {"id": node_id, "type": node_type, "data": {"label": label or node_type}}+++def _interaction(+ *,+ status: str = "completed",+ interaction_id: str = "ix-1",+ environment_id: str = "env_CAE1",+ output_text: str = "cloud response",+ steps: list | None = None,+ usage: dict | None = None,+) -> SimpleNamespace:+ return SimpleNamespace(+ id=interaction_id,+ status=status,+ environment_id=environment_id,+ output_text=output_text,+ steps=steps or [],+ usage=usage,+ )+++def _fc_step(name: str, call_id: str, arguments: dict | None = None) -> SimpleNamespace:+ return SimpleNamespace(+ type="function_call", name=name, id=call_id, arguments=arguments or {}+ )+++def _fr_step(call_id: str) -> SimpleNamespace:+ return SimpleNamespace(type="function_result", call_id=call_id)+++_NODE_MODULE = "nodes.agent.vertex_managed_agent"+_ADMIN_MODULE = "nodes.agent.vertex_agent_admin"+++def _patched_interactions(side_effect):+ """Patch the node's SDK seam: fake client + canned interactions."""+ return (+ patch(f"{_NODE_MODULE}.build_genai_client", return_value=MagicMock()),+ patch(+ f"{_NODE_MODULE}.create_interaction_and_wait",+ AsyncMock(side_effect=side_effect),+ ),+ )+++def _wire_async_broadcasts(broadcaster: MagicMock) -> None:+ broadcaster.broadcast_agent_progress = AsyncMock(return_value=None)+ broadcaster.broadcast = AsyncMock(return_value=None)+++class FakeGenaiError(Exception):+ """Stands in for the SDK error hierarchy (module-name matched)."""+++FakeGenaiError.__module__ = "google.genai._gaos.lib.compat_errors"+++# ============================================================================+# vertex_managed_agent+# ============================================================================+++class TestVertexManagedAgent:+ async def test_happy_path_single_turn(self, harness):+ client_patch, create_patch = _patched_interactions([_interaction()])+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ client_patch,+ create_patch as create_mock,+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_managed_agent",+ {"prompt": "hello", "project_id": "test-proj"},+ )++ harness.assert_envelope(result, success=True)+ payload = result["result"]+ assert payload["response"] == "cloud response"+ assert payload["interaction_id"] == "ix-1"+ assert payload["environment_id"] == "env_CAE1"+ assert payload["status"] == "completed"+ assert payload["provider"] == "gemini"++ # Fresh run: remote sandbox, no chaining.+ _, kwargs = create_mock.call_args+ assert kwargs["environment"] == "remote"+ assert "previous_interaction_id" not in kwargs+ assert kwargs["agent"] == "antigravity-preview-05-2026"+ assert kwargs["store"] is True++ async def test_empty_prompt_without_input_is_user_error(self, harness):+ client_patch, create_patch = _patched_interactions([_interaction()])+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ client_patch,+ create_patch,+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_managed_agent",+ {"prompt": "", "project_id": "test-proj"},+ )++ assert result["success"] is False+ assert result.get("error_type") == "NodeUserError"++ async def test_prompt_falls_back_to_input_message(self, harness):+ agent_id = "vx-1"+ client_patch, create_patch = _patched_interactions([_interaction()])+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ client_patch,+ create_patch as create_mock,+ ):+ _wire_async_broadcasts(bc)+ ctx = harness.build_context(+ nodes=[_node(agent_id, "vertex_managed_agent"), _node("t1", "chatTrigger")],+ edges=[_edge("t1", agent_id, "input-main")],+ )+ ctx["outputs"] = {"t1": {"message": "from trigger"}}+ result = await harness.execute(+ "vertex_managed_agent",+ {"prompt": "", "project_id": "test-proj"},+ node_id=agent_id,+ context=ctx,+ )++ harness.assert_envelope(result, success=True)+ _, kwargs = create_mock.call_args+ assert kwargs["input"] == "from trigger"++ async def test_memory_bridge_chains_and_persists(self, harness):+ agent_id = "vx-1"+ mem_id = "mem-1"+ saved: dict = {}++ harness.database.get_node_parameters = AsyncMock(+ return_value={+ "session_id": "",+ "window_size": 5,+ "memory_content": "# Conversation History\n",+ "vertex_interaction_id": "ix-prev",+ "vertex_environment_id": "env_prev",+ }+ )++ async def capture_save(node_id, params):+ saved[node_id] = params+ return True++ harness.database.save_node_parameters = AsyncMock(side_effect=capture_save)++ client_patch, create_patch = _patched_interactions(+ [_interaction(interaction_id="ix-new", environment_id="env_new")]+ )+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ client_patch,+ create_patch as create_mock,+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_managed_agent",+ {"prompt": "remember me", "project_id": "test-proj"},+ node_id=agent_id,+ nodes=[_node(agent_id, "vertex_managed_agent"), _node(mem_id, "simpleMemory")],+ edges=[_edge(mem_id, agent_id, "input-memory")],+ )++ harness.assert_envelope(result, success=True)+ _, kwargs = create_mock.call_args+ assert kwargs["previous_interaction_id"] == "ix-prev"+ assert kwargs["environment"] == "env_prev"++ persisted = saved[mem_id]+ assert persisted["vertex_interaction_id"] == "ix-new"+ assert persisted["vertex_environment_id"] == "env_new"+ assert "remember me" in persisted["memory_content"]+ assert "cloud response" in persisted["memory_content"]++ async def test_requires_action_dispatches_tool_and_answers(self, harness):+ agent_id = "vx-1"+ tool_id = "tool-1"++ fake_tool = SimpleNamespace(name="fake_tool", description="d", args_schema=None)+ ai_service = MagicMock(name="AIService")+ ai_service._build_tool_from_node = AsyncMock(+ return_value=(+ fake_tool,+ {"node_type": "duckduckgoSearch", "node_id": tool_id, "parameters": {}, "label": "ddg"},+ )+ )+ execute_tool_mock = AsyncMock(return_value={"answer": 42})++ turns = [+ _interaction(+ status="requires_action",+ interaction_id="ix-1",+ steps=[+ _fc_step("provision_sandbox", "c0"),+ _fr_step("c0"),+ _fc_step("fake_tool", "c1", {"query": "x"}),+ ],+ ),+ _interaction(status="completed", interaction_id="ix-2"),+ ]+ client_patch, create_patch = _patched_interactions(turns)+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ client_patch,+ create_patch as create_mock,+ patch("services.plugin.deps.get_ai_service", return_value=ai_service),+ patch("services.handlers.tools.execute_tool", execute_tool_mock),+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_managed_agent",+ {"prompt": "use the tool", "project_id": "test-proj"},+ node_id=agent_id,+ nodes=[+ _node(agent_id, "vertex_managed_agent"),+ _node(tool_id, "duckduckgoSearch"),+ ],+ edges=[_edge(tool_id, agent_id, "input-tools")],+ )++ harness.assert_envelope(result, success=True)+ assert result["result"]["turns"] == 2++ # Tools declared on both creates.+ first_kwargs = create_mock.call_args_list[0].kwargs+ declared = first_kwargs["tools"]+ assert declared == [+ {+ "type": "function",+ "name": "fake_tool",+ "description": "d",+ "parameters": {"type": "object", "properties": {}},+ }+ ]++ # Only OUR pending call executed (provision_sandbox skipped).+ execute_tool_mock.assert_awaited_once()+ name_arg, args_arg, config_arg = execute_tool_mock.await_args.args+ assert name_arg == "fake_tool"+ assert args_arg == {"query": "x"}+ assert config_arg["parent_node_id"] == agent_id++ # Follow-up create answers with the matched call_id.+ second_kwargs = create_mock.call_args_list[1].kwargs+ assert second_kwargs["previous_interaction_id"] == "ix-1"+ assert second_kwargs["input"] == [+ {+ "type": "function_result",+ "name": "fake_tool",+ "call_id": "c1",+ "result": {"answer": 42},+ }+ ]++ async def test_stale_chain_wipes_and_retries_fresh(self, harness):+ agent_id = "vx-1"+ mem_id = "mem-1"++ harness.database.get_node_parameters = AsyncMock(+ return_value={+ "vertex_interaction_id": "ix-stale",+ "vertex_environment_id": "env_stale",+ "memory_content": "# Conversation History\n",+ }+ )++ calls: list = []++ async def create_side_effect(client, **kwargs):+ calls.append(kwargs)+ if len(calls) == 1:+ raise FakeGenaiError("Error 404: environment not found")+ return _interaction(interaction_id="ix-fresh", environment_id="env_fresh")++ client_patch = patch(f"{_NODE_MODULE}.build_genai_client", return_value=MagicMock())+ create_patch = patch(+ f"{_NODE_MODULE}.create_interaction_and_wait",+ AsyncMock(side_effect=create_side_effect),+ )+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ client_patch,+ create_patch,+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_managed_agent",+ {"prompt": "p", "project_id": "test-proj"},+ node_id=agent_id,+ nodes=[_node(agent_id, "vertex_managed_agent"), _node(mem_id, "simpleMemory")],+ edges=[_edge(mem_id, agent_id, "input-memory")],+ )++ harness.assert_envelope(result, success=True)+ assert calls[0]["previous_interaction_id"] == "ix-stale"+ assert "previous_interaction_id" not in calls[1]+ assert calls[1]["environment"] == "remote"+ assert result["result"]["interaction_id"] == "ix-fresh"++ async def test_cloud_tool_usage_feeds_minting(self, harness):+ agent_id = "vx-1"+ steps = [+ _fc_step("run_command", "c1"),+ _fr_step("c1"),+ SimpleNamespace(type="google_search_call", id="c2", name=None),+ ]+ client_patch, create_patch = _patched_interactions([_interaction(steps=steps)])+ mint_mock = AsyncMock(return_value=[])+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ client_patch,+ create_patch,+ patch(f"{_NODE_MODULE}._ops.ensure_cloud_tool_nodes", mint_mock),+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_managed_agent",+ {"prompt": "p", "project_id": "test-proj"},+ node_id=agent_id,+ context={+ "workflow_id": "wf-1",+ "nodes": [_node(agent_id, "vertex_managed_agent")],+ "edges": [],+ "outputs": {},+ },+ )++ harness.assert_envelope(result, success=True)+ mint_mock.assert_awaited_once()+ used = mint_mock.await_args.kwargs["used"]+ assert used == {+ "fn:run_command": "run_command",+ "type:google_search_call": "Google Search",+ }+ assert sorted(result["result"]["cloud_tools_used"]) == [+ "Google Search",+ "run_command",+ ]++ async def test_visualize_off_skips_minting(self, harness):+ steps = [_fc_step("run_command", "c1")]+ client_patch, create_patch = _patched_interactions([_interaction(steps=steps)])+ mint_mock = AsyncMock(return_value=[])+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ client_patch,+ create_patch,+ patch(f"{_NODE_MODULE}._ops.ensure_cloud_tool_nodes", mint_mock),+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_managed_agent",+ {"prompt": "p", "project_id": "test-proj", "visualize_cloud_tools": False},+ context={"workflow_id": "wf-1", "nodes": [], "edges": [], "outputs": {}},+ )++ harness.assert_envelope(result, success=True)+ mint_mock.assert_not_awaited()+++# ============================================================================+# ensure_cloud_tool_nodes (minting helper)+# ============================================================================+++class TestCloudToolMinting:+ def _workflow(self, nodes=None, edges=None):+ return SimpleNamespace(+ data={"nodes": list(nodes or []), "edges": list(edges or [])},+ name="wf",+ slug="wf_1",+ description=None,+ )++ async def test_mints_persists_then_broadcasts_and_pulses(self):+ from nodes.agent.vertex_managed_agent import _ops++ database = MagicMock()+ database.get_workflow = AsyncMock(return_value=self._workflow())+ database.save_workflow = AsyncMock(return_value=True)+ database.save_node_parameters = AsyncMock(return_value=True)+ broadcaster = MagicMock()+ broadcaster.broadcast = AsyncMock()+ broadcaster.update_node_status = AsyncMock()++ with (+ patch.object(_ops, "get_database", return_value=database),+ patch.object(_ops, "get_status_broadcaster", return_value=broadcaster),+ ):+ pulsed = await _ops.ensure_cloud_tool_nodes(+ workflow_id="wf-1",+ agent_node_id="vx-1",+ used={"fn:run_command": "run_command"},+ )++ assert len(pulsed) == 1+ minted_id = pulsed[0]+ assert minted_id.startswith("vertexCloudTool-")++ # Persisted node + edge with the minted id.+ save_kwargs = database.save_workflow.await_args.kwargs+ persisted_nodes = save_kwargs["data"]["nodes"]+ persisted_edges = save_kwargs["data"]["edges"]+ assert persisted_nodes[0]["id"] == minted_id+ assert persisted_nodes[0]["type"] == "vertexCloudTool"+ assert persisted_edges[0]["source"] == minted_id+ assert persisted_edges[0]["targetHandle"] == "input-tools"++ # Persist happens before the ops broadcast.+ broadcast_payload = broadcaster.broadcast.await_args.args[0]+ assert broadcast_payload["type"] == "workflow_ops_apply"+ ops = broadcast_payload["data"]["operations"]+ assert ops[0]["type"] == "add_node"+ assert ops[0]["minted_id"] == minted_id+ assert ops[1]["type"] == "add_edge"++ # executing -> success pulse on the minted node.+ statuses = [c.args[1] for c in broadcaster.update_node_status.await_args_list]+ assert statuses == ["executing", "success"]++ async def test_dedupes_existing_node_by_label(self):+ from nodes.agent.vertex_managed_agent import _ops++ existing_nodes = [+ {+ "id": "vertexCloudTool-1-aaa",+ "type": "vertexCloudTool",+ "data": {"label": "run_command"},+ }+ ]+ existing_edges = [+ {+ "source": "vertexCloudTool-1-aaa",+ "target": "vx-1",+ "targetHandle": "input-tools",+ }+ ]+ database = MagicMock()+ database.get_workflow = AsyncMock(+ return_value=self._workflow(existing_nodes, existing_edges)+ )+ database.save_workflow = AsyncMock(return_value=True)+ database.save_node_parameters = AsyncMock(return_value=True)+ broadcaster = MagicMock()+ broadcaster.broadcast = AsyncMock()+ broadcaster.update_node_status = AsyncMock()++ with (+ patch.object(_ops, "get_database", return_value=database),+ patch.object(_ops, "get_status_broadcaster", return_value=broadcaster),+ ):+ pulsed = await _ops.ensure_cloud_tool_nodes(+ workflow_id="wf-1",+ agent_node_id="vx-1",+ used={"fn:run_command": "run_command"},+ )++ assert pulsed == ["vertexCloudTool-1-aaa"]+ database.save_workflow.assert_not_awaited()+ broadcaster.broadcast.assert_not_awaited()+ # Existing node still pulses.+ assert broadcaster.update_node_status.await_count == 2+++# ============================================================================+# vertex_agent_admin+# ============================================================================+++class TestVertexAgentAdmin:+ def _client_with_agents(self):+ client = MagicMock()+ client.aio.agents.create = AsyncMock(+ return_value=SimpleNamespace(model_dump=lambda **kw: {"id": "my-agent"})+ )+ client.aio.agents.list = AsyncMock(+ return_value=SimpleNamespace(agents=[{"id": "a1"}, {"id": "a2"}])+ )+ client.aio.agents.get = AsyncMock(return_value={"id": "my-agent", "tools": []})+ client.aio.agents.delete = AsyncMock(return_value=None)+ return client++ async def test_create_maps_params_to_sdk(self, harness):+ client = self._client_with_agents()+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ patch(f"{_ADMIN_MODULE}.build_genai_client", return_value=client),+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_agent_admin",+ {+ "operation": "create",+ "project_id": "test-proj",+ "agent_id": "my-agent",+ "description": "demo",+ "system_instruction": "be helpful",+ "tools": ["code_execution", "google_search"],+ },+ )++ harness.assert_envelope(result, success=True)+ assert result["result"]["agent"] == {"id": "my-agent"}+ kwargs = client.aio.agents.create.await_args.kwargs+ assert kwargs["id"] == "my-agent"+ assert kwargs["base_agent"] == "antigravity-preview-05-2026"+ assert kwargs["description"] == "demo"+ assert kwargs["system_instruction"] == "be helpful"+ assert kwargs["tools"] == [+ {"type": "code_execution"},+ {"type": "google_search"},+ ]++ async def test_list_returns_agents(self, harness):+ client = self._client_with_agents()+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ patch(f"{_ADMIN_MODULE}.build_genai_client", return_value=client),+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_agent_admin",+ {"operation": "list", "project_id": "test-proj"},+ )++ harness.assert_envelope(result, success=True)+ assert result["result"]["count"] == 2+ assert result["result"]["agents"][0]["id"] == "a1"++ async def test_delete_requires_agent_id(self, harness):+ client = self._client_with_agents()+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ patch(f"{_ADMIN_MODULE}.build_genai_client", return_value=client),+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_agent_admin",+ {"operation": "delete", "project_id": "test-proj"},+ )++ assert result["success"] is False+ assert result.get("error_type") == "NodeUserError"+ client.aio.agents.delete.assert_not_awaited()++ async def test_delete_happy_path(self, harness):+ client = self._client_with_agents()+ with (+ patched_container(auth_api_keys={}),+ patched_broadcaster() as bc,+ patch(f"{_ADMIN_MODULE}.build_genai_client", return_value=client),+ ):+ _wire_async_broadcasts(bc)+ result = await harness.execute(+ "vertex_agent_admin",+ {"operation": "delete", "project_id": "test-proj", "agent_id": "my-agent"},+ )++ harness.assert_envelope(result, success=True)+ assert result["result"]["deleted"] is True+ client.aio.agents.delete.assert_awaited_once_with(id="my-agent")+++# ============================================================================+# memory clear integration (chain ids wiped)+# ============================================================================+++class TestChainIdHelpers:+ async def test_save_chain_ids_none_pops_keys(self):+ from nodes.agent.vertex_managed_agent import VertexManagedAgentNode++ params_store = {+ "vertex_interaction_id": "ix-old",+ "vertex_environment_id": "env-old",+ "memory_content": "# Conversation History\n",+ }+ database = MagicMock()+ database.get_node_parameters = AsyncMock(return_value=dict(params_store))+ saved = {}++ async def capture(node_id, params):+ saved.update(params)+ return True++ database.save_node_parameters = AsyncMock(side_effect=capture)++ await VertexManagedAgentNode._save_chain_ids(database, "mem-1", None, None)++ assert "vertex_interaction_id" not in saved+ assert "vertex_environment_id" not in saved