code-puppy 0.0.373__py3-none-any.whl → 0.0.374__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.
- code_puppy/agents/agent_creator_agent.py +49 -1
- code_puppy/agents/agent_helios.py +122 -0
- code_puppy/agents/agent_manager.py +26 -2
- code_puppy/agents/json_agent.py +30 -7
- code_puppy/command_line/colors_menu.py +2 -0
- code_puppy/command_line/command_handler.py +1 -0
- code_puppy/command_line/config_commands.py +3 -1
- code_puppy/command_line/uc_menu.py +890 -0
- code_puppy/config.py +29 -0
- code_puppy/messaging/messages.py +18 -0
- code_puppy/messaging/rich_renderer.py +35 -0
- code_puppy/messaging/subagent_console.py +0 -1
- code_puppy/plugins/universal_constructor/__init__.py +13 -0
- code_puppy/plugins/universal_constructor/models.py +138 -0
- code_puppy/plugins/universal_constructor/register_callbacks.py +47 -0
- code_puppy/plugins/universal_constructor/registry.py +304 -0
- code_puppy/plugins/universal_constructor/sandbox.py +584 -0
- code_puppy/tools/__init__.py +138 -1
- code_puppy/tools/universal_constructor.py +889 -0
- {code_puppy-0.0.373.dist-info → code_puppy-0.0.374.dist-info}/METADATA +1 -1
- {code_puppy-0.0.373.dist-info → code_puppy-0.0.374.dist-info}/RECORD +26 -18
- {code_puppy-0.0.373.data → code_puppy-0.0.374.data}/data/code_puppy/models.json +0 -0
- {code_puppy-0.0.373.data → code_puppy-0.0.374.data}/data/code_puppy/models_dev_api.json +0 -0
- {code_puppy-0.0.373.dist-info → code_puppy-0.0.374.dist-info}/WHEEL +0 -0
- {code_puppy-0.0.373.dist-info → code_puppy-0.0.374.dist-info}/entry_points.txt +0 -0
- {code_puppy-0.0.373.dist-info → code_puppy-0.0.374.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
"""Code validation and safety checking for UC tools.
|
|
2
|
+
|
|
3
|
+
This module provides utilities for validating tool code before
|
|
4
|
+
execution or storage, including syntax checking, function extraction,
|
|
5
|
+
and dangerous pattern detection.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import ast
|
|
9
|
+
import logging
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, Dict, List, Optional, Set
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
# Required fields for TOOL_META
|
|
17
|
+
TOOL_META_REQUIRED_FIELDS = {"name", "description"}
|
|
18
|
+
|
|
19
|
+
# Imports that might indicate dangerous operations
|
|
20
|
+
DANGEROUS_IMPORTS: Set[str] = {
|
|
21
|
+
# Execution/code generation
|
|
22
|
+
"subprocess",
|
|
23
|
+
"os.system",
|
|
24
|
+
"shutil.rmtree",
|
|
25
|
+
"eval",
|
|
26
|
+
"exec",
|
|
27
|
+
"compile",
|
|
28
|
+
"__import__",
|
|
29
|
+
"importlib",
|
|
30
|
+
"multiprocessing",
|
|
31
|
+
"pickle",
|
|
32
|
+
"marshal",
|
|
33
|
+
# Network access
|
|
34
|
+
"socket",
|
|
35
|
+
"urllib",
|
|
36
|
+
"http.client",
|
|
37
|
+
"requests",
|
|
38
|
+
# System access
|
|
39
|
+
"platform",
|
|
40
|
+
"ctypes",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
# Dangerous function calls
|
|
44
|
+
DANGEROUS_CALLS: Set[str] = {
|
|
45
|
+
# Code execution
|
|
46
|
+
"eval",
|
|
47
|
+
"exec",
|
|
48
|
+
"compile",
|
|
49
|
+
"__import__",
|
|
50
|
+
"import_module",
|
|
51
|
+
# Process creation
|
|
52
|
+
"system",
|
|
53
|
+
"popen",
|
|
54
|
+
"spawn",
|
|
55
|
+
"fork",
|
|
56
|
+
"execv",
|
|
57
|
+
"execve",
|
|
58
|
+
"execvp",
|
|
59
|
+
"execl",
|
|
60
|
+
"execle",
|
|
61
|
+
"execlp",
|
|
62
|
+
# Scope manipulation
|
|
63
|
+
"globals",
|
|
64
|
+
"locals",
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
# open() calls with write modes are dangerous
|
|
68
|
+
DANGEROUS_OPEN_MODES = {"w", "a", "x", "wb", "ab", "xb", "w+", "a+", "r+", "rb+", "wb+"}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class FunctionInfo:
|
|
73
|
+
"""Information extracted from a function definition."""
|
|
74
|
+
|
|
75
|
+
name: str
|
|
76
|
+
signature: str
|
|
77
|
+
docstring: Optional[str] = None
|
|
78
|
+
parameters: List[str] = field(default_factory=list)
|
|
79
|
+
return_annotation: Optional[str] = None
|
|
80
|
+
is_async: bool = False
|
|
81
|
+
decorators: List[str] = field(default_factory=list)
|
|
82
|
+
line_number: int = 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class ValidationResult:
|
|
87
|
+
"""Result of code validation."""
|
|
88
|
+
|
|
89
|
+
valid: bool
|
|
90
|
+
errors: List[str] = field(default_factory=list)
|
|
91
|
+
warnings: List[str] = field(default_factory=list)
|
|
92
|
+
functions: List[FunctionInfo] = field(default_factory=list)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def validate_syntax(code: str) -> ValidationResult:
|
|
96
|
+
"""Validate Python syntax.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
code: Python source code to validate.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
ValidationResult with valid=True if syntax is correct,
|
|
103
|
+
or valid=False with error details.
|
|
104
|
+
"""
|
|
105
|
+
result = ValidationResult(valid=True)
|
|
106
|
+
|
|
107
|
+
try:
|
|
108
|
+
ast.parse(code)
|
|
109
|
+
except SyntaxError as e:
|
|
110
|
+
result.valid = False
|
|
111
|
+
line_info = f" (line {e.lineno})" if e.lineno else ""
|
|
112
|
+
result.errors.append(f"Syntax error{line_info}: {e.msg}")
|
|
113
|
+
|
|
114
|
+
return result
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def extract_function_info(code: str) -> ValidationResult:
|
|
118
|
+
"""Extract function information from Python code.
|
|
119
|
+
|
|
120
|
+
Parses the code and extracts information about all function
|
|
121
|
+
definitions including name, signature, docstring, and parameters.
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
code: Python source code.
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
ValidationResult containing list of FunctionInfo objects.
|
|
128
|
+
"""
|
|
129
|
+
result = validate_syntax(code)
|
|
130
|
+
if not result.valid:
|
|
131
|
+
return result
|
|
132
|
+
|
|
133
|
+
try:
|
|
134
|
+
tree = ast.parse(code)
|
|
135
|
+
except SyntaxError:
|
|
136
|
+
return result
|
|
137
|
+
|
|
138
|
+
for node in ast.walk(tree):
|
|
139
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
140
|
+
func_info = _extract_single_function(node)
|
|
141
|
+
result.functions.append(func_info)
|
|
142
|
+
|
|
143
|
+
return result
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _extract_single_function(
|
|
147
|
+
node: ast.FunctionDef | ast.AsyncFunctionDef,
|
|
148
|
+
) -> FunctionInfo:
|
|
149
|
+
"""Extract info from a single function AST node."""
|
|
150
|
+
# Get parameter names
|
|
151
|
+
params = []
|
|
152
|
+
for arg in node.args.args:
|
|
153
|
+
param_str = arg.arg
|
|
154
|
+
if arg.annotation:
|
|
155
|
+
param_str += f": {ast.unparse(arg.annotation)}"
|
|
156
|
+
params.append(param_str)
|
|
157
|
+
|
|
158
|
+
# Handle *args and **kwargs
|
|
159
|
+
if node.args.vararg:
|
|
160
|
+
vararg = f"*{node.args.vararg.arg}"
|
|
161
|
+
if node.args.vararg.annotation:
|
|
162
|
+
vararg += f": {ast.unparse(node.args.vararg.annotation)}"
|
|
163
|
+
params.append(vararg)
|
|
164
|
+
|
|
165
|
+
if node.args.kwarg:
|
|
166
|
+
kwarg = f"**{node.args.kwarg.arg}"
|
|
167
|
+
if node.args.kwarg.annotation:
|
|
168
|
+
kwarg += f": {ast.unparse(node.args.kwarg.annotation)}"
|
|
169
|
+
params.append(kwarg)
|
|
170
|
+
|
|
171
|
+
# Build signature string
|
|
172
|
+
signature = f"{node.name}({', '.join(params)})"
|
|
173
|
+
|
|
174
|
+
# Get return annotation
|
|
175
|
+
return_annotation = None
|
|
176
|
+
if node.returns:
|
|
177
|
+
return_annotation = ast.unparse(node.returns)
|
|
178
|
+
signature += f" -> {return_annotation}"
|
|
179
|
+
|
|
180
|
+
# Get docstring
|
|
181
|
+
docstring = ast.get_docstring(node)
|
|
182
|
+
|
|
183
|
+
# Get decorators
|
|
184
|
+
decorators = []
|
|
185
|
+
for dec in node.decorator_list:
|
|
186
|
+
decorators.append(ast.unparse(dec))
|
|
187
|
+
|
|
188
|
+
return FunctionInfo(
|
|
189
|
+
name=node.name,
|
|
190
|
+
signature=signature,
|
|
191
|
+
docstring=docstring,
|
|
192
|
+
parameters=params,
|
|
193
|
+
return_annotation=return_annotation,
|
|
194
|
+
is_async=isinstance(node, ast.AsyncFunctionDef),
|
|
195
|
+
decorators=decorators,
|
|
196
|
+
line_number=node.lineno,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def check_dangerous_patterns(code: str) -> ValidationResult:
|
|
201
|
+
"""Check for potentially dangerous patterns in code.
|
|
202
|
+
|
|
203
|
+
This is an advisory check - it warns about patterns that might
|
|
204
|
+
be dangerous but doesn't prevent tool execution. Users should
|
|
205
|
+
review warned code before trusting it.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
code: Python source code to check.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
ValidationResult with warnings for dangerous patterns.
|
|
212
|
+
"""
|
|
213
|
+
result = validate_syntax(code)
|
|
214
|
+
if not result.valid:
|
|
215
|
+
return result
|
|
216
|
+
|
|
217
|
+
try:
|
|
218
|
+
tree = ast.parse(code)
|
|
219
|
+
except SyntaxError:
|
|
220
|
+
return result
|
|
221
|
+
|
|
222
|
+
# Track dangerous imports
|
|
223
|
+
dangerous_found: List[str] = []
|
|
224
|
+
|
|
225
|
+
for node in ast.walk(tree):
|
|
226
|
+
# Check imports
|
|
227
|
+
if isinstance(node, ast.Import):
|
|
228
|
+
for alias in node.names:
|
|
229
|
+
if alias.name in DANGEROUS_IMPORTS:
|
|
230
|
+
dangerous_found.append(f"import {alias.name}")
|
|
231
|
+
|
|
232
|
+
elif isinstance(node, ast.ImportFrom):
|
|
233
|
+
module = node.module or ""
|
|
234
|
+
for alias in node.names:
|
|
235
|
+
full_name = f"{module}.{alias.name}"
|
|
236
|
+
if module in DANGEROUS_IMPORTS or full_name in DANGEROUS_IMPORTS:
|
|
237
|
+
dangerous_found.append(f"from {module} import {alias.name}")
|
|
238
|
+
|
|
239
|
+
# Check function calls
|
|
240
|
+
elif isinstance(node, ast.Call):
|
|
241
|
+
func_name = _get_call_name(node)
|
|
242
|
+
if func_name in DANGEROUS_CALLS:
|
|
243
|
+
line = getattr(node, "lineno", "?")
|
|
244
|
+
dangerous_found.append(f"{func_name}() call at line {line}")
|
|
245
|
+
# Special handling for open() - check if write mode is used
|
|
246
|
+
elif func_name == "open":
|
|
247
|
+
if _is_dangerous_open_call(node):
|
|
248
|
+
line = getattr(node, "lineno", "?")
|
|
249
|
+
dangerous_found.append(f"open() with write mode at line {line}")
|
|
250
|
+
|
|
251
|
+
# Add warnings for dangerous patterns
|
|
252
|
+
if dangerous_found:
|
|
253
|
+
result.warnings.append(
|
|
254
|
+
f"Potentially dangerous patterns found: {', '.join(dangerous_found)}"
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
return result
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _get_call_name(node: ast.Call) -> str:
|
|
261
|
+
"""Extract the function name from a Call node."""
|
|
262
|
+
if isinstance(node.func, ast.Name):
|
|
263
|
+
return node.func.id
|
|
264
|
+
elif isinstance(node.func, ast.Attribute):
|
|
265
|
+
return node.func.attr
|
|
266
|
+
return ""
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _is_dangerous_open_call(node: ast.Call) -> bool:
|
|
270
|
+
"""Check if an open() call uses a dangerous (write) mode.
|
|
271
|
+
|
|
272
|
+
Args:
|
|
273
|
+
node: AST Call node for open()
|
|
274
|
+
|
|
275
|
+
Returns:
|
|
276
|
+
True if the open call uses a write mode, False otherwise.
|
|
277
|
+
"""
|
|
278
|
+
# Check positional args - mode is typically the second argument
|
|
279
|
+
if len(node.args) >= 2:
|
|
280
|
+
mode_arg = node.args[1]
|
|
281
|
+
if isinstance(mode_arg, ast.Constant) and isinstance(mode_arg.value, str):
|
|
282
|
+
return mode_arg.value in DANGEROUS_OPEN_MODES
|
|
283
|
+
|
|
284
|
+
# Check keyword arguments
|
|
285
|
+
for kw in node.keywords:
|
|
286
|
+
if kw.arg == "mode":
|
|
287
|
+
if isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
|
|
288
|
+
return kw.value.value in DANGEROUS_OPEN_MODES
|
|
289
|
+
|
|
290
|
+
# If no mode specified, open() defaults to "r" which is safe
|
|
291
|
+
return False
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def full_validation(code: str) -> ValidationResult:
|
|
295
|
+
"""Perform full validation including syntax, function extraction, and safety.
|
|
296
|
+
|
|
297
|
+
Args:
|
|
298
|
+
code: Python source code to validate.
|
|
299
|
+
|
|
300
|
+
Returns:
|
|
301
|
+
Complete ValidationResult with all checks performed.
|
|
302
|
+
"""
|
|
303
|
+
# Start with syntax validation
|
|
304
|
+
result = validate_syntax(code)
|
|
305
|
+
if not result.valid:
|
|
306
|
+
return result
|
|
307
|
+
|
|
308
|
+
# Extract function info
|
|
309
|
+
func_result = extract_function_info(code)
|
|
310
|
+
result.functions = func_result.functions
|
|
311
|
+
|
|
312
|
+
# Check dangerous patterns
|
|
313
|
+
safety_result = check_dangerous_patterns(code)
|
|
314
|
+
result.warnings.extend(safety_result.warnings)
|
|
315
|
+
|
|
316
|
+
# Additional validation: ensure there's at least one function
|
|
317
|
+
if not result.functions:
|
|
318
|
+
result.warnings.append("No functions found in code - tool may not be callable")
|
|
319
|
+
|
|
320
|
+
return result
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
@dataclass
|
|
324
|
+
class ToolFileValidationResult(ValidationResult):
|
|
325
|
+
"""Extended validation result for tool files.
|
|
326
|
+
|
|
327
|
+
Includes TOOL_META extraction and main function validation.
|
|
328
|
+
"""
|
|
329
|
+
|
|
330
|
+
tool_meta: Optional[Dict[str, Any]] = None
|
|
331
|
+
main_function: Optional[FunctionInfo] = None
|
|
332
|
+
file_path: Optional[Path] = None
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _extract_tool_meta(code: str) -> Optional[Dict[str, Any]]:
|
|
336
|
+
"""Extract TOOL_META dictionary from code.
|
|
337
|
+
|
|
338
|
+
Args:
|
|
339
|
+
code: Python source code containing TOOL_META.
|
|
340
|
+
|
|
341
|
+
Returns:
|
|
342
|
+
The TOOL_META dict if found and valid, None otherwise.
|
|
343
|
+
"""
|
|
344
|
+
try:
|
|
345
|
+
tree = ast.parse(code)
|
|
346
|
+
except SyntaxError:
|
|
347
|
+
return None
|
|
348
|
+
|
|
349
|
+
for node in ast.walk(tree):
|
|
350
|
+
if isinstance(node, ast.Assign):
|
|
351
|
+
for target in node.targets:
|
|
352
|
+
if isinstance(target, ast.Name) and target.id == "TOOL_META":
|
|
353
|
+
# Try to evaluate the dict literal
|
|
354
|
+
if isinstance(node.value, ast.Dict):
|
|
355
|
+
try:
|
|
356
|
+
# Safely evaluate the dict using ast.literal_eval
|
|
357
|
+
meta_str = ast.unparse(node.value)
|
|
358
|
+
return ast.literal_eval(meta_str)
|
|
359
|
+
except (ValueError, SyntaxError):
|
|
360
|
+
return None
|
|
361
|
+
return None
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _validate_tool_meta(meta: Dict[str, Any]) -> List[str]:
|
|
365
|
+
"""Validate that TOOL_META has required fields.
|
|
366
|
+
|
|
367
|
+
Args:
|
|
368
|
+
meta: The TOOL_META dictionary to validate.
|
|
369
|
+
|
|
370
|
+
Returns:
|
|
371
|
+
List of error messages (empty if valid).
|
|
372
|
+
"""
|
|
373
|
+
errors = []
|
|
374
|
+
for field_name in TOOL_META_REQUIRED_FIELDS:
|
|
375
|
+
if field_name not in meta:
|
|
376
|
+
errors.append(f"TOOL_META missing required field: '{field_name}'")
|
|
377
|
+
elif not meta[field_name]:
|
|
378
|
+
errors.append(f"TOOL_META field '{field_name}' cannot be empty")
|
|
379
|
+
return errors
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _find_main_function(
|
|
383
|
+
functions: List[FunctionInfo], tool_name: str
|
|
384
|
+
) -> Optional[FunctionInfo]:
|
|
385
|
+
"""Find the main function for a tool.
|
|
386
|
+
|
|
387
|
+
The main function is expected to have the same name as the tool.
|
|
388
|
+
|
|
389
|
+
Args:
|
|
390
|
+
functions: List of functions found in the code.
|
|
391
|
+
tool_name: Expected name of the main function.
|
|
392
|
+
|
|
393
|
+
Returns:
|
|
394
|
+
The main FunctionInfo if found, None otherwise.
|
|
395
|
+
"""
|
|
396
|
+
for func in functions:
|
|
397
|
+
if func.name == tool_name:
|
|
398
|
+
return func
|
|
399
|
+
return None
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def validate_tool_file(file_path: Path) -> ToolFileValidationResult:
|
|
403
|
+
"""Validate a tool file including TOOL_META and main function.
|
|
404
|
+
|
|
405
|
+
This function performs comprehensive validation:
|
|
406
|
+
1. Reads the file content
|
|
407
|
+
2. Validates Python syntax
|
|
408
|
+
3. Extracts and validates TOOL_META dict
|
|
409
|
+
4. Extracts and validates the main function
|
|
410
|
+
5. Checks for dangerous patterns
|
|
411
|
+
|
|
412
|
+
Args:
|
|
413
|
+
file_path: Path to the tool file to validate.
|
|
414
|
+
|
|
415
|
+
Returns:
|
|
416
|
+
ToolFileValidationResult with all validation details.
|
|
417
|
+
"""
|
|
418
|
+
result = ToolFileValidationResult(valid=True, file_path=file_path)
|
|
419
|
+
|
|
420
|
+
# Check file exists
|
|
421
|
+
if not file_path.exists():
|
|
422
|
+
result.valid = False
|
|
423
|
+
result.errors.append(f"File not found: {file_path}")
|
|
424
|
+
return result
|
|
425
|
+
|
|
426
|
+
if not file_path.is_file():
|
|
427
|
+
result.valid = False
|
|
428
|
+
result.errors.append(f"Path is not a file: {file_path}")
|
|
429
|
+
return result
|
|
430
|
+
|
|
431
|
+
# Read file content
|
|
432
|
+
try:
|
|
433
|
+
code = file_path.read_text(encoding="utf-8")
|
|
434
|
+
except Exception as e:
|
|
435
|
+
result.valid = False
|
|
436
|
+
result.errors.append(f"Failed to read file: {e}")
|
|
437
|
+
return result
|
|
438
|
+
|
|
439
|
+
# Validate syntax
|
|
440
|
+
syntax_result = validate_syntax(code)
|
|
441
|
+
if not syntax_result.valid:
|
|
442
|
+
result.valid = False
|
|
443
|
+
result.errors.extend(syntax_result.errors)
|
|
444
|
+
return result
|
|
445
|
+
|
|
446
|
+
# Extract TOOL_META
|
|
447
|
+
meta = _extract_tool_meta(code)
|
|
448
|
+
if meta is None:
|
|
449
|
+
result.valid = False
|
|
450
|
+
result.errors.append("TOOL_META not found or invalid in file")
|
|
451
|
+
return result
|
|
452
|
+
|
|
453
|
+
result.tool_meta = meta
|
|
454
|
+
|
|
455
|
+
# Validate TOOL_META has required fields
|
|
456
|
+
meta_errors = _validate_tool_meta(meta)
|
|
457
|
+
if meta_errors:
|
|
458
|
+
result.valid = False
|
|
459
|
+
result.errors.extend(meta_errors)
|
|
460
|
+
return result
|
|
461
|
+
|
|
462
|
+
# Extract functions
|
|
463
|
+
func_result = extract_function_info(code)
|
|
464
|
+
result.functions = func_result.functions
|
|
465
|
+
|
|
466
|
+
# Find main function (should match tool name)
|
|
467
|
+
tool_name = meta.get("name", "")
|
|
468
|
+
main_func = _find_main_function(result.functions, tool_name)
|
|
469
|
+
if main_func is None:
|
|
470
|
+
result.warnings.append(
|
|
471
|
+
f"No function named '{tool_name}' found - "
|
|
472
|
+
f"tool may not be callable as expected"
|
|
473
|
+
)
|
|
474
|
+
else:
|
|
475
|
+
result.main_function = main_func
|
|
476
|
+
|
|
477
|
+
# Check dangerous patterns
|
|
478
|
+
safety_result = check_dangerous_patterns(code)
|
|
479
|
+
result.warnings.extend(safety_result.warnings)
|
|
480
|
+
|
|
481
|
+
return result
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _validate_safe_path(file_path: Path, safe_root: Path) -> bool:
|
|
485
|
+
"""Validate that file_path is contained within safe_root.
|
|
486
|
+
|
|
487
|
+
Args:
|
|
488
|
+
file_path: The path to validate.
|
|
489
|
+
safe_root: The root directory that file_path must be within.
|
|
490
|
+
|
|
491
|
+
Returns:
|
|
492
|
+
True if file_path is safely within safe_root, False otherwise.
|
|
493
|
+
"""
|
|
494
|
+
try:
|
|
495
|
+
# Resolve both paths to absolute paths
|
|
496
|
+
resolved_path = file_path.resolve()
|
|
497
|
+
resolved_root = safe_root.resolve()
|
|
498
|
+
# Check if the resolved path is relative to the root
|
|
499
|
+
resolved_path.relative_to(resolved_root)
|
|
500
|
+
return True
|
|
501
|
+
except ValueError:
|
|
502
|
+
return False
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def validate_and_write_tool(
|
|
506
|
+
code: str, file_path: Path, safe_root: Optional[Path] = None
|
|
507
|
+
) -> ToolFileValidationResult:
|
|
508
|
+
"""Validate code and write to file only if valid.
|
|
509
|
+
|
|
510
|
+
This function performs full validation before writing,
|
|
511
|
+
ensuring only valid tool code is persisted to disk.
|
|
512
|
+
|
|
513
|
+
Args:
|
|
514
|
+
code: Python source code for the tool.
|
|
515
|
+
file_path: Path where the tool file should be written.
|
|
516
|
+
safe_root: Optional root directory to validate against. Defaults to USER_UC_DIR.
|
|
517
|
+
Pass the parent directory of file_path to skip validation (for testing).
|
|
518
|
+
|
|
519
|
+
Returns:
|
|
520
|
+
ToolFileValidationResult indicating success/failure.
|
|
521
|
+
If valid, the file will be written to file_path.
|
|
522
|
+
"""
|
|
523
|
+
from . import USER_UC_DIR
|
|
524
|
+
|
|
525
|
+
result = ToolFileValidationResult(valid=True, file_path=file_path)
|
|
526
|
+
|
|
527
|
+
# Validate path is within safe root directory (prevent path traversal)
|
|
528
|
+
root_to_check = safe_root if safe_root is not None else USER_UC_DIR
|
|
529
|
+
if not _validate_safe_path(file_path, root_to_check):
|
|
530
|
+
result.valid = False
|
|
531
|
+
result.errors.append(f"Unsafe file path: must be within {root_to_check}")
|
|
532
|
+
return result
|
|
533
|
+
syntax_result = validate_syntax(code)
|
|
534
|
+
if not syntax_result.valid:
|
|
535
|
+
result.valid = False
|
|
536
|
+
result.errors.extend(syntax_result.errors)
|
|
537
|
+
return result
|
|
538
|
+
|
|
539
|
+
# Extract and validate TOOL_META
|
|
540
|
+
meta = _extract_tool_meta(code)
|
|
541
|
+
if meta is None:
|
|
542
|
+
result.valid = False
|
|
543
|
+
result.errors.append("TOOL_META not found or invalid in code")
|
|
544
|
+
return result
|
|
545
|
+
|
|
546
|
+
result.tool_meta = meta
|
|
547
|
+
|
|
548
|
+
# Validate TOOL_META has required fields
|
|
549
|
+
meta_errors = _validate_tool_meta(meta)
|
|
550
|
+
if meta_errors:
|
|
551
|
+
result.valid = False
|
|
552
|
+
result.errors.extend(meta_errors)
|
|
553
|
+
return result
|
|
554
|
+
|
|
555
|
+
# Extract functions
|
|
556
|
+
func_result = extract_function_info(code)
|
|
557
|
+
result.functions = func_result.functions
|
|
558
|
+
|
|
559
|
+
# Find main function
|
|
560
|
+
tool_name = meta.get("name", "")
|
|
561
|
+
main_func = _find_main_function(result.functions, tool_name)
|
|
562
|
+
if main_func is None:
|
|
563
|
+
result.warnings.append(
|
|
564
|
+
f"No function named '{tool_name}' found - "
|
|
565
|
+
f"tool may not be callable as expected"
|
|
566
|
+
)
|
|
567
|
+
else:
|
|
568
|
+
result.main_function = main_func
|
|
569
|
+
|
|
570
|
+
# Check dangerous patterns (warnings only, don't fail)
|
|
571
|
+
safety_result = check_dangerous_patterns(code)
|
|
572
|
+
result.warnings.extend(safety_result.warnings)
|
|
573
|
+
|
|
574
|
+
# If we got here, validation passed - write the file
|
|
575
|
+
try:
|
|
576
|
+
# Ensure parent directory exists
|
|
577
|
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
578
|
+
file_path.write_text(code, encoding="utf-8")
|
|
579
|
+
except Exception as e:
|
|
580
|
+
result.valid = False
|
|
581
|
+
result.errors.append(f"Failed to write file: {e}")
|
|
582
|
+
return result
|
|
583
|
+
|
|
584
|
+
return result
|