glaip-sdk 0.1.3__py3-none-any.whl → 0.6.19__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.
Files changed (146) hide show
  1. glaip_sdk/__init__.py +44 -4
  2. glaip_sdk/_version.py +9 -0
  3. glaip_sdk/agents/__init__.py +27 -0
  4. glaip_sdk/agents/base.py +1196 -0
  5. glaip_sdk/branding.py +13 -0
  6. glaip_sdk/cli/account_store.py +540 -0
  7. glaip_sdk/cli/auth.py +254 -15
  8. glaip_sdk/cli/commands/__init__.py +2 -2
  9. glaip_sdk/cli/commands/accounts.py +746 -0
  10. glaip_sdk/cli/commands/agents.py +213 -73
  11. glaip_sdk/cli/commands/common_config.py +104 -0
  12. glaip_sdk/cli/commands/configure.py +729 -113
  13. glaip_sdk/cli/commands/mcps.py +241 -72
  14. glaip_sdk/cli/commands/models.py +11 -5
  15. glaip_sdk/cli/commands/tools.py +49 -57
  16. glaip_sdk/cli/commands/transcripts.py +755 -0
  17. glaip_sdk/cli/config.py +48 -4
  18. glaip_sdk/cli/constants.py +38 -0
  19. glaip_sdk/cli/context.py +8 -0
  20. glaip_sdk/cli/core/__init__.py +79 -0
  21. glaip_sdk/cli/core/context.py +124 -0
  22. glaip_sdk/cli/core/output.py +851 -0
  23. glaip_sdk/cli/core/prompting.py +649 -0
  24. glaip_sdk/cli/core/rendering.py +187 -0
  25. glaip_sdk/cli/display.py +35 -19
  26. glaip_sdk/cli/hints.py +57 -0
  27. glaip_sdk/cli/io.py +6 -3
  28. glaip_sdk/cli/main.py +241 -121
  29. glaip_sdk/cli/masking.py +21 -33
  30. glaip_sdk/cli/pager.py +9 -10
  31. glaip_sdk/cli/parsers/__init__.py +1 -3
  32. glaip_sdk/cli/slash/__init__.py +0 -9
  33. glaip_sdk/cli/slash/accounts_controller.py +578 -0
  34. glaip_sdk/cli/slash/accounts_shared.py +75 -0
  35. glaip_sdk/cli/slash/agent_session.py +62 -21
  36. glaip_sdk/cli/slash/prompt.py +21 -0
  37. glaip_sdk/cli/slash/remote_runs_controller.py +566 -0
  38. glaip_sdk/cli/slash/session.py +771 -140
  39. glaip_sdk/cli/slash/tui/__init__.py +9 -0
  40. glaip_sdk/cli/slash/tui/accounts.tcss +86 -0
  41. glaip_sdk/cli/slash/tui/accounts_app.py +876 -0
  42. glaip_sdk/cli/slash/tui/background_tasks.py +72 -0
  43. glaip_sdk/cli/slash/tui/loading.py +58 -0
  44. glaip_sdk/cli/slash/tui/remote_runs_app.py +628 -0
  45. glaip_sdk/cli/transcript/__init__.py +12 -52
  46. glaip_sdk/cli/transcript/cache.py +255 -44
  47. glaip_sdk/cli/transcript/capture.py +27 -1
  48. glaip_sdk/cli/transcript/history.py +815 -0
  49. glaip_sdk/cli/transcript/viewer.py +72 -499
  50. glaip_sdk/cli/update_notifier.py +14 -5
  51. glaip_sdk/cli/utils.py +243 -1252
  52. glaip_sdk/cli/validators.py +5 -6
  53. glaip_sdk/client/__init__.py +2 -1
  54. glaip_sdk/client/_agent_payloads.py +45 -9
  55. glaip_sdk/client/agent_runs.py +147 -0
  56. glaip_sdk/client/agents.py +291 -35
  57. glaip_sdk/client/base.py +1 -0
  58. glaip_sdk/client/main.py +19 -10
  59. glaip_sdk/client/mcps.py +122 -12
  60. glaip_sdk/client/run_rendering.py +466 -89
  61. glaip_sdk/client/shared.py +21 -0
  62. glaip_sdk/client/tools.py +155 -10
  63. glaip_sdk/config/constants.py +11 -0
  64. glaip_sdk/hitl/__init__.py +15 -0
  65. glaip_sdk/hitl/local.py +151 -0
  66. glaip_sdk/mcps/__init__.py +21 -0
  67. glaip_sdk/mcps/base.py +345 -0
  68. glaip_sdk/models/__init__.py +90 -0
  69. glaip_sdk/models/agent.py +47 -0
  70. glaip_sdk/models/agent_runs.py +116 -0
  71. glaip_sdk/models/common.py +42 -0
  72. glaip_sdk/models/mcp.py +33 -0
  73. glaip_sdk/models/tool.py +33 -0
  74. glaip_sdk/payload_schemas/__init__.py +1 -13
  75. glaip_sdk/registry/__init__.py +55 -0
  76. glaip_sdk/registry/agent.py +164 -0
  77. glaip_sdk/registry/base.py +139 -0
  78. glaip_sdk/registry/mcp.py +253 -0
  79. glaip_sdk/registry/tool.py +232 -0
  80. glaip_sdk/rich_components.py +58 -2
  81. glaip_sdk/runner/__init__.py +59 -0
  82. glaip_sdk/runner/base.py +84 -0
  83. glaip_sdk/runner/deps.py +112 -0
  84. glaip_sdk/runner/langgraph.py +870 -0
  85. glaip_sdk/runner/mcp_adapter/__init__.py +13 -0
  86. glaip_sdk/runner/mcp_adapter/base_mcp_adapter.py +43 -0
  87. glaip_sdk/runner/mcp_adapter/langchain_mcp_adapter.py +257 -0
  88. glaip_sdk/runner/mcp_adapter/mcp_config_builder.py +95 -0
  89. glaip_sdk/runner/tool_adapter/__init__.py +18 -0
  90. glaip_sdk/runner/tool_adapter/base_tool_adapter.py +44 -0
  91. glaip_sdk/runner/tool_adapter/langchain_tool_adapter.py +219 -0
  92. glaip_sdk/tools/__init__.py +22 -0
  93. glaip_sdk/tools/base.py +435 -0
  94. glaip_sdk/utils/__init__.py +58 -12
  95. glaip_sdk/utils/a2a/__init__.py +34 -0
  96. glaip_sdk/utils/a2a/event_processor.py +188 -0
  97. glaip_sdk/utils/bundler.py +267 -0
  98. glaip_sdk/utils/client.py +111 -0
  99. glaip_sdk/utils/client_utils.py +39 -7
  100. glaip_sdk/utils/datetime_helpers.py +58 -0
  101. glaip_sdk/utils/discovery.py +78 -0
  102. glaip_sdk/utils/display.py +23 -15
  103. glaip_sdk/utils/export.py +143 -0
  104. glaip_sdk/utils/general.py +0 -33
  105. glaip_sdk/utils/import_export.py +12 -7
  106. glaip_sdk/utils/import_resolver.py +492 -0
  107. glaip_sdk/utils/instructions.py +101 -0
  108. glaip_sdk/utils/rendering/__init__.py +115 -1
  109. glaip_sdk/utils/rendering/formatting.py +5 -30
  110. glaip_sdk/utils/rendering/layout/__init__.py +64 -0
  111. glaip_sdk/utils/rendering/{renderer → layout}/panels.py +9 -0
  112. glaip_sdk/utils/rendering/{renderer → layout}/progress.py +70 -1
  113. glaip_sdk/utils/rendering/layout/summary.py +74 -0
  114. glaip_sdk/utils/rendering/layout/transcript.py +606 -0
  115. glaip_sdk/utils/rendering/models.py +1 -0
  116. glaip_sdk/utils/rendering/renderer/__init__.py +9 -47
  117. glaip_sdk/utils/rendering/renderer/base.py +275 -1476
  118. glaip_sdk/utils/rendering/renderer/debug.py +26 -20
  119. glaip_sdk/utils/rendering/renderer/factory.py +138 -0
  120. glaip_sdk/utils/rendering/renderer/stream.py +4 -12
  121. glaip_sdk/utils/rendering/renderer/thinking.py +273 -0
  122. glaip_sdk/utils/rendering/renderer/tool_panels.py +442 -0
  123. glaip_sdk/utils/rendering/renderer/transcript_mode.py +162 -0
  124. glaip_sdk/utils/rendering/state.py +204 -0
  125. glaip_sdk/utils/rendering/steps/__init__.py +34 -0
  126. glaip_sdk/utils/rendering/{steps.py → steps/event_processor.py} +53 -440
  127. glaip_sdk/utils/rendering/steps/format.py +176 -0
  128. glaip_sdk/utils/rendering/steps/manager.py +387 -0
  129. glaip_sdk/utils/rendering/timing.py +36 -0
  130. glaip_sdk/utils/rendering/viewer/__init__.py +21 -0
  131. glaip_sdk/utils/rendering/viewer/presenter.py +184 -0
  132. glaip_sdk/utils/resource_refs.py +25 -13
  133. glaip_sdk/utils/runtime_config.py +425 -0
  134. glaip_sdk/utils/serialization.py +18 -0
  135. glaip_sdk/utils/sync.py +142 -0
  136. glaip_sdk/utils/tool_detection.py +33 -0
  137. glaip_sdk/utils/tool_storage_provider.py +140 -0
  138. glaip_sdk/utils/validation.py +16 -24
  139. {glaip_sdk-0.1.3.dist-info → glaip_sdk-0.6.19.dist-info}/METADATA +56 -21
  140. glaip_sdk-0.6.19.dist-info/RECORD +163 -0
  141. {glaip_sdk-0.1.3.dist-info → glaip_sdk-0.6.19.dist-info}/WHEEL +2 -1
  142. glaip_sdk-0.6.19.dist-info/entry_points.txt +2 -0
  143. glaip_sdk-0.6.19.dist-info/top_level.txt +1 -0
  144. glaip_sdk/models.py +0 -240
  145. glaip_sdk-0.1.3.dist-info/RECORD +0 -83
  146. glaip_sdk-0.1.3.dist-info/entry_points.txt +0 -3
