glaip-sdk 0.0.0b99__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 (207) hide show
  1. glaip_sdk/__init__.py +52 -0
  2. glaip_sdk/_version.py +81 -0
  3. glaip_sdk/agents/__init__.py +27 -0
  4. glaip_sdk/agents/base.py +1227 -0
  5. glaip_sdk/branding.py +211 -0
  6. glaip_sdk/cli/__init__.py +9 -0
  7. glaip_sdk/cli/account_store.py +540 -0
  8. glaip_sdk/cli/agent_config.py +78 -0
  9. glaip_sdk/cli/auth.py +705 -0
  10. glaip_sdk/cli/commands/__init__.py +5 -0
  11. glaip_sdk/cli/commands/accounts.py +746 -0
  12. glaip_sdk/cli/commands/agents/__init__.py +119 -0
  13. glaip_sdk/cli/commands/agents/_common.py +561 -0
  14. glaip_sdk/cli/commands/agents/create.py +151 -0
  15. glaip_sdk/cli/commands/agents/delete.py +64 -0
  16. glaip_sdk/cli/commands/agents/get.py +89 -0
  17. glaip_sdk/cli/commands/agents/list.py +129 -0
  18. glaip_sdk/cli/commands/agents/run.py +264 -0
  19. glaip_sdk/cli/commands/agents/sync_langflow.py +72 -0
  20. glaip_sdk/cli/commands/agents/update.py +112 -0
  21. glaip_sdk/cli/commands/common_config.py +104 -0
  22. glaip_sdk/cli/commands/configure.py +895 -0
  23. glaip_sdk/cli/commands/mcps/__init__.py +94 -0
  24. glaip_sdk/cli/commands/mcps/_common.py +459 -0
  25. glaip_sdk/cli/commands/mcps/connect.py +82 -0
  26. glaip_sdk/cli/commands/mcps/create.py +152 -0
  27. glaip_sdk/cli/commands/mcps/delete.py +73 -0
  28. glaip_sdk/cli/commands/mcps/get.py +212 -0
  29. glaip_sdk/cli/commands/mcps/list.py +69 -0
  30. glaip_sdk/cli/commands/mcps/tools.py +235 -0
  31. glaip_sdk/cli/commands/mcps/update.py +190 -0
  32. glaip_sdk/cli/commands/models.py +67 -0
  33. glaip_sdk/cli/commands/shared/__init__.py +21 -0
  34. glaip_sdk/cli/commands/shared/formatters.py +91 -0
  35. glaip_sdk/cli/commands/tools/__init__.py +69 -0
  36. glaip_sdk/cli/commands/tools/_common.py +80 -0
  37. glaip_sdk/cli/commands/tools/create.py +228 -0
  38. glaip_sdk/cli/commands/tools/delete.py +61 -0
  39. glaip_sdk/cli/commands/tools/get.py +103 -0
  40. glaip_sdk/cli/commands/tools/list.py +69 -0
  41. glaip_sdk/cli/commands/tools/script.py +49 -0
  42. glaip_sdk/cli/commands/tools/update.py +102 -0
  43. glaip_sdk/cli/commands/transcripts/__init__.py +90 -0
  44. glaip_sdk/cli/commands/transcripts/_common.py +9 -0
  45. glaip_sdk/cli/commands/transcripts/clear.py +5 -0
  46. glaip_sdk/cli/commands/transcripts/detail.py +5 -0
  47. glaip_sdk/cli/commands/transcripts_original.py +756 -0
  48. glaip_sdk/cli/commands/update.py +192 -0
  49. glaip_sdk/cli/config.py +95 -0
  50. glaip_sdk/cli/constants.py +38 -0
  51. glaip_sdk/cli/context.py +150 -0
  52. glaip_sdk/cli/core/__init__.py +79 -0
  53. glaip_sdk/cli/core/context.py +124 -0
  54. glaip_sdk/cli/core/output.py +851 -0
  55. glaip_sdk/cli/core/prompting.py +649 -0
  56. glaip_sdk/cli/core/rendering.py +187 -0
  57. glaip_sdk/cli/display.py +355 -0
  58. glaip_sdk/cli/hints.py +57 -0
  59. glaip_sdk/cli/io.py +112 -0
  60. glaip_sdk/cli/main.py +686 -0
  61. glaip_sdk/cli/masking.py +136 -0
  62. glaip_sdk/cli/mcp_validators.py +287 -0
  63. glaip_sdk/cli/pager.py +266 -0
  64. glaip_sdk/cli/parsers/__init__.py +7 -0
  65. glaip_sdk/cli/parsers/json_input.py +177 -0
  66. glaip_sdk/cli/resolution.py +68 -0
  67. glaip_sdk/cli/rich_helpers.py +27 -0
  68. glaip_sdk/cli/slash/__init__.py +15 -0
  69. glaip_sdk/cli/slash/accounts_controller.py +580 -0
  70. glaip_sdk/cli/slash/accounts_shared.py +75 -0
  71. glaip_sdk/cli/slash/agent_session.py +285 -0
  72. glaip_sdk/cli/slash/prompt.py +256 -0
  73. glaip_sdk/cli/slash/remote_runs_controller.py +566 -0
  74. glaip_sdk/cli/slash/session.py +1724 -0
  75. glaip_sdk/cli/slash/tui/__init__.py +34 -0
  76. glaip_sdk/cli/slash/tui/accounts.tcss +88 -0
  77. glaip_sdk/cli/slash/tui/accounts_app.py +933 -0
  78. glaip_sdk/cli/slash/tui/background_tasks.py +72 -0
  79. glaip_sdk/cli/slash/tui/clipboard.py +147 -0
  80. glaip_sdk/cli/slash/tui/context.py +59 -0
  81. glaip_sdk/cli/slash/tui/keybind_registry.py +235 -0
  82. glaip_sdk/cli/slash/tui/loading.py +58 -0
  83. glaip_sdk/cli/slash/tui/remote_runs_app.py +628 -0
  84. glaip_sdk/cli/slash/tui/terminal.py +402 -0
  85. glaip_sdk/cli/slash/tui/theme/__init__.py +15 -0
  86. glaip_sdk/cli/slash/tui/theme/catalog.py +79 -0
  87. glaip_sdk/cli/slash/tui/theme/manager.py +86 -0
  88. glaip_sdk/cli/slash/tui/theme/tokens.py +55 -0
  89. glaip_sdk/cli/slash/tui/toast.py +123 -0
  90. glaip_sdk/cli/transcript/__init__.py +31 -0
  91. glaip_sdk/cli/transcript/cache.py +536 -0
  92. glaip_sdk/cli/transcript/capture.py +329 -0
  93. glaip_sdk/cli/transcript/export.py +38 -0
  94. glaip_sdk/cli/transcript/history.py +815 -0
  95. glaip_sdk/cli/transcript/launcher.py +77 -0
  96. glaip_sdk/cli/transcript/viewer.py +374 -0
  97. glaip_sdk/cli/update_notifier.py +369 -0
  98. glaip_sdk/cli/validators.py +238 -0
  99. glaip_sdk/client/__init__.py +12 -0
  100. glaip_sdk/client/_schedule_payloads.py +89 -0
  101. glaip_sdk/client/agent_runs.py +147 -0
  102. glaip_sdk/client/agents.py +1353 -0
  103. glaip_sdk/client/base.py +502 -0
  104. glaip_sdk/client/main.py +253 -0
  105. glaip_sdk/client/mcps.py +401 -0
  106. glaip_sdk/client/payloads/agent/__init__.py +23 -0
  107. glaip_sdk/client/payloads/agent/requests.py +495 -0
  108. glaip_sdk/client/payloads/agent/responses.py +43 -0
  109. glaip_sdk/client/run_rendering.py +747 -0
  110. glaip_sdk/client/schedules.py +439 -0
  111. glaip_sdk/client/shared.py +21 -0
  112. glaip_sdk/client/tools.py +690 -0
  113. glaip_sdk/client/validators.py +198 -0
  114. glaip_sdk/config/constants.py +52 -0
  115. glaip_sdk/exceptions.py +113 -0
  116. glaip_sdk/hitl/__init__.py +15 -0
  117. glaip_sdk/hitl/local.py +151 -0
  118. glaip_sdk/icons.py +25 -0
  119. glaip_sdk/mcps/__init__.py +21 -0
  120. glaip_sdk/mcps/base.py +345 -0
  121. glaip_sdk/models/__init__.py +107 -0
  122. glaip_sdk/models/agent.py +47 -0
  123. glaip_sdk/models/agent_runs.py +117 -0
  124. glaip_sdk/models/common.py +42 -0
  125. glaip_sdk/models/mcp.py +33 -0
  126. glaip_sdk/models/schedule.py +224 -0
  127. glaip_sdk/models/tool.py +33 -0
  128. glaip_sdk/payload_schemas/__init__.py +7 -0
  129. glaip_sdk/payload_schemas/agent.py +85 -0
  130. glaip_sdk/registry/__init__.py +55 -0
  131. glaip_sdk/registry/agent.py +164 -0
  132. glaip_sdk/registry/base.py +139 -0
  133. glaip_sdk/registry/mcp.py +253 -0
  134. glaip_sdk/registry/tool.py +393 -0
  135. glaip_sdk/rich_components.py +125 -0
  136. glaip_sdk/runner/__init__.py +59 -0
  137. glaip_sdk/runner/base.py +84 -0
  138. glaip_sdk/runner/deps.py +112 -0
  139. glaip_sdk/runner/langgraph.py +870 -0
  140. glaip_sdk/runner/mcp_adapter/__init__.py +13 -0
  141. glaip_sdk/runner/mcp_adapter/base_mcp_adapter.py +43 -0
  142. glaip_sdk/runner/mcp_adapter/langchain_mcp_adapter.py +257 -0
  143. glaip_sdk/runner/mcp_adapter/mcp_config_builder.py +95 -0
  144. glaip_sdk/runner/tool_adapter/__init__.py +18 -0
  145. glaip_sdk/runner/tool_adapter/base_tool_adapter.py +44 -0
  146. glaip_sdk/runner/tool_adapter/langchain_tool_adapter.py +219 -0
  147. glaip_sdk/schedules/__init__.py +22 -0
  148. glaip_sdk/schedules/base.py +291 -0
  149. glaip_sdk/tools/__init__.py +22 -0
  150. glaip_sdk/tools/base.py +466 -0
  151. glaip_sdk/utils/__init__.py +86 -0
  152. glaip_sdk/utils/a2a/__init__.py +34 -0
  153. glaip_sdk/utils/a2a/event_processor.py +188 -0
  154. glaip_sdk/utils/agent_config.py +194 -0
  155. glaip_sdk/utils/bundler.py +267 -0
  156. glaip_sdk/utils/client.py +111 -0
  157. glaip_sdk/utils/client_utils.py +486 -0
  158. glaip_sdk/utils/datetime_helpers.py +58 -0
  159. glaip_sdk/utils/discovery.py +78 -0
  160. glaip_sdk/utils/display.py +135 -0
  161. glaip_sdk/utils/export.py +143 -0
  162. glaip_sdk/utils/general.py +61 -0
  163. glaip_sdk/utils/import_export.py +168 -0
  164. glaip_sdk/utils/import_resolver.py +530 -0
  165. glaip_sdk/utils/instructions.py +101 -0
  166. glaip_sdk/utils/rendering/__init__.py +115 -0
  167. glaip_sdk/utils/rendering/formatting.py +264 -0
  168. glaip_sdk/utils/rendering/layout/__init__.py +64 -0
  169. glaip_sdk/utils/rendering/layout/panels.py +156 -0
  170. glaip_sdk/utils/rendering/layout/progress.py +202 -0
  171. glaip_sdk/utils/rendering/layout/summary.py +74 -0
  172. glaip_sdk/utils/rendering/layout/transcript.py +606 -0
  173. glaip_sdk/utils/rendering/models.py +85 -0
  174. glaip_sdk/utils/rendering/renderer/__init__.py +55 -0
  175. glaip_sdk/utils/rendering/renderer/base.py +1082 -0
  176. glaip_sdk/utils/rendering/renderer/config.py +27 -0
  177. glaip_sdk/utils/rendering/renderer/console.py +55 -0
  178. glaip_sdk/utils/rendering/renderer/debug.py +178 -0
  179. glaip_sdk/utils/rendering/renderer/factory.py +138 -0
  180. glaip_sdk/utils/rendering/renderer/stream.py +202 -0
  181. glaip_sdk/utils/rendering/renderer/summary_window.py +79 -0
  182. glaip_sdk/utils/rendering/renderer/thinking.py +273 -0
  183. glaip_sdk/utils/rendering/renderer/toggle.py +182 -0
  184. glaip_sdk/utils/rendering/renderer/tool_panels.py +442 -0
  185. glaip_sdk/utils/rendering/renderer/transcript_mode.py +162 -0
  186. glaip_sdk/utils/rendering/state.py +204 -0
  187. glaip_sdk/utils/rendering/step_tree_state.py +100 -0
  188. glaip_sdk/utils/rendering/steps/__init__.py +34 -0
  189. glaip_sdk/utils/rendering/steps/event_processor.py +778 -0
  190. glaip_sdk/utils/rendering/steps/format.py +176 -0
  191. glaip_sdk/utils/rendering/steps/manager.py +387 -0
  192. glaip_sdk/utils/rendering/timing.py +36 -0
  193. glaip_sdk/utils/rendering/viewer/__init__.py +21 -0
  194. glaip_sdk/utils/rendering/viewer/presenter.py +184 -0
  195. glaip_sdk/utils/resource_refs.py +195 -0
  196. glaip_sdk/utils/run_renderer.py +41 -0
  197. glaip_sdk/utils/runtime_config.py +425 -0
  198. glaip_sdk/utils/serialization.py +424 -0
  199. glaip_sdk/utils/sync.py +142 -0
  200. glaip_sdk/utils/tool_detection.py +33 -0
  201. glaip_sdk/utils/tool_storage_provider.py +140 -0
  202. glaip_sdk/utils/validation.py +264 -0
  203. glaip_sdk-0.0.0b99.dist-info/METADATA +239 -0
  204. glaip_sdk-0.0.0b99.dist-info/RECORD +207 -0
  205. glaip_sdk-0.0.0b99.dist-info/WHEEL +5 -0
  206. glaip_sdk-0.0.0b99.dist-info/entry_points.txt +2 -0
  207. glaip_sdk-0.0.0b99.dist-info/top_level.txt +1 -0
