Agent Zero AI framework
fix(skills): use standard CLI conventions for script argument passing
TerminallyLazy5fefa5f53b4c
diff --git a/prompts/agent.system.tool.skills.md b/prompts/agent.system.tool.skills.mdindex 9721ccbd1..e9bad8f97 100644--- a/prompts/agent.system.tool.skills.md+++ b/prompts/agent.system.tool.skills.md@@ -119,25 +119,25 @@ Security:### 4. execute skill scriptExecutes bundled scripts from skill with arguments-Scripts run in sandbox with injected arguments+Scripts receive arguments via standard CLI conventions (sys.argv, process.argv)Use when: skill provides script for deterministic operation or automation~~~json{"thoughts": [- "Need to extract PDF form fields programmatically",- "Skill provides extract_fields.py script",- "Executing with target PDF path"+ "Need to convert PDF to images",+ "Skill provides convert_pdf_to_images.py script",+ "Script expects positional args: input_pdf output_dir"],- "headline": "Executing PDF field extraction script",+ "headline": "Converting PDF to images","tool_name": "skills_tool","tool_args": {"method": "execute_script","skill_name": "pdf_editing",- "script_path": "scripts/extract_fields.py",+ "script_path": "scripts/convert_pdf_to_images.py","script_args": {- "pdf_path": "/path/to/form.pdf",- "output_format": "json"+ "input_pdf": "/path/to/document.pdf",+ "output_dir": "/tmp/images"}}}@@ -148,10 +148,20 @@ Required args:- script_path: relative path to script file- script_args: dictionary of arguments passed to script-Supported script types:-- .py (Python): args injected as _skill_args dictionary-- .js (Node.js): args injected as _skill_args constant-- .sh (Shell): args exported as environment variables+Optional args:+- arg_style: how to pass arguments to script (default: "positional")+ - "positional": values as positional args → sys.argv = ['script.py', 'value1', 'value2']+ - "named": as --key value pairs → sys.argv = ['script.py', '--key1', 'value1', '--key2', 'value2']+ - "env": only environment variables, no CLI args++How scripts receive arguments:+- .py (Python): sys.argv[1], sys.argv[2], etc. (standard argparse/CLI compatible)+- .js (Node.js): process.argv[2], process.argv[3], etc. (standard CLI compatible)+- .sh (Shell): $1, $2, etc. as positional parameters++Environment variables (always available as fallback):+- SKILL_ARG_KEY1=value1, SKILL_ARG_KEY2=value2, etc.+- Scripts can use os.environ.get('SKILL_ARG_INPUT_PDF') if neededScript execution:- Runs in Docker container sandbox@@ -159,6 +169,28 @@ Script execution:- Returns stdout/stderr output- Secure and isolated execution+Example with argparse script (use arg_style="named"):+~~~json+{+ "thoughts": [+ "Script uses argparse with --input and --output flags",+ "Need to use named arg_style"+ ],+ "headline": "Running argparse-based script",+ "tool_name": "skills_tool",+ "tool_args": {+ "method": "execute_script",+ "skill_name": "data_processor",+ "script_path": "scripts/process.py",+ "script_args": {+ "input": "/path/to/data.csv",+ "output": "/tmp/result.json"+ },+ "arg_style": "named"+ }+}+~~~+### 5. search skills by querySearches skills by text matching in name, description, and tags@@ -264,34 +296,38 @@ When script execution fails:## Examples-Example 1: PDF form field extraction+Example 1: Simple script with positional args (default)+Script expects: python script.py /path/to/file.pdf~~~json{"thoughts": [- "User has PDF form to analyze",- "pdf_editing skill has extraction capabilities",- "Will load skill and execute extraction script"+ "User has PDF to convert to images",+ "Script uses sys.argv[1] for input, sys.argv[2] for output",+ "Using default positional arg_style"],- "headline": "Extracting PDF form fields",+ "headline": "Converting PDF to images","tool_name": "skills_tool","tool_args": {"method": "execute_script","skill_name": "pdf_editing",- "script_path": "scripts/extract_fields.py",+ "script_path": "scripts/convert_pdf_to_images.py","script_args": {- "pdf_path": "/workspace/application.pdf"+ "input_pdf": "/workspace/document.pdf",+ "output_dir": "/tmp/images"}}}~~~+Result: sys.argv = ['script.py', '/workspace/document.pdf', '/tmp/images']-Example 2: Web scraping with custom selector+Example 2: Argparse script with named args+Script expects: python script.py --url https://... --selector .price~~~json{"thoughts": ["Need to scrape product prices from website",- "web_scraping skill provides fetch script",- "Using CSS selector to target price elements"+ "Script uses argparse with --url and --selector flags",+ "Using arg_style='named' for argparse compatibility"],"headline": "Scraping product prices from webpage","tool_name": "skills_tool",@@ -302,12 +338,38 @@ Example 2: Web scraping with custom selector"script_args": {"url": "https://example.com/products","selector": ".price"- }+ },+ "arg_style": "named"+ }+}+~~~+Result: sys.argv = ['script.py', '--url', 'https://...', '--selector', '.price']++Example 3: Environment-only script+Script reads from os.environ only+~~~json+{+ "thoughts": [+ "Script reads configuration from environment variables",+ "Using arg_style='env' to only set env vars"+ ],+ "headline": "Running config-based processor",+ "tool_name": "skills_tool",+ "tool_args": {+ "method": "execute_script",+ "skill_name": "data_processor",+ "script_path": "scripts/process.py",+ "script_args": {+ "input_file": "/data/input.csv",+ "mode": "production"+ },+ "arg_style": "env"}}~~~+Result: SKILL_ARG_INPUT_FILE=/data/input.csv, SKILL_ARG_MODE=production-Example 3: Data analysis workflow+Example 4: Data analysis workflow~~~json{"thoughts": [@@ -324,12 +386,12 @@ Example 3: Data analysis workflow}~~~-Then follow up with script:+Then follow up with script (positional args):~~~json{"thoughts": [- "Skill loaded, now analyzing CSV with grouping",- "Using analyze_csv script with group_by parameter"+ "Skill loaded, now analyzing CSV",+ "Script takes csv_path as first arg, group_by as second"],"headline": "Analyzing sales data grouped by category","tool_name": "skills_tool",@@ -350,7 +412,8 @@ Then follow up with script:- Skills metadata already loaded in your system prompt- Skills cache after first load for efficiency- Referenced files listed in load response-- Scripts inject arguments as _skill_args variable+- Scripts receive arguments via sys.argv (positional by default) + SKILL_ARG_* env vars+- Use arg_style parameter to control argument passing: "positional", "named", or "env"- All operations return formatted text responses- Skills follow the open SKILL.md standard (cross-platform compatible)- Use skills for structured procedures and contextual expertisediff --git a/python/tools/skills_tool.py b/python/tools/skills_tool.pyindex 35890da8d..9fba3be81 100644--- a/python/tools/skills_tool.py+++ b/python/tools/skills_tool.py@@ -20,7 +20,16 @@ class SkillsTool(Tool):- search (query)- load (skill_name)- read_file (skill_name, file_path)- - execute_script (skill_name, script_path, script_args)+ - execute_script (skill_name, script_path, script_args, arg_style)++ arg_style options for execute_script:+ - "positional" (default): Pass values as positional args (sys.argv[1], sys.argv[2])+ Example: {"input": "file.pdf", "output": "/tmp"} → sys.argv = ['script.py', 'file.pdf', '/tmp']+ - "named": Pass as --key value pairs (for argparse/click scripts)+ Example: {"input": "file.pdf", "output": "/tmp"} → sys.argv = ['script.py', '--input', 'file.pdf', '--output', '/tmp']+ - "env": Only use environment variables (SKILL_ARG_INPUT, SKILL_ARG_OUTPUT)++ Environment variables (SKILL_ARG_*) are always set regardless of arg_style."""async def execute(self, **kwargs) -> Response:@@ -49,7 +58,9 @@ class SkillsTool(Tool):script_args = kwargs.get("script_args") or {}if not isinstance(script_args, dict):script_args = {}- return await self._execute_script(skill_name, script_path, script_args)+ # arg_style: "positional" (default), "named" (--key value), or "env" (env vars only)+ arg_style = str(kwargs.get("arg_style") or "positional").strip().lower()+ return await self._execute_script(skill_name, script_path, script_args, arg_style)return Response(message=(@@ -176,7 +187,8 @@ class SkillsTool(Tool):return f"File: {file_path}\n\n{text}"async def _execute_script(- self, skill_name: str, script_path: str, script_args: Dict[str, Any]+ self, skill_name: str, script_path: str, script_args: Dict[str, Any],+ arg_style: str = "positional") -> Response:if not skill_name:return Response(message="Error: 'skill_name' is required for method=execute_script.", break_loop=False)@@ -207,39 +219,64 @@ class SkillsTool(Tool):script_runtime_path = str(script_abs)script_runtime_dir = str(script_abs.parent)- # Normalize args once for injection- args_json = json.dumps(script_args, ensure_ascii=False)+ # Build environment variables (SKILL_ARG_*) - always set as fallback+ env_vars: Dict[str, str] = {}+ for k, v in (script_args or {}).items():+ env_key = f"SKILL_ARG_{re.sub(r'[^A-Za-z0-9_]', '_', str(k).upper())}"+ env_vars[env_key] = str(v)++ # Build CLI args based on arg_style:+ # - "positional": ['value1', 'value2'] - for scripts using sys.argv[1], sys.argv[2]+ # - "named": ['--key1', 'value1', '--key2', 'value2'] - for argparse/click scripts+ # - "env": [] - only use environment variables, no CLI args+ cli_args: List[str] = []+ if arg_style == "positional":+ cli_args = [str(v) for v in (script_args or {}).values()]+ elif arg_style == "named":+ for k, v in (script_args or {}).items():+ cli_args.append(f"--{k}")+ cli_args.append(str(v))+ # "env" style: cli_args stays empty, only env vars are usedif ext == ".py":runtime = "python"+ # Set env vars (always available as fallback)+ env_lines = [f"os.environ[{json.dumps(k)}] = {json.dumps(v)}" for k, v in env_vars.items()]+ env_setup = "\n".join(env_lines) if env_lines else "pass"+ # Set sys.argv: ['script.py', ...cli_args]+ argv_list = [script_runtime_path] + cli_args+ argv_setup = f"sys.argv = {json.dumps(argv_list)}"code = (- "import json, os, runpy\n"+ "import os, sys, runpy\n"f"os.chdir({json.dumps(script_runtime_dir)})\n"- f"_skill_args = json.loads({json.dumps(args_json)})\n"- f"runpy.run_path({json.dumps(script_runtime_path)}, run_name='__main__', init_globals={{'_skill_args': _skill_args}})\n"+ f"{env_setup}\n"+ f"{argv_setup}\n"+ f"runpy.run_path({json.dumps(script_runtime_path)}, run_name='__main__')\n")elif ext == ".js":runtime = "nodejs"+ # Set process.env (always available as fallback)+ env_lines = [f"process.env[{json.dumps(k)}] = {json.dumps(v)};" for k, v in env_vars.items()]+ env_setup = "\n".join(env_lines) if env_lines else ""+ # Node.js argv: ['node', 'script.js', ...cli_args]+ argv_list = ["node", script_runtime_path] + cli_argscode = (- "const fs = require('fs');\n"- "const path = require('path');\n"f"process.chdir({json.dumps(script_runtime_dir)});\n"- f"const _skill_args = JSON.parse({json.dumps(args_json)});\n"- f"const __skill_script = fs.readFileSync({json.dumps(script_runtime_path)}, 'utf8');\n"- "eval(__skill_script);\n"+ f"{env_setup}\n"+ f"process.argv = {json.dumps(argv_list)};\n"+ f"require({json.dumps(script_runtime_path)});\n")elif ext == ".sh":runtime = "terminal"- env_parts: List[str] = []- for k, v in (script_args or {}).items():- key = re.sub(r"[^A-Za-z0-9_]", "_", str(k).upper())- if not key:- continue- env_key = f"SKILL_ARG_{key}"- env_parts.append(f"{env_key}={shlex.quote(str(v))}")+ # Environment variables (always available as fallback)+ env_parts = [f"{k}={shlex.quote(v)}" for k, v in env_vars.items()]env_prefix = " ".join(env_parts)+ # Pass CLI args to script+ cli_args_str = " ".join(shlex.quote(a) for a in cli_args)cd_cmd = f"cd {shlex.quote(script_runtime_dir)}"run_cmd = f"bash {shlex.quote(script_runtime_path)}"+ if cli_args_str:+ run_cmd = f"{run_cmd} {cli_args_str}"if env_prefix:code = f"{cd_cmd} && {env_prefix} {run_cmd}"else:@@ -266,6 +303,8 @@ class SkillsTool(Tool):loop_data=self.loop_data,)+ # Must call before_execution to initialize self.log before execute()+ await cet.before_execution(**cet.args)resp = await cet.execute(**cet.args)# Wrap result to make it clear it was a skill scriptwrapped = (