alita-sdk 0.3.449__py3-none-any.whl → 0.3.465__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.

Potentially problematic release.


This version of alita-sdk might be problematic. Click here for more details.

Files changed (74) hide show
  1. alita_sdk/cli/__init__.py +10 -0
  2. alita_sdk/cli/__main__.py +17 -0
  3. alita_sdk/cli/agent/__init__.py +0 -0
  4. alita_sdk/cli/agent/default.py +176 -0
  5. alita_sdk/cli/agent_executor.py +155 -0
  6. alita_sdk/cli/agent_loader.py +197 -0
  7. alita_sdk/cli/agent_ui.py +218 -0
  8. alita_sdk/cli/agents.py +1911 -0
  9. alita_sdk/cli/callbacks.py +576 -0
  10. alita_sdk/cli/cli.py +159 -0
  11. alita_sdk/cli/config.py +164 -0
  12. alita_sdk/cli/formatting.py +182 -0
  13. alita_sdk/cli/input_handler.py +256 -0
  14. alita_sdk/cli/mcp_loader.py +315 -0
  15. alita_sdk/cli/toolkit.py +330 -0
  16. alita_sdk/cli/toolkit_loader.py +55 -0
  17. alita_sdk/cli/tools/__init__.py +36 -0
  18. alita_sdk/cli/tools/approval.py +224 -0
  19. alita_sdk/cli/tools/filesystem.py +905 -0
  20. alita_sdk/cli/tools/planning.py +403 -0
  21. alita_sdk/cli/tools/terminal.py +280 -0
  22. alita_sdk/runtime/clients/client.py +16 -1
  23. alita_sdk/runtime/langchain/constants.py +2 -1
  24. alita_sdk/runtime/langchain/langraph_agent.py +74 -20
  25. alita_sdk/runtime/langchain/utils.py +20 -4
  26. alita_sdk/runtime/toolkits/artifact.py +5 -6
  27. alita_sdk/runtime/toolkits/mcp.py +5 -2
  28. alita_sdk/runtime/toolkits/tools.py +1 -0
  29. alita_sdk/runtime/tools/function.py +19 -6
  30. alita_sdk/runtime/tools/llm.py +65 -7
  31. alita_sdk/runtime/tools/vectorstore_base.py +17 -2
  32. alita_sdk/runtime/utils/mcp_sse_client.py +64 -6
  33. alita_sdk/tools/ado/repos/__init__.py +1 -0
  34. alita_sdk/tools/ado/test_plan/__init__.py +1 -1
  35. alita_sdk/tools/ado/wiki/__init__.py +1 -5
  36. alita_sdk/tools/ado/work_item/__init__.py +1 -5
  37. alita_sdk/tools/base_indexer_toolkit.py +64 -8
  38. alita_sdk/tools/bitbucket/__init__.py +1 -0
  39. alita_sdk/tools/code/sonar/__init__.py +1 -1
  40. alita_sdk/tools/confluence/__init__.py +2 -2
  41. alita_sdk/tools/github/__init__.py +2 -2
  42. alita_sdk/tools/gitlab/__init__.py +2 -1
  43. alita_sdk/tools/gitlab_org/__init__.py +1 -2
  44. alita_sdk/tools/google_places/__init__.py +2 -1
  45. alita_sdk/tools/jira/__init__.py +1 -0
  46. alita_sdk/tools/memory/__init__.py +1 -1
  47. alita_sdk/tools/pandas/__init__.py +1 -1
  48. alita_sdk/tools/postman/__init__.py +2 -1
  49. alita_sdk/tools/pptx/__init__.py +2 -2
  50. alita_sdk/tools/qtest/__init__.py +3 -3
  51. alita_sdk/tools/qtest/api_wrapper.py +1235 -51
  52. alita_sdk/tools/rally/__init__.py +1 -2
  53. alita_sdk/tools/report_portal/__init__.py +1 -0
  54. alita_sdk/tools/salesforce/__init__.py +1 -0
  55. alita_sdk/tools/servicenow/__init__.py +2 -3
  56. alita_sdk/tools/sharepoint/__init__.py +1 -0
  57. alita_sdk/tools/sharepoint/api_wrapper.py +22 -2
  58. alita_sdk/tools/sharepoint/authorization_helper.py +17 -1
  59. alita_sdk/tools/slack/__init__.py +1 -0
  60. alita_sdk/tools/sql/__init__.py +2 -1
  61. alita_sdk/tools/testio/__init__.py +1 -0
  62. alita_sdk/tools/testrail/__init__.py +1 -3
  63. alita_sdk/tools/xray/__init__.py +2 -1
  64. alita_sdk/tools/zephyr/__init__.py +2 -1
  65. alita_sdk/tools/zephyr_enterprise/__init__.py +1 -0
  66. alita_sdk/tools/zephyr_essential/__init__.py +1 -0
  67. alita_sdk/tools/zephyr_scale/__init__.py +1 -0
  68. alita_sdk/tools/zephyr_squad/__init__.py +1 -0
  69. {alita_sdk-0.3.449.dist-info → alita_sdk-0.3.465.dist-info}/METADATA +145 -2
  70. {alita_sdk-0.3.449.dist-info → alita_sdk-0.3.465.dist-info}/RECORD +74 -52
  71. alita_sdk-0.3.465.dist-info/entry_points.txt +2 -0
  72. {alita_sdk-0.3.449.dist-info → alita_sdk-0.3.465.dist-info}/WHEEL +0 -0
  73. {alita_sdk-0.3.449.dist-info → alita_sdk-0.3.465.dist-info}/licenses/LICENSE +0 -0
  74. {alita_sdk-0.3.449.dist-info → alita_sdk-0.3.465.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,330 @@
1
+ """
2
+ Toolkit testing commands for Alita CLI.
3
+
4
+ Provides commands to list, inspect, and test toolkits directly from the command line.
5
+ """
6
+
7
+ import click
8
+ import json
9
+ import logging
10
+ from typing import Optional, Dict, Any
11
+
12
+ from .cli import get_client
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ @click.group()
18
+ def toolkit():
19
+ """Toolkit testing commands."""
20
+ pass
21
+
22
+
23
+ @toolkit.command('list')
24
+ @click.option('--failed', is_flag=True, help='Show failed imports')
25
+ @click.pass_context
26
+ def toolkit_list(ctx, failed: bool):
27
+ """List all available toolkits."""
28
+ formatter = ctx.obj['formatter']
29
+
30
+ try:
31
+ # Import toolkit registry
32
+ from alita_sdk.tools import AVAILABLE_TOOLS, AVAILABLE_TOOLKITS, FAILED_IMPORTS
33
+
34
+ if failed:
35
+ # Show failed imports
36
+ if FAILED_IMPORTS:
37
+ click.echo("\nFailed toolkit imports:\n")
38
+ for name, error in FAILED_IMPORTS.items():
39
+ click.echo(f" - {name}: {error}")
40
+ click.echo(f"\nTotal failed: {len(FAILED_IMPORTS)}")
41
+ else:
42
+ click.echo("\nNo failed imports")
43
+ return
44
+
45
+ # Build toolkit list
46
+ toolkits = []
47
+ for name, toolkit_dict in AVAILABLE_TOOLS.items():
48
+ toolkit_class_name = None
49
+ if 'toolkit_class' in toolkit_dict:
50
+ toolkit_class_name = toolkit_dict['toolkit_class'].__name__
51
+
52
+ toolkits.append({
53
+ 'name': name,
54
+ 'class_name': toolkit_class_name,
55
+ 'has_get_tools': 'get_tools' in toolkit_dict
56
+ })
57
+
58
+ # Format and display
59
+ output = formatter.format_toolkit_list(toolkits)
60
+ click.echo(output)
61
+
62
+ except Exception as e:
63
+ logger.exception("Failed to list toolkits")
64
+ click.echo(formatter.format_error(str(e)), err=True)
65
+ raise click.Abort()
66
+
67
+
68
+ @toolkit.command('schema')
69
+ @click.argument('toolkit_name')
70
+ @click.pass_context
71
+ def toolkit_schema(ctx, toolkit_name: str):
72
+ """
73
+ Show configuration schema for a toolkit.
74
+
75
+ TOOLKIT_NAME: Name of the toolkit (e.g., 'jira', 'github', 'confluence')
76
+ """
77
+ formatter = ctx.obj['formatter']
78
+
79
+ try:
80
+ # Import toolkit registry
81
+ from alita_sdk.tools import AVAILABLE_TOOLKITS
82
+
83
+ # Find toolkit class
84
+ toolkit_class = None
85
+ for name, cls in AVAILABLE_TOOLKITS.items():
86
+ if name.lower().replace('toolkit', '').replace('alita', '').strip() == toolkit_name.lower():
87
+ toolkit_class = cls
88
+ break
89
+
90
+ if not toolkit_class:
91
+ # Try direct match
92
+ for name, cls in AVAILABLE_TOOLKITS.items():
93
+ if toolkit_name.lower() in name.lower():
94
+ toolkit_class = cls
95
+ break
96
+
97
+ if not toolkit_class:
98
+ available = [name.lower().replace('toolkit', '').replace('alita', '').strip()
99
+ for name in AVAILABLE_TOOLKITS.keys()]
100
+ raise click.ClickException(
101
+ f"Toolkit '{toolkit_name}' not found.\n"
102
+ f"Available toolkits: {', '.join(sorted(set(available)))}"
103
+ )
104
+
105
+ # Get schema
106
+ schema_model = toolkit_class.toolkit_config_schema()
107
+ schema = schema_model.model_json_schema()
108
+
109
+ # Format and display
110
+ if formatter.__class__.__name__ == 'JSONFormatter':
111
+ output = formatter.format_toolkit_schema(toolkit_name, schema)
112
+ else:
113
+ output = formatter.format_toolkit_schema(toolkit_name, schema)
114
+
115
+ click.echo(output)
116
+
117
+ except click.ClickException:
118
+ raise
119
+ except Exception as e:
120
+ logger.exception(f"Failed to get schema for toolkit '{toolkit_name}'")
121
+ click.echo(formatter.format_error(str(e)), err=True)
122
+ raise click.Abort()
123
+
124
+
125
+ @toolkit.command('test')
126
+ @click.argument('toolkit_type')
127
+ @click.option('--tool', required=True, help='Tool name to execute')
128
+ @click.option('--config', 'config_file', type=click.File('r'),
129
+ help='Toolkit configuration JSON file')
130
+ @click.option('--params', type=click.File('r'),
131
+ help='Tool parameters JSON file')
132
+ @click.option('--param', multiple=True,
133
+ help='Tool parameter as key=value (can be used multiple times)')
134
+ @click.option('--llm-model', default='gpt-4o-mini',
135
+ help='LLM model to use (default: gpt-4o-mini)')
136
+ @click.option('--temperature', default=0.1, type=float,
137
+ help='LLM temperature (default: 0.1)')
138
+ @click.option('--max-tokens', default=1000, type=int,
139
+ help='LLM max tokens (default: 1000)')
140
+ @click.pass_context
141
+ def toolkit_test(ctx, toolkit_type: str, tool: str, config_file, params,
142
+ param, llm_model: str, temperature: float, max_tokens: int):
143
+ """
144
+ Test a specific tool from a toolkit.
145
+
146
+ TOOLKIT_TYPE: Type of toolkit (e.g., 'jira', 'github', 'confluence')
147
+
148
+ Examples:
149
+
150
+ # Test with config and params from files
151
+ alita-cli toolkit test jira --tool get_issue \\
152
+ --config jira-config.json --params params.json
153
+
154
+ # Test with inline parameters
155
+ alita-cli toolkit test jira --tool get_issue \\
156
+ --config jira-config.json --param issue_key=PROJ-123
157
+
158
+ # Test with JSON output for scripting
159
+ alita-cli --output json toolkit test github --tool get_issue \\
160
+ --config github-config.json --param owner=user --param repo=myrepo
161
+ """
162
+ formatter = ctx.obj['formatter']
163
+ client = get_client(ctx)
164
+
165
+ try:
166
+ # Load toolkit configuration
167
+ toolkit_config = {}
168
+ if config_file:
169
+ toolkit_config = json.load(config_file)
170
+ logger.debug(f"Loaded toolkit config from {config_file.name}")
171
+
172
+ # Load tool parameters
173
+ tool_params = {}
174
+ if params:
175
+ tool_params = json.load(params)
176
+ logger.debug(f"Loaded tool params from {params.name}")
177
+
178
+ # Parse inline parameters
179
+ if param:
180
+ for param_pair in param:
181
+ if '=' not in param_pair:
182
+ raise click.ClickException(
183
+ f"Invalid parameter format: '{param_pair}'. "
184
+ "Use --param key=value"
185
+ )
186
+ key, value = param_pair.split('=', 1)
187
+
188
+ # Try to parse as JSON for complex values
189
+ try:
190
+ tool_params[key] = json.loads(value)
191
+ except json.JSONDecodeError:
192
+ tool_params[key] = value
193
+
194
+ logger.debug(f"Parsed {len(param)} inline parameters")
195
+
196
+ # Prepare full toolkit configuration
197
+ full_config = {
198
+ 'toolkit_name': toolkit_type,
199
+ 'type': toolkit_type,
200
+ 'settings': toolkit_config
201
+ }
202
+
203
+ # LLM configuration
204
+ llm_config = {
205
+ 'temperature': temperature,
206
+ 'max_tokens': max_tokens,
207
+ 'top_p': 1.0
208
+ }
209
+
210
+ # Execute test
211
+ logger.info(f"Testing tool '{tool}' from toolkit '{toolkit_type}'")
212
+ result = client.test_toolkit_tool(
213
+ toolkit_config=full_config,
214
+ tool_name=tool,
215
+ tool_params=tool_params,
216
+ llm_model=llm_model,
217
+ llm_config=llm_config
218
+ )
219
+
220
+ # Format and display result
221
+ output = formatter.format_toolkit_result(result)
222
+ click.echo(output)
223
+
224
+ # Exit with error code if test failed
225
+ if not result.get('success', False):
226
+ raise click.Abort()
227
+
228
+ except click.ClickException:
229
+ raise
230
+ except Exception as e:
231
+ logger.exception("Failed to execute toolkit test")
232
+ click.echo(formatter.format_error(str(e)), err=True)
233
+ raise click.Abort()
234
+
235
+
236
+ @toolkit.command('tools')
237
+ @click.argument('toolkit_type')
238
+ @click.option('--config', 'config_file', type=click.File('r'),
239
+ help='Toolkit configuration JSON file (required for some toolkits)')
240
+ @click.pass_context
241
+ def toolkit_tools(ctx, toolkit_type: str, config_file):
242
+ """
243
+ List available tools for a specific toolkit.
244
+
245
+ TOOLKIT_TYPE: Type of toolkit (e.g., 'jira', 'github', 'confluence')
246
+
247
+ Some toolkits require configuration to determine available tools.
248
+ Use --config to provide configuration if needed.
249
+ """
250
+ formatter = ctx.obj['formatter']
251
+ client = get_client(ctx)
252
+
253
+ try:
254
+ # Load toolkit configuration if provided
255
+ toolkit_config = {}
256
+ if config_file:
257
+ toolkit_config = json.load(config_file)
258
+
259
+ # Import and instantiate toolkit
260
+ from alita_sdk.tools import AVAILABLE_TOOLS
261
+
262
+ if toolkit_type not in AVAILABLE_TOOLS:
263
+ raise click.ClickException(
264
+ f"Toolkit '{toolkit_type}' not found. "
265
+ f"Use 'alita-cli toolkit list' to see available toolkits."
266
+ )
267
+
268
+ toolkit_entry = AVAILABLE_TOOLS[toolkit_type]
269
+
270
+ if 'toolkit_class' not in toolkit_entry:
271
+ raise click.ClickException(
272
+ f"Toolkit '{toolkit_type}' does not support tool listing"
273
+ )
274
+
275
+ # Get toolkit class and instantiate
276
+ toolkit_class = toolkit_entry['toolkit_class']
277
+
278
+ # Create minimal configuration
279
+ full_config = {
280
+ 'toolkit_name': toolkit_type,
281
+ 'type': toolkit_type,
282
+ 'settings': toolkit_config
283
+ }
284
+
285
+ # Try to get available tools via API wrapper
286
+ try:
287
+ # Instantiate API wrapper if possible
288
+ api_wrapper_class = None
289
+
290
+ # Find API wrapper class by inspecting toolkit
291
+ import inspect
292
+ for name, obj in inspect.getmembers(toolkit_class):
293
+ if inspect.isclass(obj) and 'ApiWrapper' in obj.__name__:
294
+ api_wrapper_class = obj
295
+ break
296
+
297
+ if api_wrapper_class:
298
+ try:
299
+ api_wrapper = api_wrapper_class(**toolkit_config)
300
+ available_tools = api_wrapper.get_available_tools()
301
+
302
+ # Format tools list
303
+ click.echo(f"\nAvailable tools for {toolkit_type}:\n")
304
+ for tool_info in available_tools:
305
+ tool_name = tool_info.get('name', 'unknown')
306
+ description = tool_info.get('description', '')
307
+ click.echo(f" - {tool_name}")
308
+ if description:
309
+ click.echo(f" {description}")
310
+
311
+ click.echo(f"\nTotal: {len(available_tools)} tools")
312
+ return
313
+
314
+ except Exception as e:
315
+ logger.debug(f"Could not instantiate API wrapper: {e}")
316
+
317
+ # Fallback: show general info
318
+ click.echo(f"\n{toolkit_type} toolkit is available")
319
+ click.echo("Use 'alita-cli toolkit schema {toolkit_type}' to see configuration options")
320
+
321
+ except Exception as e:
322
+ logger.exception("Failed to list tools")
323
+ raise click.ClickException(str(e))
324
+
325
+ except click.ClickException:
326
+ raise
327
+ except Exception as e:
328
+ logger.exception("Failed to list toolkit tools")
329
+ click.echo(formatter.format_error(str(e)), err=True)
330
+ raise click.Abort()
@@ -0,0 +1,55 @@
1
+ """
2
+ Toolkit configuration loading and management.
3
+
4
+ Handles loading toolkit configurations from JSON/YAML files.
5
+ """
6
+
7
+ import json
8
+ import yaml
9
+ from pathlib import Path
10
+ from typing import Dict, Any, List
11
+
12
+ from .config import substitute_env_vars
13
+
14
+
15
+ def load_toolkit_config(file_path: str) -> Dict[str, Any]:
16
+ """Load toolkit configuration from JSON or YAML file with env var substitution."""
17
+ path = Path(file_path)
18
+
19
+ if not path.exists():
20
+ raise FileNotFoundError(f"Toolkit configuration not found: {file_path}")
21
+
22
+ with open(path) as f:
23
+ content = f.read()
24
+
25
+ # Apply environment variable substitution
26
+ content = substitute_env_vars(content)
27
+
28
+ # Parse based on file extension
29
+ if path.suffix in ['.yaml', '.yml']:
30
+ return yaml.safe_load(content)
31
+ else:
32
+ return json.loads(content)
33
+
34
+
35
+ def load_toolkit_configs(agent_def: Dict[str, Any], toolkit_config_paths: tuple) -> List[Dict[str, Any]]:
36
+ """Load all toolkit configurations from agent definition and CLI options."""
37
+ toolkit_configs = []
38
+
39
+ # Load from agent definition if present
40
+ if 'toolkit_configs' in agent_def:
41
+ for tk_config in agent_def['toolkit_configs']:
42
+ if isinstance(tk_config, dict):
43
+ if 'file' in tk_config:
44
+ config = load_toolkit_config(tk_config['file'])
45
+ toolkit_configs.append(config)
46
+ elif 'config' in tk_config:
47
+ toolkit_configs.append(tk_config['config'])
48
+
49
+ # Load from CLI options
50
+ if toolkit_config_paths:
51
+ for config_path in toolkit_config_paths:
52
+ config = load_toolkit_config(config_path)
53
+ toolkit_configs.append(config)
54
+
55
+ return toolkit_configs
@@ -0,0 +1,36 @@
1
+ """
2
+ CLI tools package.
3
+
4
+ Contains specialized tools for CLI agents.
5
+ """
6
+
7
+ from .filesystem import get_filesystem_tools
8
+ from .terminal import get_terminal_tools, create_default_blocked_patterns_file
9
+ from .planning import (
10
+ get_planning_tools,
11
+ PlanState,
12
+ list_sessions,
13
+ generate_session_id,
14
+ create_session_memory,
15
+ save_session_metadata,
16
+ load_session_metadata,
17
+ get_session_dir,
18
+ )
19
+ from .approval import create_approval_wrapper, ApprovalToolWrapper, prompt_approval
20
+
21
+ __all__ = [
22
+ 'get_filesystem_tools',
23
+ 'get_terminal_tools',
24
+ 'create_default_blocked_patterns_file',
25
+ 'get_planning_tools',
26
+ 'PlanState',
27
+ 'list_sessions',
28
+ 'generate_session_id',
29
+ 'create_session_memory',
30
+ 'save_session_metadata',
31
+ 'load_session_metadata',
32
+ 'get_session_dir',
33
+ 'create_approval_wrapper',
34
+ 'ApprovalToolWrapper',
35
+ 'prompt_approval',
36
+ ]
@@ -0,0 +1,224 @@
1
+ """
2
+ Tool approval wrapper for CLI.
3
+
4
+ Wraps tools to require user approval before execution based on approval mode.
5
+ Modes:
6
+ - 'always': Always require approval for each tool call
7
+ - 'auto': No approval required (automatic execution)
8
+ - 'yolo': No approval and no safety checks (use with caution)
9
+ """
10
+
11
+ import functools
12
+ from typing import Any, Callable, Dict, List, Optional, Set
13
+ from rich.console import Console
14
+ from rich.panel import Panel
15
+ from rich.table import Table
16
+ from rich import box
17
+ from rich.text import Text
18
+ import json
19
+
20
+ from langchain_core.tools import BaseTool, StructuredTool, Tool
21
+
22
+ console = Console()
23
+
24
+ # Tools that always require approval in 'always' mode (dangerous built-in operations)
25
+ # These are the built-in CLI tools that modify the filesystem or execute commands
26
+ DANGEROUS_TOOLS = {
27
+ 'terminal_run_command', # Shell command execution
28
+ 'write_file',
29
+ 'create_file',
30
+ 'delete_file',
31
+ 'move_file',
32
+ 'copy_file',
33
+ 'create_directory',
34
+ }
35
+
36
+ # Note: Tools NOT in DANGEROUS_TOOLS are auto-approved, including:
37
+ # - Read-only filesystem tools (read_file, list_directory, etc.)
38
+ # - User-added toolkit tools (via --toolkit_config or /add_toolkit)
39
+ # - MCP server tools (via --mcp or /add_mcp)
40
+ #
41
+ # The assumption is that users explicitly add toolkits they trust.
42
+ # Only built-in tools that can modify files or run commands require approval.
43
+
44
+
45
+ def prompt_approval(tool_name: str, tool_args: Dict[str, Any], approval_mode: str) -> bool:
46
+ """
47
+ Prompt user for approval before executing a tool.
48
+
49
+ Args:
50
+ tool_name: Name of the tool to execute
51
+ tool_args: Arguments to pass to the tool
52
+ approval_mode: Current approval mode ('always', 'auto', 'yolo')
53
+
54
+ Returns:
55
+ True if approved, False if rejected
56
+ """
57
+ # Auto mode - always approve
58
+ if approval_mode == 'auto':
59
+ return True
60
+
61
+ # Yolo mode - always approve, no questions asked
62
+ if approval_mode == 'yolo':
63
+ return True
64
+
65
+ # Always mode - only prompt for dangerous built-in tools
66
+ # User-added toolkits and MCP tools are auto-approved (user explicitly added them)
67
+ if tool_name not in DANGEROUS_TOOLS:
68
+ return True
69
+
70
+ # Create approval prompt panel for dangerous tools
71
+ console.print()
72
+
73
+ # Build args display
74
+ args_content = []
75
+ for key, value in tool_args.items():
76
+ if isinstance(value, str) and len(value) > 100:
77
+ display_value = value[:100] + "..."
78
+ elif isinstance(value, (dict, list)):
79
+ try:
80
+ formatted = json.dumps(value, indent=2)
81
+ if len(formatted) > 200:
82
+ formatted = formatted[:200] + "..."
83
+ display_value = formatted
84
+ except:
85
+ display_value = str(value)[:100]
86
+ else:
87
+ display_value = str(value)
88
+ args_content.append(f" [cyan]{key}[/cyan]: {display_value}")
89
+
90
+ args_text = "\n".join(args_content) if args_content else " (no arguments)"
91
+
92
+ # All tools reaching here are dangerous (in DANGEROUS_TOOLS)
93
+ icon = "⚠️"
94
+ border_style = "yellow"
95
+ title_style = "bold yellow"
96
+
97
+ panel = Panel(
98
+ Text.from_markup(f"[bold]{tool_name}[/bold]\n\n[dim]Arguments:[/dim]\n{args_text}"),
99
+ title=f"[{title_style}]{icon} Approve Tool Call?[/{title_style}]",
100
+ title_align="left",
101
+ subtitle="[dim][y]es / [n]o / [a]uto-approve / [q]uit[/dim]",
102
+ subtitle_align="right",
103
+ border_style=border_style,
104
+ box=box.ROUNDED,
105
+ padding=(1, 2),
106
+ )
107
+ console.print(panel)
108
+
109
+ # Get user input
110
+ while True:
111
+ try:
112
+ response = input("→ ").strip().lower()
113
+ except (KeyboardInterrupt, EOFError):
114
+ console.print("\n[yellow]Cancelled[/yellow]")
115
+ return False
116
+
117
+ if response in ('y', 'yes', ''):
118
+ console.print("[green]✓ Approved[/green]")
119
+ return True
120
+ elif response in ('n', 'no'):
121
+ console.print("[red]✗ Rejected[/red]")
122
+ return False
123
+ elif response in ('a', 'auto'):
124
+ console.print("[cyan]→ Switching to auto mode for this session[/cyan]")
125
+ # Signal to switch to auto mode
126
+ return 'switch_auto'
127
+ elif response in ('q', 'quit'):
128
+ console.print("[yellow]Quitting...[/yellow]")
129
+ raise KeyboardInterrupt()
130
+ else:
131
+ console.print("[dim]Please enter y/n/a/q[/dim]")
132
+
133
+
134
+ class ApprovalToolWrapper:
135
+ """
136
+ Wrapper that adds approval prompts to tools based on approval mode.
137
+
138
+ This wrapper intercepts tool calls and prompts for user approval
139
+ before executing dangerous operations.
140
+ """
141
+
142
+ def __init__(self, approval_mode_ref: List[str]):
143
+ """
144
+ Initialize the approval wrapper.
145
+
146
+ Args:
147
+ approval_mode_ref: A mutable list containing the current approval mode.
148
+ Using a list allows the mode to be changed externally.
149
+ access as approval_mode_ref[0]
150
+ """
151
+ self.approval_mode_ref = approval_mode_ref
152
+
153
+ @property
154
+ def approval_mode(self) -> str:
155
+ """Get current approval mode."""
156
+ return self.approval_mode_ref[0] if self.approval_mode_ref else 'always'
157
+
158
+ def wrap_tool(self, tool: BaseTool) -> BaseTool:
159
+ """
160
+ Wrap a tool to add approval prompts.
161
+
162
+ Args:
163
+ tool: The tool to wrap
164
+
165
+ Returns:
166
+ Wrapped tool with approval logic
167
+ """
168
+ original_func = tool.func if hasattr(tool, 'func') else tool._run
169
+ tool_name = tool.name
170
+ wrapper_self = self
171
+
172
+ @functools.wraps(original_func)
173
+ def wrapped_func(*args, **kwargs):
174
+ # Get approval
175
+ approval = prompt_approval(tool_name, kwargs, wrapper_self.approval_mode)
176
+
177
+ if approval == 'switch_auto':
178
+ # Switch to auto mode
179
+ wrapper_self.approval_mode_ref[0] = 'auto'
180
+ console.print("[cyan]Mode switched to 'auto' - tools will auto-approve[/cyan]")
181
+ elif not approval:
182
+ return f"Tool execution rejected by user"
183
+
184
+ # Execute the tool
185
+ return original_func(*args, **kwargs)
186
+
187
+ # Create new tool with wrapped function
188
+ if isinstance(tool, StructuredTool):
189
+ return StructuredTool(
190
+ name=tool.name,
191
+ description=tool.description,
192
+ func=wrapped_func,
193
+ args_schema=tool.args_schema,
194
+ return_direct=tool.return_direct,
195
+ )
196
+ else:
197
+ # Clone the tool with wrapped function
198
+ tool.func = wrapped_func
199
+ return tool
200
+
201
+ def wrap_tools(self, tools: List[BaseTool]) -> List[BaseTool]:
202
+ """
203
+ Wrap multiple tools with approval logic.
204
+
205
+ Args:
206
+ tools: List of tools to wrap
207
+
208
+ Returns:
209
+ List of wrapped tools
210
+ """
211
+ return [self.wrap_tool(tool) for tool in tools]
212
+
213
+
214
+ def create_approval_wrapper(approval_mode_ref: List[str]) -> ApprovalToolWrapper:
215
+ """
216
+ Create an approval wrapper with a reference to the current mode.
217
+
218
+ Args:
219
+ approval_mode_ref: Mutable list containing current approval mode [0]
220
+
221
+ Returns:
222
+ ApprovalToolWrapper instance
223
+ """
224
+ return ApprovalToolWrapper(approval_mode_ref)