@@ -0,0 +1,530 @@
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 self._should_skip_import_from(node)
219
+ if isinstance(node, ast.Import):
220
+ return self._should_skip_regular_import(node)
221
+ return False
222
+
223
+ def _should_skip_import_from(self, node: ast.ImportFrom) -> bool:
224
+ """Check if ImportFrom node should be skipped.
225
+
226
+ Args:
227
+ node: ImportFrom node to check.
228
+
229
+ Returns:
230
+ True if import should be skipped.
231
+ """
232
+ if not node.module:
233
+ return False
234
+ return self._is_module_excluded(node.module)
235
+
236
+ def _should_skip_regular_import(self, node: ast.Import) -> bool:
237
+ """Check if Import node should be skipped.
238
+
239
+ Args:
240
+ node: Import node to check.
241
+
242
+ Returns:
243
+ True if any alias should be skipped.
244
+ """
245
+ return any(self._is_module_excluded(alias.name) for alias in node.names)
246
+
247
+ def _is_module_excluded(self, module_name: str) -> bool:
248
+ """Check if a module name should be excluded.
249
+
250
+ Args:
251
+ module_name: Module name to check.
252
+
253
+ Returns:
254
+ True if module is excluded.
255
+ """
256
+ # Exact match for glaip_sdk or match excluded submodules with boundary
257
+ if module_name == "glaip_sdk":
258
+ return True
259
+ return any(module_name == m or module_name.startswith(m + ".") for m in self.EXCLUDED_MODULES)
260
+
261
+ @staticmethod
262
+ def _build_import_strings(future_imports: list, regular_imports: list) -> list[str]:
263
+ """Build formatted import strings from import nodes.
264
+
265
+ Args:
266
+ future_imports: List of __future__ import nodes.
267
+ regular_imports: List of regular import nodes.
268
+
269
+ Returns:
270
+ Formatted import statements.
271
+ """
272
+ result = []
273
+
274
+ if future_imports:
275
+ result.append("# Future imports\n")
276
+ for node in future_imports:
277
+ result.append(ast.unparse(node) + "\n")
278
+ result.append("\n")
279
+
280
+ if regular_imports:
281
+ result.append("# External imports\n")
282
+ for node in regular_imports:
283
+ result.append(ast.unparse(node) + "\n")
284
+ result.append("\n")
285
+
286
+ return result
287
+
288
+ def inline_local_imports(
289
+ self,
290
+ local_imports: list,
291
+ processed_modules: set[str] | None = None,
292
+ ) -> tuple[list[str], list]:
293
+ """Inline local imports into bundled code and collect their external imports.
294
+
295
+ Recursively inlines nested local imports.
296
+
297
+ Args:
298
+ local_imports: List of (module_name, file_path, import_node) tuples.
299
+ processed_modules: Set of already processed module paths to avoid duplicates.
300
+
301
+ Returns:
302
+ Tuple of (inlined_code_strings, collected_external_imports).
303
+ """
304
+ if not local_imports:
305
+ return [], []
306
+
307
+ if processed_modules is None:
308
+ processed_modules = set()
309
+
310
+ result = ["# Inlined local imports\n"]
311
+ all_external_imports = []
312
+
313
+ for module_name, file_path, _ in local_imports:
314
+ if str(file_path) in processed_modules:
315
+ continue
316
+ processed_modules.add(str(file_path))
317
+
318
+ # Recursively inline nested local imports
319
+ nested_resolver = ImportResolver(file_path.parent)
320
+ with open(file_path, encoding="utf-8") as f:
321
+ source = f.read()
322
+ tree = ast.parse(source)
323
+ nested_local_imports, nested_external_imports = nested_resolver.categorize_imports(tree)
324
+
325
+ if nested_local_imports:
326
+ nested_code, nested_ext_imports = nested_resolver.inline_local_imports(
327
+ nested_local_imports, processed_modules
328
+ )
329
+ result.extend(nested_code)
330
+ all_external_imports.extend(nested_ext_imports)
331
+
332
+ # Inline this module's code
333
+ result.append(f"# --- Inlined from {module_name}.py ---\n")
334
+ code_lines, external_imports = self._extract_module_code(file_path, collect_imports=True)
335
+ result.extend(code_lines)
336
+ all_external_imports.extend(external_imports)
337
+ all_external_imports.extend(nested_external_imports)
338
+ result.append(f"# --- End of {module_name}.py ---\n\n")
339
+
340
+ return result, all_external_imports
341
+
342
+ def _extract_module_code(
343
+ self,
344
+ file_path: Path,
345
+ *,
346
+ collect_imports: bool = False,
347
+ ) -> tuple[list[str], list] | list[str]:
348
+ """Extract code from module, excluding imports and docstrings.
349
+
350
+ Args:
351
+ file_path: Path to the module file.
352
+ collect_imports: If True, also return external imports.
353
+
354
+ Returns:
355
+ If collect_imports is True: tuple of (code_lines, external_import_nodes)
356
+ Otherwise: list of code lines.
357
+ """
358
+ with open(file_path, encoding="utf-8") as f:
359
+ local_source = f.read()
360
+
361
+ local_tree = ast.parse(local_source)
362
+ tool_dir = file_path.parent
363
+
364
+ result, external_imports = self._process_module_nodes(local_tree, tool_dir, collect_imports)
365
+
366
+ if collect_imports:
367
+ return result, external_imports
368
+ return result
369
+
370
+ def _process_module_nodes(
371
+ self,
372
+ tree: ast.AST,
373
+ tool_dir: Path,
374
+ collect_imports: bool,
375
+ ) -> tuple[list[str], list]:
376
+ """Process AST nodes from a module.
377
+
378
+ Args:
379
+ tree: AST tree of the module.
380
+ tool_dir: Directory containing the module.
381
+ collect_imports: Whether to collect external imports.
382
+
383
+ Returns:
384
+ Tuple of (code_lines, external_imports).
385
+ """
386
+ result = []
387
+ external_imports = []
388
+
389
+ for local_node in tree.body:
390
+ if isinstance(local_node, (ast.Import, ast.ImportFrom)):
391
+ if collect_imports:
392
+ ext_import = self._get_external_import(local_node, tool_dir)
393
+ if ext_import:
394
+ external_imports.append(ext_import)
395
+ continue
396
+
397
+ if self._is_docstring(local_node):
398
+ continue
399
+
400
+ if isinstance(local_node, ast.ClassDef):
401
+ local_node = self._remove_tool_plugin_decorator(local_node)
402
+
403
+ result.append(ast.unparse(local_node) + "\n")
404
+
405
+ return result, external_imports
406
+
407
+ def _get_external_import(
408
+ self,
409
+ node: ast.Import | ast.ImportFrom,
410
+ tool_dir: Path,
411
+ ) -> ast.Import | ast.ImportFrom | None:
412
+ """Get external import node if not local.
413
+
414
+ Args:
415
+ node: Import node to check.
416
+ tool_dir: Directory containing the tool.
417
+
418
+ Returns:
419
+ The node if external, None if local.
420
+ """
421
+ if isinstance(node, ast.ImportFrom):
422
+ if node.module and node.module.startswith("."):
423
+ return None
424
+ temp_resolver = ImportResolver(tool_dir)
425
+ if temp_resolver.is_local_import(node):
426
+ return None
427
+ return node
428
+ if isinstance(node, ast.Import):
429
+ return node
430
+ return None
431
+
432
+ @staticmethod
433
+ def _is_docstring(node: ast.stmt) -> bool:
434
+ """Check if AST node is a docstring.
435
+
436
+ Args:
437
+ node: AST statement node.
438
+
439
+ Returns:
440
+ True if node is a docstring.
441
+ """
442
+ return isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant)
443
+
444
+ @staticmethod
445
+ def _remove_tool_plugin_decorator(node: ast.ClassDef) -> ast.ClassDef:
446
+ """Remove @tool_plugin decorator and BaseTool inheritance from a class node.
447
+
448
+ Args:
449
+ node: AST ClassDef node.
450
+
451
+ Returns:
452
+ Modified ClassDef node with decorator and base class removed.
453
+ """
454
+ node.decorator_list = ImportResolver._filter_decorators(node.decorator_list)
455
+ node.bases = ImportResolver._filter_bases(node.bases)
456
+ return node
457
+
458
+ @staticmethod
459
+ def _filter_decorators(decorator_list: list) -> list:
460
+ """Filter out @tool_plugin decorators.
461
+
462
+ Args:
463
+ decorator_list: List of decorator nodes.
464
+
465
+ Returns:
466
+ Filtered decorator list.
467
+ """
468
+ filtered = []
469
+ for decorator in decorator_list:
470
+ if ImportResolver._is_tool_plugin_decorator(decorator):
471
+ continue
472
+ filtered.append(decorator)
473
+ return filtered
474
+
475
+ @staticmethod
476
+ def _is_tool_plugin_decorator(decorator: ast.expr) -> bool:
477
+ """Check if decorator is @tool_plugin.
478
+
479
+ Args:
480
+ decorator: Decorator AST node.
481
+
482
+ Returns:
483
+ True if decorator is @tool_plugin.
484
+ """
485
+ if isinstance(decorator, ast.Name) and decorator.id == "tool_plugin":
486
+ return True
487
+ if (
488
+ isinstance(decorator, ast.Call)
489
+ and isinstance(decorator.func, ast.Name)
490
+ and decorator.func.id == "tool_plugin"
491
+ ):
492
+ return True
493
+ return False
494
+
495
+ @staticmethod
496
+ def _filter_bases(bases: list) -> list:
497
+ """Filter out BaseTool from base classes.
498
+
499
+ Args:
500
+ bases: List of base class nodes.
501
+
502
+ Returns:
503
+ Filtered base class list.
504
+ """
505
+ filtered = []
506
+ for base in bases:
507
+ is_base_tool = isinstance(base, ast.Name) and base.id == "BaseTool"
508
+ if not is_base_tool:
509
+ filtered.append(base)
510
+ return filtered if filtered else []
511
+
512
+
513
+ def load_class(import_path: str) -> type:
514
+ """Dynamically load a class from its import path.
515
+
516
+ Args:
517
+ import_path: Python import path (e.g., 'package.module.ClassName').
518
+
519
+ Returns:
520
+ The loaded class.
521
+
522
+ Raises:
523
+ ImportError: If the module or class cannot be imported.
524
+ """
525
+ try:
526
+ module_path, class_name = import_path.rsplit(".", 1)
527
+ module = importlib.import_module(module_path)
528
+ return getattr(module, class_name)
529
+ except (ValueError, ImportError, AttributeError) as e:
530
+ 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