glaip-sdk 0.6.6__py3-none-any.whl → 0.6.8b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,706 @@
1
+ """LangGraph-based runner for local agent execution.
2
+
3
+ This module provides the LangGraphRunner which executes glaip-sdk agents
4
+ locally via the aip-agents LangGraphReactAgent, without requiring the AIP server.
5
+
6
+ Authors:
7
+ Christian Trisno Sen Long Chen (christian.t.s.l.chen@gdplabs.id)
8
+
9
+ Example:
10
+ >>> from glaip_sdk.runner import LangGraphRunner
11
+ >>> from glaip_sdk.agents import Agent
12
+ >>>
13
+ >>> runner = LangGraphRunner()
14
+ >>> agent = Agent(name="my-agent", instruction="You are helpful.")
15
+ >>> result = runner.run(agent, "Hello, world!")
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import inspect
22
+ from dataclasses import dataclass
23
+ from typing import TYPE_CHECKING, Any
24
+
25
+ from glaip_sdk.runner.base import BaseRunner
26
+ from glaip_sdk.runner.deps import (
27
+ check_local_runtime_available,
28
+ get_local_runtime_missing_message,
29
+ )
30
+ from glaip_sdk.utils.a2a import A2AEventStreamProcessor
31
+ from gllm_core.utils import LoggerManager
32
+
33
+ if TYPE_CHECKING:
34
+ from langchain_core.messages import BaseMessage
35
+
36
+ from glaip_sdk.agents.base import Agent
37
+
38
+ logger = LoggerManager().get_logger(__name__)
39
+
40
+ # Default A2A event processor
41
+ _event_processor = A2AEventStreamProcessor()
42
+
43
+
44
+ def _convert_chat_history_to_messages(
45
+ chat_history: list[dict[str, str]] | None,
46
+ ) -> list[BaseMessage]:
47
+ """Convert chat history dicts to LangChain messages.
48
+
49
+ Args:
50
+ chat_history: List of dicts with "role" and "content" keys.
51
+ Supported roles: "user"/"human", "assistant"/"ai", "system".
52
+
53
+ Returns:
54
+ List of LangChain BaseMessage instances.
55
+ """
56
+ if not chat_history:
57
+ return []
58
+
59
+ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage # noqa: PLC0415
60
+
61
+ messages: list[BaseMessage] = []
62
+ for msg in chat_history:
63
+ role = msg.get("role", "").lower()
64
+ content = msg.get("content", "")
65
+
66
+ if role in ("user", "human"):
67
+ messages.append(HumanMessage(content=content))
68
+ elif role in ("assistant", "ai"):
69
+ messages.append(AIMessage(content=content))
70
+ elif role == "system":
71
+ messages.append(SystemMessage(content=content))
72
+ else:
73
+ # Default to human message for unknown roles
74
+ logger.warning("Unknown chat history role '%s', treating as user message", role)
75
+ messages.append(HumanMessage(content=content))
76
+
77
+ return messages
78
+
79
+
80
+ @dataclass(frozen=True, slots=True)
81
+ class LangGraphRunner(BaseRunner):
82
+ """Runner implementation using aip-agents LangGraphReactAgent.
83
+
84
+ MVP scope:
85
+ - Execute via `LangGraphReactAgent.arun_a2a_stream()`
86
+ - Extract and return final text from the emitted `final_response` event
87
+
88
+ Attributes:
89
+ default_model: Model name to use when agent.model is not set.
90
+ Defaults to "gpt-4o-mini".
91
+ """
92
+
93
+ default_model: str = "openai/gpt-4o-mini"
94
+
95
+ def run(
96
+ self,
97
+ agent: Agent,
98
+ message: str,
99
+ verbose: bool = False,
100
+ runtime_config: dict[str, Any] | None = None,
101
+ chat_history: list[dict[str, str]] | None = None,
102
+ **kwargs: Any,
103
+ ) -> str:
104
+ """Execute agent synchronously and return final response text.
105
+
106
+ Args:
107
+ agent: The glaip_sdk Agent to execute.
108
+ message: The user message to send to the agent.
109
+ verbose: If True, emit debug trace output during execution.
110
+ Defaults to False.
111
+ runtime_config: Optional runtime configuration for tools, MCPs, etc.
112
+ Defaults to None. (Implemented in PR-04+)
113
+ chat_history: Optional list of prior conversation messages.
114
+ Each message is a dict with "role" and "content" keys.
115
+ Defaults to None.
116
+ **kwargs: Additional keyword arguments passed to the backend.
117
+
118
+ Returns:
119
+ The final response text from the agent.
120
+
121
+ Raises:
122
+ RuntimeError: If the local runtime dependencies are not available.
123
+ RuntimeError: If no final response is received from the agent.
124
+ """
125
+ if not check_local_runtime_available():
126
+ raise RuntimeError(get_local_runtime_missing_message())
127
+
128
+ try:
129
+ asyncio.get_running_loop()
130
+ except RuntimeError:
131
+ pass
132
+ else:
133
+ raise RuntimeError(
134
+ "LangGraphRunner.run() cannot be called from a running event loop. "
135
+ "Use 'await LangGraphRunner.arun(...)' instead."
136
+ )
137
+
138
+ coro = self._arun_internal(
139
+ agent=agent,
140
+ message=message,
141
+ verbose=verbose,
142
+ runtime_config=runtime_config,
143
+ chat_history=chat_history,
144
+ **kwargs,
145
+ )
146
+
147
+ return asyncio.run(coro)
148
+
149
+ async def arun(
150
+ self,
151
+ agent: Agent,
152
+ message: str,
153
+ verbose: bool = False,
154
+ runtime_config: dict[str, Any] | None = None,
155
+ chat_history: list[dict[str, str]] | None = None,
156
+ **kwargs: Any,
157
+ ) -> str:
158
+ """Execute agent asynchronously and return final response text.
159
+
160
+ Args:
161
+ agent: The glaip_sdk Agent to execute.
162
+ message: The user message to send to the agent.
163
+ verbose: If True, emit debug trace output during execution.
164
+ Defaults to False.
165
+ runtime_config: Optional runtime configuration for tools, MCPs, etc.
166
+ Defaults to None. (Implemented in PR-04+)
167
+ chat_history: Optional list of prior conversation messages.
168
+ Each message is a dict with "role" and "content" keys.
169
+ Defaults to None.
170
+ **kwargs: Additional keyword arguments passed to the backend.
171
+
172
+ Returns:
173
+ The final response text from the agent.
174
+
175
+ Raises:
176
+ RuntimeError: If no final response is received from the agent.
177
+ """
178
+ return await self._arun_internal(
179
+ agent=agent,
180
+ message=message,
181
+ verbose=verbose,
182
+ runtime_config=runtime_config,
183
+ chat_history=chat_history,
184
+ **kwargs,
185
+ )
186
+
187
+ async def _arun_internal(
188
+ self,
189
+ agent: Agent,
190
+ message: str,
191
+ verbose: bool = False,
192
+ runtime_config: dict[str, Any] | None = None,
193
+ chat_history: list[dict[str, str]] | None = None,
194
+ **kwargs: Any,
195
+ ) -> str:
196
+ """Internal async implementation of agent execution.
197
+
198
+ Args:
199
+ agent: The glaip_sdk Agent to execute.
200
+ message: The user message to send to the agent.
201
+ verbose: If True, emit debug trace output during execution.
202
+ runtime_config: Optional runtime configuration for tools, MCPs, etc.
203
+ chat_history: Optional list of prior conversation messages.
204
+ **kwargs: Additional keyword arguments passed to the backend.
205
+
206
+ Returns:
207
+ The final response text from the agent.
208
+ """
209
+ # Build the local LangGraphReactAgent from the glaip_sdk Agent
210
+ local_agent = self.build_langgraph_agent(agent, runtime_config=runtime_config)
211
+
212
+ # Convert chat history to LangChain messages for the agent
213
+ langchain_messages = _convert_chat_history_to_messages(chat_history)
214
+ if langchain_messages:
215
+ kwargs["messages"] = langchain_messages
216
+ logger.debug(
217
+ "Passing %d chat history messages to agent '%s'",
218
+ len(langchain_messages),
219
+ agent.name,
220
+ )
221
+
222
+ # Collect A2AEvents from the stream and extract final response
223
+ events: list[dict[str, Any]] = []
224
+
225
+ async for event in local_agent.arun_a2a_stream(message, **kwargs):
226
+ if verbose:
227
+ self._log_event(event)
228
+ events.append(event)
229
+
230
+ return _event_processor.extract_final_response(events)
231
+
232
+ def build_langgraph_agent(
233
+ self,
234
+ agent: Agent,
235
+ runtime_config: dict[str, Any] | None = None,
236
+ ) -> Any:
237
+ """Build a LangGraphReactAgent from a glaip_sdk Agent definition.
238
+
239
+ Args:
240
+ agent: The glaip_sdk Agent to convert.
241
+ runtime_config: Optional runtime configuration with tool_configs,
242
+ mcp_configs, agent_config, and agent-specific overrides.
243
+
244
+ Returns:
245
+ A configured LangGraphReactAgent instance.
246
+
247
+ Raises:
248
+ ImportError: If aip-agents is not installed.
249
+ ValueError: If agent has unsupported tools, MCPs, or sub-agents for local mode.
250
+ """
251
+ from aip_agents.agent import LangGraphReactAgent # noqa: PLC0415
252
+ from glaip_sdk.runner.tool_adapter import LangChainToolAdapter # noqa: PLC0415
253
+
254
+ # Adapt tools for local execution
255
+ # NOTE: CLI parity waiver - local tool execution is SDK-only for MVP.
256
+ # See specs/f/local-agent-runtime/plan.md: "CLI parity is explicitly deferred
257
+ # and will require SDK Technical Lead sign-off per constitution principle IV."
258
+ langchain_tools: list[Any] = []
259
+ if agent.tools:
260
+ adapter = LangChainToolAdapter()
261
+ langchain_tools = adapter.adapt_tools(agent.tools)
262
+
263
+ # Build sub-agents recursively
264
+ sub_agent_instances = self._build_sub_agents(agent.agents, runtime_config)
265
+
266
+ # Normalize runtime config: merge global and agent-specific configs
267
+ normalized_config = self._normalize_runtime_config(runtime_config, agent)
268
+
269
+ # Merge tool_configs: agent definition < runtime config
270
+ tool_configs = self._merge_tool_configs(agent, normalized_config)
271
+
272
+ # Merge mcp_configs: agent definition < runtime config
273
+ mcp_configs = self._merge_mcp_configs(agent, normalized_config)
274
+
275
+ # Merge agent_config: agent definition < runtime config
276
+ merged_agent_config = self._merge_agent_config(agent, normalized_config)
277
+ agent_config_params, agent_config_kwargs = self._apply_agent_config(merged_agent_config)
278
+
279
+ # Build the LangGraphReactAgent with tools, sub-agents, and configs
280
+ local_agent = LangGraphReactAgent(
281
+ name=agent.name,
282
+ instruction=agent.instruction,
283
+ description=agent.description,
284
+ model=agent.model or self.default_model,
285
+ tools=langchain_tools,
286
+ agents=sub_agent_instances if sub_agent_instances else None,
287
+ tool_configs=tool_configs if tool_configs else None,
288
+ **agent_config_params,
289
+ **agent_config_kwargs,
290
+ )
291
+
292
+ # Add MCP servers if configured
293
+ self._add_mcp_servers(local_agent, agent, mcp_configs)
294
+
295
+ logger.debug(
296
+ "Built local LangGraphReactAgent for agent '%s' with %d tools, %d sub-agents, and %d MCPs",
297
+ agent.name,
298
+ len(langchain_tools),
299
+ len(sub_agent_instances),
300
+ len(agent.mcps) if agent.mcps else 0,
301
+ )
302
+ return local_agent
303
+
304
+ def _build_sub_agents(
305
+ self,
306
+ sub_agents: list[Any] | None,
307
+ runtime_config: dict[str, Any] | None,
308
+ ) -> list[Any]:
309
+ """Build sub-agent instances recursively.
310
+
311
+ Args:
312
+ sub_agents: List of sub-agent definitions.
313
+ runtime_config: Runtime config to pass to sub-agents.
314
+
315
+ Returns:
316
+ List of built sub-agent instances.
317
+
318
+ Raises:
319
+ ValueError: If sub-agent is platform-only.
320
+ """
321
+ if not sub_agents:
322
+ return []
323
+
324
+ sub_agent_instances = []
325
+ for sub_agent in sub_agents:
326
+ self._validate_sub_agent_for_local_mode(sub_agent)
327
+ sub_agent_instances.append(self.build_langgraph_agent(sub_agent, runtime_config))
328
+ return sub_agent_instances
329
+
330
+ def _add_mcp_servers(
331
+ self,
332
+ local_agent: Any,
333
+ agent: Agent,
334
+ merged_mcp_configs: dict[str, Any],
335
+ ) -> None:
336
+ """Add MCP servers to a built agent.
337
+
338
+ Args:
339
+ local_agent: The LangGraphReactAgent to add MCPs to.
340
+ agent: The glaip_sdk Agent with MCP definitions.
341
+ merged_mcp_configs: Merged mcp_configs (agent definition + runtime).
342
+ """
343
+ if not agent.mcps:
344
+ return
345
+
346
+ from glaip_sdk.runner.mcp_adapter import LangChainMCPAdapter # noqa: PLC0415
347
+
348
+ mcp_adapter = LangChainMCPAdapter()
349
+ base_mcp_configs = mcp_adapter.adapt_mcps(agent.mcps)
350
+
351
+ # Apply merged mcp_configs overrides (agent definition + runtime)
352
+ if merged_mcp_configs:
353
+ base_mcp_configs = self._apply_runtime_mcp_configs(base_mcp_configs, merged_mcp_configs)
354
+
355
+ if base_mcp_configs:
356
+ local_agent.add_mcp_server(base_mcp_configs)
357
+ logger.debug(
358
+ "Registered %d MCP server(s) for agent '%s'",
359
+ len(base_mcp_configs),
360
+ agent.name,
361
+ )
362
+
363
+ def _normalize_runtime_config(
364
+ self,
365
+ runtime_config: dict[str, Any] | None,
366
+ agent: Agent,
367
+ ) -> dict[str, Any]:
368
+ """Normalize runtime_config for local execution.
369
+
370
+ Merges global and agent-specific configs with proper priority.
371
+ Keys are resolved from instances/classes to string names.
372
+
373
+ Args:
374
+ runtime_config: Raw runtime config from user.
375
+ agent: The agent being built (for resolving agent-specific overrides).
376
+
377
+ Returns:
378
+ Normalized config with string keys and merged priorities.
379
+ """
380
+ from glaip_sdk.utils.runtime_config import ( # noqa: PLC0415
381
+ merge_configs,
382
+ normalize_local_config_keys,
383
+ )
384
+
385
+ if not runtime_config:
386
+ return {}
387
+
388
+ # 1. Extract global configs and normalize keys
389
+ global_tool_configs = normalize_local_config_keys(runtime_config.get("tool_configs", {}))
390
+ global_mcp_configs = normalize_local_config_keys(runtime_config.get("mcp_configs", {}))
391
+ global_agent_config = runtime_config.get("agent_config", {})
392
+
393
+ # 2. Extract agent-specific overrides (highest priority)
394
+ agent_specific = self._get_agent_specific_config(runtime_config, agent)
395
+ agent_tool_configs = normalize_local_config_keys(agent_specific.get("tool_configs", {}))
396
+ agent_mcp_configs = normalize_local_config_keys(agent_specific.get("mcp_configs", {}))
397
+ agent_config_override = agent_specific.get("agent_config", {})
398
+
399
+ # 3. Merge with priority: global < agent-specific
400
+ merged_result = {
401
+ "tool_configs": merge_configs(global_tool_configs, agent_tool_configs),
402
+ "mcp_configs": merge_configs(global_mcp_configs, agent_mcp_configs),
403
+ "agent_config": merge_configs(global_agent_config, agent_config_override),
404
+ }
405
+ return merged_result
406
+
407
+ def _get_agent_specific_config(
408
+ self,
409
+ runtime_config: dict[str, Any],
410
+ agent: Agent,
411
+ ) -> dict[str, Any]:
412
+ """Extract agent-specific config from runtime_config.
413
+
414
+ Args:
415
+ runtime_config: Runtime config that may contain agent-specific overrides.
416
+ agent: The agent to find config for.
417
+
418
+ Returns:
419
+ Agent-specific config dict, or empty dict if not found.
420
+ """
421
+ from glaip_sdk.utils.resource_refs import is_uuid # noqa: PLC0415
422
+ from glaip_sdk.utils.runtime_config import get_name_from_key # noqa: PLC0415
423
+
424
+ # Reserved keys at the top level
425
+ reserved_keys = {"tool_configs", "mcp_configs", "agent_config"}
426
+
427
+ # Try finding agent by instance, class, or name
428
+ for key, value in runtime_config.items():
429
+ if key in reserved_keys:
430
+ continue # Skip global configs
431
+
432
+ if isinstance(key, str) and is_uuid(key):
433
+ logger.warning(
434
+ "UUID agent override key '%s' is not supported in local mode; skipping. "
435
+ "Use agent name string or Agent instance as the key instead.",
436
+ key,
437
+ )
438
+ continue
439
+
440
+ # Check if this key matches the agent
441
+ try:
442
+ key_name = get_name_from_key(key)
443
+ except ValueError:
444
+ continue # Skip invalid keys
445
+
446
+ if key_name and key_name == agent.name:
447
+ return value if isinstance(value, dict) else {}
448
+
449
+ return {}
450
+
451
+ def _merge_tool_configs(
452
+ self,
453
+ agent: Agent,
454
+ normalized_config: dict[str, Any],
455
+ ) -> dict[str, Any]:
456
+ """Merge agent.tool_configs with runtime tool_configs.
457
+
458
+ Priority (lowest to highest):
459
+ 1. Agent definition (agent.tool_configs)
460
+ 2. Runtime config (normalized_config["tool_configs"])
461
+
462
+ Args:
463
+ agent: The agent with optional tool_configs property.
464
+ normalized_config: Normalized runtime config.
465
+
466
+ Returns:
467
+ Merged tool_configs dict.
468
+ """
469
+ from glaip_sdk.utils.runtime_config import ( # noqa: PLC0415
470
+ merge_configs,
471
+ normalize_local_config_keys,
472
+ )
473
+
474
+ # Get agent's tool_configs if defined
475
+ agent_tool_configs = {}
476
+ if hasattr(agent, "tool_configs") and agent.tool_configs:
477
+ agent_tool_configs = normalize_local_config_keys(agent.tool_configs)
478
+
479
+ # Get runtime tool_configs
480
+ runtime_tool_configs = normalized_config.get("tool_configs", {})
481
+
482
+ # Merge: agent definition < runtime config
483
+ return merge_configs(agent_tool_configs, runtime_tool_configs)
484
+
485
+ def _merge_mcp_configs(
486
+ self,
487
+ agent: Agent,
488
+ normalized_config: dict[str, Any],
489
+ ) -> dict[str, Any]:
490
+ """Merge agent.mcp_configs with runtime mcp_configs.
491
+
492
+ Priority (lowest to highest):
493
+ 1. Agent definition (agent.mcp_configs)
494
+ 2. Runtime config (normalized_config["mcp_configs"])
495
+
496
+ Args:
497
+ agent: The agent with optional mcp_configs property.
498
+ normalized_config: Normalized runtime config.
499
+
500
+ Returns:
501
+ Merged mcp_configs dict.
502
+ """
503
+ from glaip_sdk.utils.runtime_config import ( # noqa: PLC0415
504
+ merge_configs,
505
+ normalize_local_config_keys,
506
+ )
507
+
508
+ # Get agent's mcp_configs if defined
509
+ agent_mcp_configs = {}
510
+ if hasattr(agent, "mcp_configs") and agent.mcp_configs:
511
+ agent_mcp_configs = normalize_local_config_keys(agent.mcp_configs)
512
+
513
+ # Get runtime mcp_configs
514
+ runtime_mcp_configs = normalized_config.get("mcp_configs", {})
515
+
516
+ # Merge: agent definition < runtime config
517
+ return merge_configs(agent_mcp_configs, runtime_mcp_configs)
518
+
519
+ def _merge_agent_config(
520
+ self,
521
+ agent: Agent,
522
+ normalized_config: dict[str, Any],
523
+ ) -> dict[str, Any]:
524
+ """Merge agent.agent_config with runtime agent_config.
525
+
526
+ Priority (lowest to highest):
527
+ 1. Agent definition (agent.agent_config)
528
+ 2. Runtime config (normalized_config["agent_config"])
529
+
530
+ Args:
531
+ agent: The agent with optional agent_config property.
532
+ normalized_config: Normalized runtime config.
533
+
534
+ Returns:
535
+ Merged agent_config dict.
536
+ """
537
+ from glaip_sdk.utils.runtime_config import merge_configs # noqa: PLC0415
538
+
539
+ # Get agent's agent_config if defined
540
+ agent_agent_config = {}
541
+ if hasattr(agent, "agent_config") and agent.agent_config:
542
+ agent_agent_config = agent.agent_config
543
+
544
+ # Get runtime agent_config
545
+ runtime_agent_config = normalized_config.get("agent_config", {})
546
+
547
+ # Merge: agent definition < runtime config
548
+ return merge_configs(agent_agent_config, runtime_agent_config)
549
+
550
+ def _apply_agent_config(
551
+ self,
552
+ agent_config: dict[str, Any],
553
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
554
+ """Extract and separate agent_config into direct params and kwargs.
555
+
556
+ Separates agent_config into parameters that go directly to LangGraphReactAgent
557
+ constructor vs those that go through **kwargs.
558
+
559
+ Args:
560
+ agent_config: Runtime agent configuration dict.
561
+
562
+ Returns:
563
+ Tuple of (direct_params, kwargs_params):
564
+ - direct_params: Parameters passed directly to LangGraphReactAgent.__init__()
565
+ - kwargs_params: Parameters passed via **kwargs to BaseAgent
566
+ """
567
+ direct_params = {}
568
+ kwargs_params = {}
569
+
570
+ # Direct constructor parameters
571
+ if "planning" in agent_config:
572
+ direct_params["planning"] = agent_config["planning"]
573
+
574
+ # Kwargs parameters (passed through **kwargs to BaseAgent)
575
+ if "memory" in agent_config:
576
+ # Map "memory" to "memory_backend" for aip-agents compatibility
577
+ kwargs_params["memory_backend"] = agent_config["memory"]
578
+
579
+ # Additional memory-related settings
580
+ memory_settings = ["agent_id", "memory_namespace", "save_interaction_to_memory"]
581
+ for key in memory_settings:
582
+ if key in agent_config:
583
+ kwargs_params[key] = agent_config[key]
584
+
585
+ return direct_params, kwargs_params
586
+
587
+ def _apply_runtime_mcp_configs(
588
+ self,
589
+ base_configs: dict[str, Any],
590
+ runtime_overrides: dict[str, Any],
591
+ ) -> dict[str, Any]:
592
+ """Apply runtime mcp_configs overrides to base MCP configurations.
593
+
594
+ Merges runtime overrides into the base configs, handling authentication
595
+ conversion to headers using MCPConfigBuilder.
596
+
597
+ Args:
598
+ base_configs: Base MCP configs from adapter (server_name -> config).
599
+ runtime_overrides: Runtime mcp_configs overrides (server_name -> config).
600
+
601
+ Returns:
602
+ Merged MCP configs with authentication converted to headers.
603
+ """
604
+ return {
605
+ server_name: self._merge_single_mcp_config(server_name, base_config, runtime_overrides.get(server_name))
606
+ for server_name, base_config in base_configs.items()
607
+ }
608
+
609
+ def _merge_single_mcp_config(
610
+ self,
611
+ server_name: str,
612
+ base_config: dict[str, Any],
613
+ override: dict[str, Any] | None,
614
+ ) -> dict[str, Any]:
615
+ """Merge a single MCP config with runtime override.
616
+
617
+ Args:
618
+ server_name: Name of the MCP server.
619
+ base_config: Base config from adapter.
620
+ override: Optional runtime override config.
621
+
622
+ Returns:
623
+ Merged config dict.
624
+ """
625
+ merged = base_config.copy()
626
+
627
+ if not override:
628
+ return merged
629
+
630
+ from glaip_sdk.runner.mcp_adapter.mcp_config_builder import ( # noqa: PLC0415
631
+ MCPConfigBuilder,
632
+ )
633
+
634
+ # Handle authentication override
635
+ if "authentication" in override:
636
+ headers = MCPConfigBuilder.build_headers_from_auth(override["authentication"])
637
+ if headers:
638
+ merged["headers"] = headers
639
+ logger.debug("Applied runtime authentication headers for MCP '%s'", server_name)
640
+
641
+ # Merge other config keys (excluding authentication since we converted it)
642
+ for key, value in override.items():
643
+ if key != "authentication":
644
+ merged[key] = value
645
+
646
+ return merged
647
+
648
+ def _validate_sub_agent_for_local_mode(self, sub_agent: Any) -> None:
649
+ """Validate that a sub-agent reference is supported for local execution.
650
+
651
+ Args:
652
+ sub_agent: The sub-agent reference to validate.
653
+
654
+ Raises:
655
+ ValueError: If the sub-agent is not supported in local mode.
656
+ """
657
+ # String references are allowed by SDK API but not for local mode
658
+ if isinstance(sub_agent, str):
659
+ raise ValueError(
660
+ f"Sub-agent '{sub_agent}' is a string reference and cannot be used in local mode. "
661
+ "String sub-agent references are only supported for server execution. "
662
+ "For local mode, define the sub-agent with Agent(name=..., instruction=...)."
663
+ )
664
+
665
+ # Validate sub-agent is not a class
666
+ if inspect.isclass(sub_agent):
667
+ raise ValueError(
668
+ f"Sub-agent '{sub_agent.__name__}' is a class, not an instance. "
669
+ "Local mode requires Agent INSTANCES. "
670
+ "Did you forget to instantiate it? e.g., Agent(...), not Agent"
671
+ )
672
+
673
+ # Validate sub-agent is an Agent-like object (has required attributes)
674
+ if not hasattr(sub_agent, "name") or not hasattr(sub_agent, "instruction"):
675
+ raise ValueError(
676
+ f"Sub-agent {type(sub_agent).__name__} is not supported in local mode. "
677
+ "Local mode requires Agent instances with 'name' and 'instruction' attributes. "
678
+ "Define the sub-agent with Agent(name=..., instruction=...)."
679
+ )
680
+
681
+ # Validate sub-agent is not platform-only (from_id, from_native)
682
+ if getattr(sub_agent, "_lookup_only", False):
683
+ agent_name = getattr(sub_agent, "name", "<unknown>")
684
+ raise ValueError(
685
+ f"Sub-agent '{agent_name}' is not supported in local mode. "
686
+ "Platform agents (from_id, from_native) cannot be used as "
687
+ "sub-agents in local execution. "
688
+ "Define the sub-agent locally with Agent(name=..., instruction=...) instead."
689
+ )
690
+
691
+ def _log_event(self, event: dict[str, Any]) -> None:
692
+ """Log an A2AEvent for verbose debug output.
693
+
694
+ Args:
695
+ event: The A2AEvent dictionary to log.
696
+ """
697
+ event_type = event.get("event_type", "unknown")
698
+ content = event.get("content", "")
699
+ is_final = event.get("is_final", False)
700
+
701
+ # Truncate long content for readability
702
+ content_str = str(content) if content else ""
703
+ content_preview = content_str[:100] + "..." if len(content_str) > 100 else content_str
704
+
705
+ final_marker = "(final)" if is_final else ""
706
+ logger.info("[%s] %s %s", event_type, final_marker, content_preview)