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,492 @@
1
+ """Import resolution and categorization for tool bundling.
2
+
3
+ This module provides the ImportResolver class for handling Python import
4
+ analysis and resolution during tool bundling operations.
5
+
6
+ Authors:
7
+ Christian Trisno Sen Long Chen (christian.t.s.l.chen@gdplabs.id)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ast
13
+ import importlib
14
+ from pathlib import Path
15
+
16
+
17
+ class ImportResolver:
18
+ """Resolves and categorizes Python imports for tool bundling.
19
+
20
+ This class handles the complex logic of determining which imports
21
+ are local (and need to be inlined) versus external (and need to
22
+ be preserved as import statements).
23
+
24
+ Attributes:
25
+ tool_dir: The directory containing the tool file being bundled.
26
+
27
+ Example:
28
+ >>> resolver = ImportResolver(Path("/path/to/tool/dir"))
29
+ >>> local, external = resolver.categorize_imports(ast_tree)
30
+ """
31
+
32
+ # Modules to exclude from bundled code (only needed locally)
33
+ EXCLUDED_MODULES: set[str] = {
34
+ "glaip_sdk.agents",
35
+ "glaip_sdk.tools",
36
+ "glaip_sdk.mcps",
37
+ }
38
+
39
+ def __init__(self, tool_dir: Path) -> None:
40
+ """Initialize the ImportResolver.
41
+
42
+ Args:
43
+ tool_dir: Directory containing the tool file being processed.
44
+ """
45
+ self.tool_dir = tool_dir
46
+ self._processed_modules: set[str] = set()
47
+
48
+ def categorize_imports(self, tree: ast.AST) -> tuple[list, list]:
49
+ """Categorize imports into local and external.
50
+
51
+ Args:
52
+ tree: AST tree of the source file.
53
+
54
+ Returns:
55
+ Tuple of (local_imports, external_imports) where local_imports
56
+ contains tuples of (module_name, file_path, import_node).
57
+ """
58
+ local_imports = []
59
+ external_imports = []
60
+
61
+ for node in ast.walk(tree):
62
+ if isinstance(node, ast.ImportFrom):
63
+ if self.is_local_import(node):
64
+ module_file = self.resolve_module_path(node.module)
65
+ local_imports.append((node.module, module_file, node))
66
+ else:
67
+ external_imports.append(node)
68
+ elif isinstance(node, ast.Import):
69
+ external_imports.append(node)
70
+
71
+ return local_imports, external_imports
72
+
73
+ def is_local_import(self, node: ast.ImportFrom) -> bool:
74
+ """Check if import is local to the tool directory.
75
+
76
+ Args:
77
+ node: Import node to check.
78
+
79
+ Returns:
80
+ True if import is local.
81
+ """
82
+ if not node.module:
83
+ return False
84
+
85
+ # Handle package imports
86
+ if "." in node.module:
87
+ return self._is_local_package_import(node.module)
88
+
89
+ potential_file = self.tool_dir / f"{node.module}.py"
90
+ return potential_file.exists()
91
+
92
+ def _is_local_package_import(self, module: str) -> bool:
93
+ """Check if a dotted module path is local.
94
+
95
+ Args:
96
+ module: Module path like 'tools.config' or 'sub.module'.
97
+
98
+ Returns:
99
+ True if the module is local to tool_dir.
100
+ """
101
+ parts = module.split(".")
102
+
103
+ # Case 1: First part matches current directory name
104
+ if parts[0] == self.tool_dir.name:
105
+ remaining_parts = parts[1:]
106
+ if len(remaining_parts) == 1:
107
+ module_path = self.tool_dir / f"{remaining_parts[0]}.py"
108
+ if module_path.exists():
109
+ return True
110
+ elif len(remaining_parts) > 1:
111
+ module_path = self.tool_dir / "/".join(remaining_parts[:-1]) / f"{remaining_parts[-1]}.py"
112
+ if module_path.exists():
113
+ return True
114
+
115
+ # Case 2: First part is a subdirectory of tool_dir
116
+ package_dir = self.tool_dir / parts[0]
117
+ if package_dir.is_dir():
118
+ module_path = self.tool_dir / "/".join(parts[:-1]) / f"{parts[-1]}.py"
119
+ if module_path.exists():
120
+ return True
121
+ module_path = self.tool_dir / "/".join(parts) / "__init__.py"
122
+ return module_path.exists()
123
+
124
+ return False
125
+
126
+ def resolve_module_path(self, module_name: str) -> Path:
127
+ """Resolve module name to file path.
128
+
129
+ Args:
130
+ module_name: Module name (e.g., 'config' or 'tools.config').
131
+
132
+ Returns:
133
+ Path to the module file.
134
+ """
135
+ if "." in module_name:
136
+ return self._resolve_dotted_module_path(module_name)
137
+ return self.tool_dir / f"{module_name}.py"
138
+
139
+ def _resolve_dotted_module_path(self, module_name: str) -> Path:
140
+ """Resolve a dotted module path to a file path.
141
+
142
+ Args:
143
+ module_name: Dotted module path like 'tools.config'.
144
+
145
+ Returns:
146
+ Path to the module file.
147
+ """
148
+ parts = module_name.split(".")
149
+
150
+ # Case 1: First part matches current directory name
151
+ if parts[0] == self.tool_dir.name:
152
+ remaining_parts = parts[1:]
153
+ if len(remaining_parts) == 1:
154
+ module_path = self.tool_dir / f"{remaining_parts[0]}.py"
155
+ if module_path.exists():
156
+ return module_path
157
+ elif len(remaining_parts) > 1:
158
+ module_path = self.tool_dir / "/".join(remaining_parts[:-1]) / f"{remaining_parts[-1]}.py"
159
+ if module_path.exists():
160
+ return module_path
161
+
162
+ # Case 2: Standard package/module.py
163
+ module_path = self.tool_dir / "/".join(parts[:-1]) / f"{parts[-1]}.py"
164
+ if module_path.exists():
165
+ return module_path
166
+
167
+ # Try package/__init__.py
168
+ return self.tool_dir / "/".join(parts) / "__init__.py"
169
+
170
+ def format_external_imports(self, external_imports: list) -> list[str]:
171
+ """Format external imports as code strings.
172
+
173
+ __future__ imports are placed first, then other imports.
174
+ Excluded modules are filtered out.
175
+
176
+ Args:
177
+ external_imports: List of external import nodes.
178
+
179
+ Returns:
180
+ Formatted import statements.
181
+ """
182
+ future_imports, regular_imports = self._categorize_by_future(external_imports)
183
+ return self._build_import_strings(future_imports, regular_imports)
184
+
185
+ def _categorize_by_future(self, external_imports: list) -> tuple[list, list]:
186
+ """Separate imports into __future__ and regular imports.
187
+
188
+ Args:
189
+ external_imports: List of import nodes.
190
+
191
+ Returns:
192
+ Tuple of (future_imports, regular_imports).
193
+ """
194
+ future_imports = []
195
+ regular_imports = []
196
+
197
+ for node in external_imports:
198
+ if self._should_skip_import(node):
199
+ continue
200
+
201
+ if isinstance(node, ast.ImportFrom) and node.module == "__future__":
202
+ future_imports.append(node)
203
+ else:
204
+ regular_imports.append(node)
205
+
206
+ return future_imports, regular_imports
207
+
208
+ def _should_skip_import(self, node: ast.Import | ast.ImportFrom) -> bool:
209
+ """Check if import should be skipped (excluded modules).
210
+
211
+ Args:
212
+ node: Import node to check.
213
+
214
+ Returns:
215
+ True if import should be skipped.
216
+ """
217
+ if isinstance(node, ast.ImportFrom):
218
+ return node.module and any(node.module.startswith(m) for m in self.EXCLUDED_MODULES)
219
+ if isinstance(node, ast.Import):
220
+ return any(alias.name.startswith(m) for m in self.EXCLUDED_MODULES for alias in node.names)
221
+ return False
222
+
223
+ @staticmethod
224
+ def _build_import_strings(future_imports: list, regular_imports: list) -> list[str]:
225
+ """Build formatted import strings from import nodes.
226
+
227
+ Args:
228
+ future_imports: List of __future__ import nodes.
229
+ regular_imports: List of regular import nodes.
230
+
231
+ Returns:
232
+ Formatted import statements.
233
+ """
234
+ result = []
235
+
236
+ if future_imports:
237
+ result.append("# Future imports\n")
238
+ for node in future_imports:
239
+ result.append(ast.unparse(node) + "\n")
240
+ result.append("\n")
241
+
242
+ if regular_imports:
243
+ result.append("# External imports\n")
244
+ for node in regular_imports:
245
+ result.append(ast.unparse(node) + "\n")
246
+ result.append("\n")
247
+
248
+ return result
249
+
250
+ def inline_local_imports(
251
+ self,
252
+ local_imports: list,
253
+ processed_modules: set[str] | None = None,
254
+ ) -> tuple[list[str], list]:
255
+ """Inline local imports into bundled code and collect their external imports.
256
+
257
+ Recursively inlines nested local imports.
258
+
259
+ Args:
260
+ local_imports: List of (module_name, file_path, import_node) tuples.
261
+ processed_modules: Set of already processed module paths to avoid duplicates.
262
+
263
+ Returns:
264
+ Tuple of (inlined_code_strings, collected_external_imports).
265
+ """
266
+ if not local_imports:
267
+ return [], []
268
+
269
+ if processed_modules is None:
270
+ processed_modules = set()
271
+
272
+ result = ["# Inlined local imports\n"]
273
+ all_external_imports = []
274
+
275
+ for module_name, file_path, _ in local_imports:
276
+ if str(file_path) in processed_modules:
277
+ continue
278
+ processed_modules.add(str(file_path))
279
+
280
+ # Recursively inline nested local imports
281
+ nested_resolver = ImportResolver(file_path.parent)
282
+ with open(file_path, encoding="utf-8") as f:
283
+ source = f.read()
284
+ tree = ast.parse(source)
285
+ nested_local_imports, nested_external_imports = nested_resolver.categorize_imports(tree)
286
+
287
+ if nested_local_imports:
288
+ nested_code, nested_ext_imports = nested_resolver.inline_local_imports(
289
+ nested_local_imports, processed_modules
290
+ )
291
+ result.extend(nested_code)
292
+ all_external_imports.extend(nested_ext_imports)
293
+
294
+ # Inline this module's code
295
+ result.append(f"# --- Inlined from {module_name}.py ---\n")
296
+ code_lines, external_imports = self._extract_module_code(file_path, collect_imports=True)
297
+ result.extend(code_lines)
298
+ all_external_imports.extend(external_imports)
299
+ all_external_imports.extend(nested_external_imports)
300
+ result.append(f"# --- End of {module_name}.py ---\n\n")
301
+
302
+ return result, all_external_imports
303
+
304
+ def _extract_module_code(
305
+ self,
306
+ file_path: Path,
307
+ *,
308
+ collect_imports: bool = False,
309
+ ) -> tuple[list[str], list] | list[str]:
310
+ """Extract code from module, excluding imports and docstrings.
311
+
312
+ Args:
313
+ file_path: Path to the module file.
314
+ collect_imports: If True, also return external imports.
315
+
316
+ Returns:
317
+ If collect_imports is True: tuple of (code_lines, external_import_nodes)
318
+ Otherwise: list of code lines.
319
+ """
320
+ with open(file_path, encoding="utf-8") as f:
321
+ local_source = f.read()
322
+
323
+ local_tree = ast.parse(local_source)
324
+ tool_dir = file_path.parent
325
+
326
+ result, external_imports = self._process_module_nodes(local_tree, tool_dir, collect_imports)
327
+
328
+ if collect_imports:
329
+ return result, external_imports
330
+ return result
331
+
332
+ def _process_module_nodes(
333
+ self,
334
+ tree: ast.AST,
335
+ tool_dir: Path,
336
+ collect_imports: bool,
337
+ ) -> tuple[list[str], list]:
338
+ """Process AST nodes from a module.
339
+
340
+ Args:
341
+ tree: AST tree of the module.
342
+ tool_dir: Directory containing the module.
343
+ collect_imports: Whether to collect external imports.
344
+
345
+ Returns:
346
+ Tuple of (code_lines, external_imports).
347
+ """
348
+ result = []
349
+ external_imports = []
350
+
351
+ for local_node in tree.body:
352
+ if isinstance(local_node, (ast.Import, ast.ImportFrom)):
353
+ if collect_imports:
354
+ ext_import = self._get_external_import(local_node, tool_dir)
355
+ if ext_import:
356
+ external_imports.append(ext_import)
357
+ continue
358
+
359
+ if self._is_docstring(local_node):
360
+ continue
361
+
362
+ if isinstance(local_node, ast.ClassDef):
363
+ local_node = self._remove_tool_plugin_decorator(local_node)
364
+
365
+ result.append(ast.unparse(local_node) + "\n")
366
+
367
+ return result, external_imports
368
+
369
+ def _get_external_import(
370
+ self,
371
+ node: ast.Import | ast.ImportFrom,
372
+ tool_dir: Path,
373
+ ) -> ast.Import | ast.ImportFrom | None:
374
+ """Get external import node if not local.
375
+
376
+ Args:
377
+ node: Import node to check.
378
+ tool_dir: Directory containing the tool.
379
+
380
+ Returns:
381
+ The node if external, None if local.
382
+ """
383
+ if isinstance(node, ast.ImportFrom):
384
+ if node.module and node.module.startswith("."):
385
+ return None
386
+ temp_resolver = ImportResolver(tool_dir)
387
+ if temp_resolver.is_local_import(node):
388
+ return None
389
+ return node
390
+ if isinstance(node, ast.Import):
391
+ return node
392
+ return None
393
+
394
+ @staticmethod
395
+ def _is_docstring(node: ast.stmt) -> bool:
396
+ """Check if AST node is a docstring.
397
+
398
+ Args:
399
+ node: AST statement node.
400
+
401
+ Returns:
402
+ True if node is a docstring.
403
+ """
404
+ return isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant)
405
+
406
+ @staticmethod
407
+ def _remove_tool_plugin_decorator(node: ast.ClassDef) -> ast.ClassDef:
408
+ """Remove @tool_plugin decorator and BaseTool inheritance from a class node.
409
+
410
+ Args:
411
+ node: AST ClassDef node.
412
+
413
+ Returns:
414
+ Modified ClassDef node with decorator and base class removed.
415
+ """
416
+ node.decorator_list = ImportResolver._filter_decorators(node.decorator_list)
417
+ node.bases = ImportResolver._filter_bases(node.bases)
418
+ return node
419
+
420
+ @staticmethod
421
+ def _filter_decorators(decorator_list: list) -> list:
422
+ """Filter out @tool_plugin decorators.
423
+
424
+ Args:
425
+ decorator_list: List of decorator nodes.
426
+
427
+ Returns:
428
+ Filtered decorator list.
429
+ """
430
+ filtered = []
431
+ for decorator in decorator_list:
432
+ if ImportResolver._is_tool_plugin_decorator(decorator):
433
+ continue
434
+ filtered.append(decorator)
435
+ return filtered
436
+
437
+ @staticmethod
438
+ def _is_tool_plugin_decorator(decorator: ast.expr) -> bool:
439
+ """Check if decorator is @tool_plugin.
440
+
441
+ Args:
442
+ decorator: Decorator AST node.
443
+
444
+ Returns:
445
+ True if decorator is @tool_plugin.
446
+ """
447
+ if isinstance(decorator, ast.Name) and decorator.id == "tool_plugin":
448
+ return True
449
+ if (
450
+ isinstance(decorator, ast.Call)
451
+ and isinstance(decorator.func, ast.Name)
452
+ and decorator.func.id == "tool_plugin"
453
+ ):
454
+ return True
455
+ return False
456
+
457
+ @staticmethod
458
+ def _filter_bases(bases: list) -> list:
459
+ """Filter out BaseTool from base classes.
460
+
461
+ Args:
462
+ bases: List of base class nodes.
463
+
464
+ Returns:
465
+ Filtered base class list.
466
+ """
467
+ filtered = []
468
+ for base in bases:
469
+ is_base_tool = isinstance(base, ast.Name) and base.id == "BaseTool"
470
+ if not is_base_tool:
471
+ filtered.append(base)
472
+ return filtered if filtered else []
473
+
474
+
475
+ def load_class(import_path: str) -> type:
476
+ """Dynamically load a class from its import path.
477
+
478
+ Args:
479
+ import_path: Python import path (e.g., 'package.module.ClassName').
480
+
481
+ Returns:
482
+ The loaded class.
483
+
484
+ Raises:
485
+ ImportError: If the module or class cannot be imported.
486
+ """
487
+ try:
488
+ module_path, class_name = import_path.rsplit(".", 1)
489
+ module = importlib.import_module(module_path)
490
+ return getattr(module, class_name)
491
+ except (ValueError, ImportError, AttributeError) as e:
492
+ raise ImportError(f"Failed to load class from '{import_path}': {e}") from e
@@ -0,0 +1,101 @@
1
+ """Instruction template loading and processing.
2
+
3
+ This module provides functions for loading and processing instruction
4
+ templates from markdown files.
5
+
6
+ Authors:
7
+ Christian Trisno Sen Long Chen (christian.t.s.l.chen@gdplabs.id)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+
14
+
15
+ def load_instruction_from_file(
16
+ instructions_path: str,
17
+ variables: dict[str, str] | None = None,
18
+ base_path: Path | None = None,
19
+ ) -> str:
20
+ """Load and process instruction template from markdown file.
21
+
22
+ Args:
23
+ instructions_path: Path to instructions markdown file.
24
+ variables: Template variables for {{variable}} substitution.
25
+ base_path: Base path to resolve relative paths from.
26
+
27
+ Returns:
28
+ Processed instructions with variables substituted.
29
+
30
+ Raises:
31
+ FileNotFoundError: If instructions file doesn't exist.
32
+
33
+ Example:
34
+ >>> instructions = load_instruction_from_file(
35
+ ... "instructions.md",
36
+ ... variables={"agent_name": "Weather Bot"}
37
+ ... )
38
+ """
39
+ full_path = _resolve_instructions_path(instructions_path, base_path)
40
+
41
+ if not full_path.exists():
42
+ raise FileNotFoundError(f"Instructions file not found: {full_path}")
43
+
44
+ with open(full_path, encoding="utf-8") as f:
45
+ template = f.read()
46
+
47
+ if variables:
48
+ template = _substitute_variables(template, variables)
49
+
50
+ return template
51
+
52
+
53
+ # Alias for backwards compatibility
54
+ load_instructions = load_instruction_from_file
55
+
56
+
57
+ def _resolve_instructions_path(instructions_path: str, base_path: Path | None) -> Path:
58
+ """Resolve instructions path to an absolute path.
59
+
60
+ Handles absolute paths, tilde expansion, and relative paths.
61
+ Guards against path traversal escaping base_path when provided.
62
+
63
+ Args:
64
+ instructions_path: Path to instructions file (may be relative).
65
+ base_path: Base path for relative resolution.
66
+
67
+ Returns:
68
+ Resolved absolute path.
69
+
70
+ Raises:
71
+ ValueError: If resolved path escapes base_path.
72
+ """
73
+ raw_path = Path(instructions_path).expanduser()
74
+
75
+ if raw_path.is_absolute():
76
+ return raw_path.resolve()
77
+
78
+ base = (base_path or Path.cwd()).resolve()
79
+ relative_part = raw_path.relative_to(".") if instructions_path.startswith("./") else raw_path
80
+ resolved = (base / relative_part).resolve()
81
+
82
+ if base_path and not resolved.is_relative_to(base):
83
+ raise ValueError(f"Resolved instructions path escapes base path: {resolved}")
84
+
85
+ return resolved
86
+
87
+
88
+ def _substitute_variables(template: str, variables: dict[str, str]) -> str:
89
+ """Substitute template variables in the format {{variable_name}}.
90
+
91
+ Args:
92
+ template: Template string with {{variable}} placeholders.
93
+ variables: Dictionary of variable names to values.
94
+
95
+ Returns:
96
+ Template with variables substituted.
97
+ """
98
+ result = template
99
+ for key, value in variables.items():
100
+ result = result.replace(f"{{{{{key}}}}}", value)
101
+ return result
@@ -1 +1,115 @@
1
- """Rendering utilities package (formatting, models, steps, debug)."""
1
+ """Rendering utilities package (formatting, models, steps, debug).
2
+
3
+ Authors:
4
+ Raymond Christopher (raymond.christopher@gdplabs.id)
5
+ """
6
+
7
+ from datetime import datetime
8
+ from typing import Any
9
+
10
+ from rich.console import Console
11
+
12
+ from glaip_sdk.models.agent_runs import RunWithOutput
13
+ from glaip_sdk.utils.rendering.renderer.debug import render_debug_event, render_debug_event_stream
14
+
15
+
16
+ def _parse_event_received_timestamp(event: dict[str, Any]) -> datetime | None:
17
+ """Parse received_at timestamp from SSE event.
18
+
19
+ Args:
20
+ event: SSE event dictionary
21
+
22
+ Returns:
23
+ Parsed datetime or None if not available
24
+ """
25
+ received_at = event.get("received_at")
26
+ if not received_at:
27
+ return None
28
+
29
+ if isinstance(received_at, datetime):
30
+ return received_at
31
+
32
+ if isinstance(received_at, str):
33
+ try:
34
+ # Try ISO format first
35
+ return datetime.fromisoformat(received_at.replace("Z", "+00:00"))
36
+ except ValueError:
37
+ try:
38
+ # Try common formats
39
+ return datetime.strptime(received_at, "%Y-%m-%dT%H:%M:%S.%fZ")
40
+ except ValueError:
41
+ return None
42
+
43
+ return None
44
+
45
+
46
+ def render_remote_sse_transcript(
47
+ run: RunWithOutput,
48
+ console: Console,
49
+ *,
50
+ show_metadata: bool = True,
51
+ ) -> None:
52
+ """Render remote SSE transcript events for a RunWithOutput.
53
+
54
+ Args:
55
+ run: RunWithOutput instance containing events
56
+ console: Rich console to render to
57
+ show_metadata: Whether to show run metadata summary
58
+ """
59
+ if show_metadata:
60
+ # Render metadata summary
61
+ console.print(f"[bold]Run: {run.id}[/bold]")
62
+ console.print(f"[dim]Agent: {run.agent_id}[/dim]")
63
+ console.print(f"[dim]Status: {run.status}[/dim]")
64
+ console.print(f"[dim]Type: {run.run_type}[/dim]")
65
+ if run.schedule_id:
66
+ console.print(f"[dim]Schedule ID: {run.schedule_id}[/dim]")
67
+ else:
68
+ console.print("[dim]Schedule: —[/dim]")
69
+ console.print(f"[dim]Started: {run.started_at.isoformat()}[/dim]")
70
+ if run.completed_at:
71
+ console.print(f"[dim]Completed: {run.completed_at.isoformat()}[/dim]")
72
+ console.print(f"[dim]Duration: {run.duration_formatted()}[/dim]")
73
+ console.print()
74
+
75
+ # Render events
76
+ if not run.output:
77
+ console.print("[dim]No SSE events available for this run.[/dim]")
78
+ return
79
+
80
+ console.print("[bold]SSE Events[/bold]")
81
+ console.print("[dim]────────────────────────────────────────────────────────[/dim]")
82
+
83
+ render_debug_event_stream(
84
+ run.output,
85
+ console,
86
+ resolve_timestamp=_parse_event_received_timestamp,
87
+ )
88
+ console.print()
89
+
90
+
91
+ class RemoteSSETranscriptRenderer:
92
+ """Renderer for remote SSE transcripts from RunWithOutput."""
93
+
94
+ def __init__(self, console: Console | None = None):
95
+ """Initialize the renderer.
96
+
97
+ Args:
98
+ console: Rich console instance (creates default if None)
99
+ """
100
+ self.console = console or Console()
101
+
102
+ def render(self, run: RunWithOutput, *, show_metadata: bool = True) -> None:
103
+ """Render a remote run transcript.
104
+
105
+ Args:
106
+ run: RunWithOutput instance to render
107
+ show_metadata: Whether to show run metadata summary
108
+ """
109
+ render_remote_sse_transcript(run, self.console, show_metadata=show_metadata)
110
+
111
+
112
+ __all__ = [
113
+ "render_remote_sse_transcript",
114
+ "RemoteSSETranscriptRenderer",
115
+ ]