@@ -0,0 +1,870 @@
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
+ import logging
23
+ from dataclasses import dataclass
24
+ from typing import TYPE_CHECKING, Any
25
+
26
+ from aip_agents.agent.hitl.manager import ApprovalManager # noqa: PLC0415
27
+ from gllm_core.utils import LoggerManager
28
+
29
+ from glaip_sdk.client.run_rendering import AgentRunRenderingManager
30
+ from glaip_sdk.hitl import LocalPromptHandler, PauseResumeCallback
31
+ from glaip_sdk.runner.base import BaseRunner
32
+ from glaip_sdk.runner.deps import (
33
+ check_local_runtime_available,
34
+ get_local_runtime_missing_message,
35
+ )
36
+ from glaip_sdk.utils.tool_storage_provider import build_tool_output_manager
37
+
38
+ if TYPE_CHECKING:
39
+ from langchain_core.messages import BaseMessage
40
+
41
+ from glaip_sdk.agents.base import Agent
42
+
43
+
44
+ _AIP_LOGS_SWALLOWED = False
45
+
46
+
47
+ def _swallow_aip_logs(level: int = logging.ERROR) -> None:
48
+ """Consume noisy AIPAgents logs once (opt-in via runner flag)."""
49
+ global _AIP_LOGS_SWALLOWED
50
+ if _AIP_LOGS_SWALLOWED:
51
+ return
52
+ prefixes = ("aip_agents.",)
53
+
54
+ def _silence(name: str) -> None:
55
+ lg = logging.getLogger(name)
56
+ lg.handlers = [logging.NullHandler()]
57
+ lg.propagate = False
58
+ lg.setLevel(level)
59
+
60
+ # Silence any already-registered loggers under the given prefixes
61
+ for logger_name in logging.root.manager.loggerDict:
62
+ if any(logger_name.startswith(prefix) for prefix in prefixes):
63
+ _silence(logger_name)
64
+
65
+ # Also set the base prefix loggers so future children inherit silence
66
+ for prefix in prefixes:
67
+ _silence(prefix.rstrip("."))
68
+ _AIP_LOGS_SWALLOWED = True
69
+
70
+
71
+ logger = LoggerManager().get_logger(__name__)
72
+
73
+
74
+ def _convert_chat_history_to_messages(
75
+ chat_history: list[dict[str, str]] | None,
76
+ ) -> list[BaseMessage]:
77
+ """Convert chat history dicts to LangChain messages.
78
+
79
+ Args:
80
+ chat_history: List of dicts with "role" and "content" keys.
81
+ Supported roles: "user"/"human", "assistant"/"ai", "system".
82
+
83
+ Returns:
84
+ List of LangChain BaseMessage instances.
85
+ """
86
+ if not chat_history:
87
+ return []
88
+
89
+ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage # noqa: PLC0415
90
+
91
+ messages: list[BaseMessage] = []
92
+ for msg in chat_history:
93
+ role = msg.get("role", "").lower()
94
+ content = msg.get("content", "")
95
+
96
+ if role in ("user", "human"):
97
+ messages.append(HumanMessage(content=content))
98
+ elif role in ("assistant", "ai"):
99
+ messages.append(AIMessage(content=content))
100
+ elif role == "system":
101
+ messages.append(SystemMessage(content=content))
102
+ else:
103
+ # Default to human message for unknown roles
104
+ logger.warning("Unknown chat history role '%s', treating as user message", role)
105
+ messages.append(HumanMessage(content=content))
106
+
107
+ return messages
108
+
109
+
110
+ @dataclass(frozen=True, slots=True)
111
+ class LangGraphRunner(BaseRunner):
112
+ """Runner implementation using aip-agents LangGraphReactAgent.
113
+
114
+ Current behavior:
115
+ - Execute via `LangGraphReactAgent.arun_sse_stream()` (normalized SSE-compatible stream)
116
+ - Route all events through `AgentRunRenderingManager.async_process_stream_events`
117
+ for unified rendering between local and remote agents
118
+
119
+ Attributes:
120
+ default_model: Model name to use when agent.model is not set.
121
+ Defaults to "gpt-4o-mini".
122
+ """
123
+
124
+ default_model: str = "openai/gpt-4o-mini"
125
+
126
+ def run(
127
+ self,
128
+ agent: Agent,
129
+ message: str,
130
+ verbose: bool = False,
131
+ runtime_config: dict[str, Any] | None = None,
132
+ chat_history: list[dict[str, str]] | None = None,
133
+ *,
134
+ swallow_aip_logs: bool = True,
135
+ **kwargs: Any,
136
+ ) -> str:
137
+ """Execute agent synchronously and return final response text.
138
+
139
+ Args:
140
+ agent: The glaip_sdk Agent to execute.
141
+ message: The user message to send to the agent.
142
+ verbose: If True, emit debug trace output during execution.
143
+ Defaults to False.
144
+ runtime_config: Optional runtime configuration for tools, MCPs, etc.
145
+ Defaults to None. (Implemented in PR-04+)
146
+ chat_history: Optional list of prior conversation messages.
147
+ Each message is a dict with "role" and "content" keys.
148
+ Defaults to None.
149
+ swallow_aip_logs: When True (default), silence noisy logs from aip-agents,
150
+ gllm_inference, OpenAILMInvoker, and httpx. Set to False to honor user
151
+ logging configuration.
152
+ **kwargs: Additional keyword arguments passed to the backend.
153
+
154
+ Returns:
155
+ The final response text from the agent.
156
+
157
+ Raises:
158
+ RuntimeError: If the local runtime dependencies are not available.
159
+ RuntimeError: If no final response is received from the agent.
160
+ """
161
+ if not check_local_runtime_available():
162
+ raise RuntimeError(get_local_runtime_missing_message())
163
+
164
+ try:
165
+ asyncio.get_running_loop()
166
+ except RuntimeError:
167
+ pass
168
+ else:
169
+ raise RuntimeError(
170
+ "LangGraphRunner.run() cannot be called from a running event loop. "
171
+ "Use 'await LangGraphRunner.arun(...)' instead."
172
+ )
173
+
174
+ coro = self._arun_internal(
175
+ agent=agent,
176
+ message=message,
177
+ verbose=verbose,
178
+ runtime_config=runtime_config,
179
+ chat_history=chat_history,
180
+ swallow_aip_logs=swallow_aip_logs,
181
+ **kwargs,
182
+ )
183
+
184
+ return asyncio.run(coro)
185
+
186
+ async def arun(
187
+ self,
188
+ agent: Agent,
189
+ message: str,
190
+ verbose: bool = False,
191
+ runtime_config: dict[str, Any] | None = None,
192
+ chat_history: list[dict[str, str]] | None = None,
193
+ *,
194
+ swallow_aip_logs: bool = True,
195
+ **kwargs: Any,
196
+ ) -> str:
197
+ """Execute agent asynchronously and return final response text.
198
+
199
+ Args:
200
+ agent: The glaip_sdk Agent to execute.
201
+ message: The user message to send to the agent.
202
+ verbose: If True, emit debug trace output during execution.
203
+ Defaults to False.
204
+ runtime_config: Optional runtime configuration for tools, MCPs, etc.
205
+ Defaults to None. (Implemented in PR-04+)
206
+ chat_history: Optional list of prior conversation messages.
207
+ Each message is a dict with "role" and "content" keys.
208
+ Defaults to None.
209
+ swallow_aip_logs: When True (default), silence noisy AIPAgents logs.
210
+ **kwargs: Additional keyword arguments passed to the backend.
211
+
212
+ Returns:
213
+ The final response text from the agent.
214
+
215
+ Raises:
216
+ RuntimeError: If no final response is received from the agent.
217
+ """
218
+ return await self._arun_internal(
219
+ agent=agent,
220
+ message=message,
221
+ verbose=verbose,
222
+ runtime_config=runtime_config,
223
+ chat_history=chat_history,
224
+ swallow_aip_logs=swallow_aip_logs,
225
+ **kwargs,
226
+ )
227
+
228
+ async def _arun_internal(
229
+ self,
230
+ agent: Agent,
231
+ message: str,
232
+ verbose: bool = False,
233
+ runtime_config: dict[str, Any] | None = None,
234
+ chat_history: list[dict[str, str]] | None = None,
235
+ *,
236
+ swallow_aip_logs: bool = True,
237
+ **kwargs: Any,
238
+ ) -> str:
239
+ """Internal async implementation of agent execution.
240
+
241
+ Args:
242
+ agent: The glaip_sdk Agent to execute.
243
+ message: The user message to send to the agent.
244
+ verbose: If True, emit debug trace output during execution.
245
+ runtime_config: Optional runtime configuration for tools, MCPs, etc.
246
+ chat_history: Optional list of prior conversation messages.
247
+ swallow_aip_logs: When True (default), silence noisy AIPAgents logs.
248
+ **kwargs: Additional keyword arguments passed to the backend.
249
+
250
+ Returns:
251
+ The final response text from the agent.
252
+ """
253
+ # Optionally swallow noisy AIPAgents logs
254
+ if swallow_aip_logs:
255
+ _swallow_aip_logs()
256
+
257
+ # POC/MVP: Create pause/resume callback for interactive HITL input
258
+ pause_resume_callback = PauseResumeCallback()
259
+
260
+ # Build the local LangGraphReactAgent from the glaip_sdk Agent
261
+ local_agent = self.build_langgraph_agent(
262
+ agent, runtime_config=runtime_config, pause_resume_callback=pause_resume_callback
263
+ )
264
+
265
+ # Convert chat history to LangChain messages for the agent
266
+ langchain_messages = _convert_chat_history_to_messages(chat_history)
267
+ if langchain_messages:
268
+ kwargs["messages"] = langchain_messages
269
+ logger.debug(
270
+ "Passing %d chat history messages to agent '%s'",
271
+ len(langchain_messages),
272
+ agent.name,
273
+ )
274
+
275
+ # Use shared render manager for unified processing
276
+ render_manager = AgentRunRenderingManager(logger)
277
+ renderer = render_manager.create_renderer(kwargs.get("renderer"), verbose=verbose)
278
+
279
+ # POC/MVP: Set renderer on callback so LocalPromptHandler can pause/resume Live
280
+ pause_resume_callback.set_renderer(renderer)
281
+
282
+ meta = render_manager.build_initial_metadata(agent.name, message, kwargs)
283
+ render_manager.start_renderer(renderer, meta)
284
+
285
+ try:
286
+ # Use shared async stream processor for unified event handling
287
+ (
288
+ final_text,
289
+ stats_usage,
290
+ started_monotonic,
291
+ finished_monotonic,
292
+ ) = await render_manager.async_process_stream_events(
293
+ local_agent.arun_sse_stream(message, **kwargs),
294
+ renderer,
295
+ meta,
296
+ skip_final_render=True,
297
+ )
298
+ except KeyboardInterrupt:
299
+ try:
300
+ renderer.close()
301
+ finally:
302
+ raise
303
+ except Exception:
304
+ try:
305
+ renderer.close()
306
+ finally:
307
+ raise
308
+
309
+ # Use shared finalizer to avoid code duplication
310
+ from glaip_sdk.client.run_rendering import finalize_render_manager # noqa: PLC0415
311
+
312
+ return finalize_render_manager(
313
+ render_manager, renderer, final_text, stats_usage, started_monotonic, finished_monotonic
314
+ )
315
+
316
+ def build_langgraph_agent(
317
+ self,
318
+ agent: Agent,
319
+ runtime_config: dict[str, Any] | None = None,
320
+ shared_tool_output_manager: Any | None = None,
321
+ *,
322
+ pause_resume_callback: Any | None = None,
323
+ ) -> Any:
324
+ """Build a LangGraphReactAgent from a glaip_sdk Agent definition.
325
+
326
+ Args:
327
+ agent: The glaip_sdk Agent to convert.
328
+ runtime_config: Optional runtime configuration with tool_configs,
329
+ mcp_configs, agent_config, and agent-specific overrides.
330
+ shared_tool_output_manager: Optional ToolOutputManager to reuse across
331
+ agents with tool_output_sharing enabled.
332
+ pause_resume_callback: Optional callback used to pause/resume the renderer
333
+ during interactive HITL prompts.
334
+
335
+ Returns:
336
+ A configured LangGraphReactAgent instance.
337
+
338
+ Raises:
339
+ ImportError: If aip-agents is not installed.
340
+ ValueError: If agent has unsupported tools, MCPs, or sub-agents for local mode.
341
+ """
342
+ from aip_agents.agent import LangGraphReactAgent # noqa: PLC0415
343
+
344
+ from glaip_sdk.runner.tool_adapter import LangChainToolAdapter # noqa: PLC0415
345
+
346
+ # Adapt tools for local execution
347
+ # NOTE: CLI parity waiver - local tool execution is SDK-only for MVP.
348
+ # See specs/f/local-agent-runtime/plan.md: "CLI parity is explicitly deferred
349
+ # and will require SDK Technical Lead sign-off per constitution principle IV."
350
+ langchain_tools: list[Any] = []
351
+ if agent.tools:
352
+ adapter = LangChainToolAdapter()
353
+ langchain_tools = adapter.adapt_tools(agent.tools)
354
+
355
+ # Normalize runtime config: merge global and agent-specific configs
356
+ normalized_config = self._normalize_runtime_config(runtime_config, agent)
357
+
358
+ # Merge tool_configs: agent definition < runtime config
359
+ tool_configs = self._merge_tool_configs(agent, normalized_config)
360
+
361
+ # Merge mcp_configs: agent definition < runtime config
362
+ mcp_configs = self._merge_mcp_configs(agent, normalized_config)
363
+
364
+ # Merge agent_config: agent definition < runtime config
365
+ merged_agent_config = self._merge_agent_config(agent, normalized_config)
366
+ agent_config_params, agent_config_kwargs = self._apply_agent_config(merged_agent_config)
367
+
368
+ tool_output_manager = self._resolve_tool_output_manager(
369
+ agent,
370
+ merged_agent_config,
371
+ shared_tool_output_manager,
372
+ )
373
+
374
+ # Build sub-agents recursively, sharing tool output manager when enabled.
375
+ sub_agent_instances = self._build_sub_agents(
376
+ agent.agents,
377
+ runtime_config,
378
+ shared_tool_output_manager=tool_output_manager,
379
+ )
380
+
381
+ # Build the LangGraphReactAgent with tools, sub-agents, and configs
382
+ local_agent = LangGraphReactAgent(
383
+ name=agent.name,
384
+ instruction=agent.instruction,
385
+ description=agent.description,
386
+ model=agent.model or self.default_model,
387
+ tools=langchain_tools,
388
+ agents=sub_agent_instances if sub_agent_instances else None,
389
+ tool_configs=tool_configs if tool_configs else None,
390
+ tool_output_manager=tool_output_manager,
391
+ **agent_config_params,
392
+ **agent_config_kwargs,
393
+ )
394
+
395
+ # Add MCP servers if configured
396
+ self._add_mcp_servers(local_agent, agent, mcp_configs)
397
+
398
+ # Inject local HITL manager only if hitl_enabled is True (master switch).
399
+ # This matches remote behavior: hitl_enabled gates the HITL plumbing.
400
+ # Tool-level HITL configs are only enforced when hitl_enabled=True.
401
+ self._inject_hitl_manager(local_agent, merged_agent_config, agent.name, pause_resume_callback)
402
+
403
+ logger.debug(
404
+ "Built local LangGraphReactAgent for agent '%s' with %d tools, %d sub-agents, and %d MCPs",
405
+ agent.name,
406
+ len(langchain_tools),
407
+ len(sub_agent_instances),
408
+ len(agent.mcps) if agent.mcps else 0,
409
+ )
410
+ return local_agent
411
+
412
+ def _resolve_tool_output_manager(
413
+ self,
414
+ agent: Agent,
415
+ merged_agent_config: dict[str, Any],
416
+ shared_tool_output_manager: Any | None,
417
+ ) -> Any | None:
418
+ """Resolve tool output manager for local agent execution."""
419
+ tool_output_sharing_enabled = merged_agent_config.get("tool_output_sharing", False)
420
+ if not tool_output_sharing_enabled:
421
+ return None
422
+ if shared_tool_output_manager is not None:
423
+ return shared_tool_output_manager
424
+ return build_tool_output_manager(agent.name, merged_agent_config)
425
+
426
+ def _inject_hitl_manager(
427
+ self,
428
+ local_agent: Any,
429
+ merged_agent_config: dict[str, Any],
430
+ agent_name: str,
431
+ pause_resume_callback: Any | None,
432
+ ) -> None:
433
+ """Inject HITL manager when enabled, mirroring remote gating behavior."""
434
+ hitl_enabled = merged_agent_config.get("hitl_enabled", False)
435
+ if hitl_enabled:
436
+ try:
437
+ local_agent.hitl_manager = ApprovalManager(
438
+ prompt_handler=LocalPromptHandler(pause_resume_callback=pause_resume_callback)
439
+ )
440
+ # Store callback reference for setting renderer later
441
+ if pause_resume_callback:
442
+ local_agent._pause_resume_callback = pause_resume_callback
443
+ logger.debug("HITL manager injected for agent '%s' (hitl_enabled=True)", agent_name)
444
+ except ImportError as e:
445
+ # Missing dependencies - fail fast
446
+ raise ImportError("Local HITL requires aip_agents. Install with: pip install 'glaip-sdk[local]'") from e
447
+ except Exception as e:
448
+ # Other errors during HITL setup - fail fast
449
+ raise RuntimeError(f"Failed to initialize HITL manager for agent '{agent_name}'") from e
450
+ else:
451
+ logger.debug("HITL manager not injected for agent '%s' (hitl_enabled=False)", agent_name)
452
+
453
+ def _build_sub_agents(
454
+ self,
455
+ sub_agents: list[Any] | None,
456
+ runtime_config: dict[str, Any] | None,
457
+ shared_tool_output_manager: Any | None = None,
458
+ ) -> list[Any]:
459
+ """Build sub-agent instances recursively.
460
+
461
+ Args:
462
+ sub_agents: List of sub-agent definitions.
463
+ runtime_config: Runtime config to pass to sub-agents.
464
+ shared_tool_output_manager: Optional ToolOutputManager to reuse across
465
+ agents with tool_output_sharing enabled.
466
+
467
+ Returns:
468
+ List of built sub-agent instances.
469
+
470
+ Raises:
471
+ ValueError: If sub-agent is platform-only.
472
+ """
473
+ if not sub_agents:
474
+ return []
475
+
476
+ sub_agent_instances = []
477
+ for sub_agent in sub_agents:
478
+ self._validate_sub_agent_for_local_mode(sub_agent)
479
+ sub_agent_instances.append(
480
+ self.build_langgraph_agent(
481
+ sub_agent,
482
+ runtime_config,
483
+ shared_tool_output_manager=shared_tool_output_manager,
484
+ )
485
+ )
486
+ return sub_agent_instances
487
+
488
+ def _add_mcp_servers(
489
+ self,
490
+ local_agent: Any,
491
+ agent: Agent,
492
+ merged_mcp_configs: dict[str, Any],
493
+ ) -> None:
494
+ """Add MCP servers to a built agent.
495
+
496
+ Args:
497
+ local_agent: The LangGraphReactAgent to add MCPs to.
498
+ agent: The glaip_sdk Agent with MCP definitions.
499
+ merged_mcp_configs: Merged mcp_configs (agent definition + runtime).
500
+ """
501
+ if not agent.mcps:
502
+ return
503
+
504
+ from glaip_sdk.runner.mcp_adapter import LangChainMCPAdapter # noqa: PLC0415
505
+
506
+ mcp_adapter = LangChainMCPAdapter()
507
+ base_mcp_configs = mcp_adapter.adapt_mcps(agent.mcps)
508
+
509
+ # Apply merged mcp_configs overrides (agent definition + runtime)
510
+ if merged_mcp_configs:
511
+ base_mcp_configs = self._apply_runtime_mcp_configs(base_mcp_configs, merged_mcp_configs)
512
+
513
+ if base_mcp_configs:
514
+ local_agent.add_mcp_server(base_mcp_configs)
515
+ logger.debug(
516
+ "Registered %d MCP server(s) for agent '%s'",
517
+ len(base_mcp_configs),
518
+ agent.name,
519
+ )
520
+
521
+ def _normalize_runtime_config(
522
+ self,
523
+ runtime_config: dict[str, Any] | None,
524
+ agent: Agent,
525
+ ) -> dict[str, Any]:
526
+ """Normalize runtime_config for local execution.
527
+
528
+ Merges global and agent-specific configs with proper priority.
529
+ Keys are resolved from instances/classes to string names.
530
+
531
+ Args:
532
+ runtime_config: Raw runtime config from user.
533
+ agent: The agent being built (for resolving agent-specific overrides).
534
+
535
+ Returns:
536
+ Normalized config with string keys and merged priorities.
537
+ """
538
+ from glaip_sdk.utils.runtime_config import ( # noqa: PLC0415
539
+ merge_configs,
540
+ normalize_local_config_keys,
541
+ )
542
+
543
+ if not runtime_config:
544
+ return {}
545
+
546
+ # 1. Extract global configs and normalize keys
547
+ global_tool_configs = normalize_local_config_keys(runtime_config.get("tool_configs", {}))
548
+ global_mcp_configs = normalize_local_config_keys(runtime_config.get("mcp_configs", {}))
549
+ global_agent_config = runtime_config.get("agent_config", {})
550
+
551
+ # 2. Extract agent-specific overrides (highest priority)
552
+ agent_specific = self._get_agent_specific_config(runtime_config, agent)
553
+ agent_tool_configs = normalize_local_config_keys(agent_specific.get("tool_configs", {}))
554
+ agent_mcp_configs = normalize_local_config_keys(agent_specific.get("mcp_configs", {}))
555
+ agent_config_override = agent_specific.get("agent_config", {})
556
+
557
+ # 3. Merge with priority: global < agent-specific
558
+ merged_result = {
559
+ "tool_configs": merge_configs(global_tool_configs, agent_tool_configs),
560
+ "mcp_configs": merge_configs(global_mcp_configs, agent_mcp_configs),
561
+ "agent_config": merge_configs(global_agent_config, agent_config_override),
562
+ }
563
+ return merged_result
564
+
565
+ def _get_agent_specific_config(
566
+ self,
567
+ runtime_config: dict[str, Any],
568
+ agent: Agent,
569
+ ) -> dict[str, Any]:
570
+ """Extract agent-specific config from runtime_config.
571
+
572
+ Args:
573
+ runtime_config: Runtime config that may contain agent-specific overrides.
574
+ agent: The agent to find config for.
575
+
576
+ Returns:
577
+ Agent-specific config dict, or empty dict if not found.
578
+ """
579
+ from glaip_sdk.utils.resource_refs import is_uuid # noqa: PLC0415
580
+ from glaip_sdk.utils.runtime_config import get_name_from_key # noqa: PLC0415
581
+
582
+ # Reserved keys at the top level
583
+ reserved_keys = {"tool_configs", "mcp_configs", "agent_config"}
584
+
585
+ # Try finding agent by instance, class, or name
586
+ for key, value in runtime_config.items():
587
+ if key in reserved_keys:
588
+ continue # Skip global configs
589
+
590
+ if isinstance(key, str) and is_uuid(key):
591
+ logger.warning(
592
+ "UUID agent override key '%s' is not supported in local mode; skipping. "
593
+ "Use agent name string or Agent instance as the key instead.",
594
+ key,
595
+ )
596
+ continue
597
+
598
+ # Check if this key matches the agent
599
+ try:
600
+ key_name = get_name_from_key(key)
601
+ except ValueError:
602
+ continue # Skip invalid keys
603
+
604
+ if key_name and key_name == agent.name:
605
+ return value if isinstance(value, dict) else {}
606
+
607
+ return {}
608
+
609
+ def _merge_tool_configs(
610
+ self,
611
+ agent: Agent,
612
+ normalized_config: dict[str, Any],
613
+ ) -> dict[str, Any]:
614
+ """Merge agent.tool_configs with runtime tool_configs.
615
+
616
+ Priority (lowest to highest):
617
+ 1. Agent definition (agent.tool_configs)
618
+ 2. Runtime config (normalized_config["tool_configs"])
619
+
620
+ Args:
621
+ agent: The agent with optional tool_configs property.
622
+ normalized_config: Normalized runtime config.
623
+
624
+ Returns:
625
+ Merged tool_configs dict.
626
+ """
627
+ from glaip_sdk.utils.runtime_config import ( # noqa: PLC0415
628
+ merge_configs,
629
+ normalize_local_config_keys,
630
+ )
631
+
632
+ # Get agent's tool_configs if defined
633
+ agent_tool_configs = {}
634
+ if hasattr(agent, "tool_configs") and agent.tool_configs:
635
+ agent_tool_configs = normalize_local_config_keys(agent.tool_configs)
636
+
637
+ # Get runtime tool_configs
638
+ runtime_tool_configs = normalized_config.get("tool_configs", {})
639
+
640
+ # Merge: agent definition < runtime config
641
+ return merge_configs(agent_tool_configs, runtime_tool_configs)
642
+
643
+ def _merge_mcp_configs(
644
+ self,
645
+ agent: Agent,
646
+ normalized_config: dict[str, Any],
647
+ ) -> dict[str, Any]:
648
+ """Merge agent.mcp_configs with runtime mcp_configs.
649
+
650
+ Priority (lowest to highest):
651
+ 1. Agent definition (agent.mcp_configs)
652
+ 2. Runtime config (normalized_config["mcp_configs"])
653
+
654
+ Args:
655
+ agent: The agent with optional mcp_configs property.
656
+ normalized_config: Normalized runtime config.
657
+
658
+ Returns:
659
+ Merged mcp_configs dict.
660
+ """
661
+ from glaip_sdk.utils.runtime_config import ( # noqa: PLC0415
662
+ merge_configs,
663
+ normalize_local_config_keys,
664
+ )
665
+
666
+ # Get agent's mcp_configs if defined
667
+ agent_mcp_configs = {}
668
+ if hasattr(agent, "mcp_configs") and agent.mcp_configs:
669
+ agent_mcp_configs = normalize_local_config_keys(agent.mcp_configs)
670
+
671
+ # Get runtime mcp_configs
672
+ runtime_mcp_configs = normalized_config.get("mcp_configs", {})
673
+
674
+ # Merge: agent definition < runtime config
675
+ return merge_configs(agent_mcp_configs, runtime_mcp_configs)
676
+
677
+ def _merge_agent_config(
678
+ self,
679
+ agent: Agent,
680
+ normalized_config: dict[str, Any],
681
+ ) -> dict[str, Any]:
682
+ """Merge agent.agent_config with runtime agent_config.
683
+
684
+ Priority (lowest to highest):
685
+ 1. Agent definition (agent.agent_config)
686
+ 2. Runtime config (normalized_config["agent_config"])
687
+
688
+ Args:
689
+ agent: The agent with optional agent_config property.
690
+ normalized_config: Normalized runtime config.
691
+
692
+ Returns:
693
+ Merged agent_config dict.
694
+ """
695
+ from glaip_sdk.utils.runtime_config import merge_configs # noqa: PLC0415
696
+
697
+ # Get agent's agent_config if defined
698
+ agent_agent_config = {}
699
+ if hasattr(agent, "agent_config") and agent.agent_config:
700
+ agent_agent_config = agent.agent_config
701
+
702
+ # Get runtime agent_config
703
+ runtime_agent_config = normalized_config.get("agent_config", {})
704
+
705
+ # Merge: agent definition < runtime config
706
+ return merge_configs(agent_agent_config, runtime_agent_config)
707
+
708
+ def _apply_agent_config(
709
+ self,
710
+ agent_config: dict[str, Any],
711
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
712
+ """Extract and separate agent_config into direct params and kwargs.
713
+
714
+ Separates agent_config into parameters that go directly to LangGraphReactAgent
715
+ constructor vs those that go through **kwargs.
716
+
717
+ Args:
718
+ agent_config: Runtime agent configuration dict.
719
+
720
+ Returns:
721
+ Tuple of (direct_params, kwargs_params):
722
+ - direct_params: Parameters passed directly to LangGraphReactAgent.__init__()
723
+ - kwargs_params: Parameters passed via **kwargs to BaseAgent
724
+ """
725
+ direct_params = {}
726
+ kwargs_params = {}
727
+
728
+ # Direct constructor parameters
729
+ if "planning" in agent_config:
730
+ direct_params["planning"] = agent_config["planning"]
731
+
732
+ if "enable_a2a_token_streaming" in agent_config:
733
+ direct_params["enable_a2a_token_streaming"] = agent_config["enable_a2a_token_streaming"]
734
+
735
+ # Kwargs parameters (passed through **kwargs to BaseAgent)
736
+ if "enable_pii" in agent_config:
737
+ kwargs_params["enable_pii"] = agent_config["enable_pii"]
738
+
739
+ if "memory" in agent_config:
740
+ # Map "memory" to "memory_backend" for aip-agents compatibility
741
+ kwargs_params["memory_backend"] = agent_config["memory"]
742
+
743
+ # Additional memory-related settings
744
+ memory_settings = ["agent_id", "memory_namespace", "save_interaction_to_memory"]
745
+ for key in memory_settings:
746
+ if key in agent_config:
747
+ kwargs_params[key] = agent_config[key]
748
+
749
+ return direct_params, kwargs_params
750
+
751
+ def _apply_runtime_mcp_configs(
752
+ self,
753
+ base_configs: dict[str, Any],
754
+ runtime_overrides: dict[str, Any],
755
+ ) -> dict[str, Any]:
756
+ """Apply runtime mcp_configs overrides to base MCP configurations.
757
+
758
+ Merges runtime overrides into the base configs, handling authentication
759
+ conversion to headers using MCPConfigBuilder.
760
+
761
+ Args:
762
+ base_configs: Base MCP configs from adapter (server_name -> config).
763
+ runtime_overrides: Runtime mcp_configs overrides (server_name -> config).
764
+
765
+ Returns:
766
+ Merged MCP configs with authentication converted to headers.
767
+ """
768
+ return {
769
+ server_name: self._merge_single_mcp_config(server_name, base_config, runtime_overrides.get(server_name))
770
+ for server_name, base_config in base_configs.items()
771
+ }
772
+
773
+ def _merge_single_mcp_config(
774
+ self,
775
+ server_name: str,
776
+ base_config: dict[str, Any],
777
+ override: dict[str, Any] | None,
778
+ ) -> dict[str, Any]:
779
+ """Merge a single MCP config with runtime override.
780
+
781
+ Args:
782
+ server_name: Name of the MCP server.
783
+ base_config: Base config from adapter.
784
+ override: Optional runtime override config.
785
+
786
+ Returns:
787
+ Merged config dict.
788
+ """
789
+ merged = base_config.copy()
790
+
791
+ if not override:
792
+ return merged
793
+
794
+ from glaip_sdk.runner.mcp_adapter.mcp_config_builder import ( # noqa: PLC0415
795
+ MCPConfigBuilder,
796
+ )
797
+
798
+ # Handle authentication override
799
+ if "authentication" in override:
800
+ headers = MCPConfigBuilder.build_headers_from_auth(override["authentication"])
801
+ if headers:
802
+ merged["headers"] = headers
803
+ logger.debug("Applied runtime authentication headers for MCP '%s'", server_name)
804
+
805
+ # Merge other config keys (excluding authentication since we converted it)
806
+ for key, value in override.items():
807
+ if key != "authentication":
808
+ merged[key] = value
809
+
810
+ return merged
811
+
812
+ def _validate_sub_agent_for_local_mode(self, sub_agent: Any) -> None:
813
+ """Validate that a sub-agent reference is supported for local execution.
814
+
815
+ Args:
816
+ sub_agent: The sub-agent reference to validate.
817
+
818
+ Raises:
819
+ ValueError: If the sub-agent is not supported in local mode.
820
+ """
821
+ # String references are allowed by SDK API but not for local mode
822
+ if isinstance(sub_agent, str):
823
+ raise ValueError(
824
+ f"Sub-agent '{sub_agent}' is a string reference and cannot be used in local mode. "
825
+ "String sub-agent references are only supported for server execution. "
826
+ "For local mode, define the sub-agent with Agent(name=..., instruction=...)."
827
+ )
828
+
829
+ # Validate sub-agent is not a class
830
+ if inspect.isclass(sub_agent):
831
+ raise ValueError(
832
+ f"Sub-agent '{sub_agent.__name__}' is a class, not an instance. "
833
+ "Local mode requires Agent INSTANCES. "
834
+ "Did you forget to instantiate it? e.g., Agent(...), not Agent"
835
+ )
836
+
837
+ # Validate sub-agent is an Agent-like object (has required attributes)
838
+ if not hasattr(sub_agent, "name") or not hasattr(sub_agent, "instruction"):
839
+ raise ValueError(
840
+ f"Sub-agent {type(sub_agent).__name__} is not supported in local mode. "
841
+ "Local mode requires Agent instances with 'name' and 'instruction' attributes. "
842
+ "Define the sub-agent with Agent(name=..., instruction=...)."
843
+ )
844
+
845
+ # Validate sub-agent is not platform-only (from_id, from_native)
846
+ if getattr(sub_agent, "_lookup_only", False):
847
+ agent_name = getattr(sub_agent, "name", "<unknown>")
848
+ raise ValueError(
849
+ f"Sub-agent '{agent_name}' is not supported in local mode. "
850
+ "Platform agents (from_id, from_native) cannot be used as "
851
+ "sub-agents in local execution. "
852
+ "Define the sub-agent locally with Agent(name=..., instruction=...) instead."
853
+ )
854
+
855
+ def _log_event(self, event: dict[str, Any]) -> None:
856
+ """Log an A2AEvent for verbose debug output.
857
+
858
+ Args:
859
+ event: The A2AEvent dictionary to log.
860
+ """
861
+ event_type = event.get("event_type", "unknown")
862
+ content = event.get("content", "")
863
+ is_final = event.get("is_final", False)
864
+
865
+ # Truncate long content for readability
866
+ content_str = str(content) if content else ""
867
+ content_preview = content_str[:100] + "..." if len(content_str) > 100 else content_str
868
+
869
+ final_marker = "(final)" if is_final else ""
870
+ logger.info("[%s] %s %s", event_type, final_marker, content_preview)