‹ 首页

code-execution-fallback

@hkuds · 收录于 5 天前 · 上游提交 1 周前

Handle code execution failures with fallback strategies and anchored workspace paths

适合你,如果经常遇到代码执行失败需要自动重试或回退

/ 通过 npx 安装 校验哈希
npx oh-my-skill add hkuds/openspace/code-execution-fallback
/ 通过 bash 安装
curl -fsSL https://oh-my-skill.com/install.sh | bash -s -- hkuds/openspace/code-execution-fallback
/ 已经装过?验证本机副本,不用重装
npx oh-my-skill verify hkuds/openspace/code-execution-fallback
安装目标可用 --agent / --scope 或 --to 明确指定;省略时只会在唯一已存在的 agent 目录上自动选择,零命中或多命中会停止并提示。content_hash 缺失或不一致均拒装。
6920GitHub stars
~911上下文体积 · 单文件
索引托管

怎么用

商店整理自技能原文 · 版本 2c5cc40 · 表述以原文为准
它做什么

Claude 在执行代码时会先确认工作目录,如果沙箱执行失败,它会依次尝试简化代码、用 shell heredoc 运行、或交给 shell_agent 处理,并确保输出文件路径正确。

什么时候触发

当 execute_code_sandbox 因语法错误、超时或未知错误失败时触发;或者在需要生成文件但怀疑目录出错时也会启用。

装好后可以这样说
触发二级回退策略。
锚定工作区路径。
委托给三级回退。
技能原文 SKILL.md作者撰写 · MIT · 2c5cc40

Code Execution Fallback & Workspace Anchoring

This skill provides a robust pattern for executing code when the primary method fails, combined with proper workspace path management to prevent file location errors.

Core Techniques
1. Workspace Path Anchoring

Always establish and verify your working directory at the start of any task:

# At the beginning of any code execution
import os
workspace_path = os.getcwd()
print(f"Working directory: {workspace_path}")
# In shell scripts
pwd
echo "Current directory: $(pwd)"

Why: Prevents files from being written to unexpected locations when agents switch between tools.

2. Execution Fallback Ladder

When execute_code_sandbox fails, follow this escalation pattern:

Level 1: Retry with Simpler Code
  • Simplify the code structure
  • Remove complex dependencies
  • Add explicit error handling
Level 2: Use run_shell with Heredoc

When sandbox execution repeatedly fails, switch to shell execution:

python3 << 'EOF'
import os
import pandas as pd

# Your code here
data = {"col1": [1, 2, 3], "col2": ["a", "b", "c"]}
df = pd.DataFrame(data)
df.to_csv("output.csv", index=False)
print("File written successfully")
EOF

Key points:

  • Use << 'EOF' (quoted) to prevent variable expansion
  • Include all imports and dependencies inline
  • Add explicit success/failure messages
Level 3: Delegate to shell_agent

For complex multi-step tasks with error recovery needs:

Task: Create a data processing pipeline that reads CSV, transforms data, and outputs Excel
Requirements:
- Handle missing values
- Apply transformations
- Write to ./output/ directory
- Retry on transient errors
3. Explicit Path Management

Always use absolute or explicitly relative paths:

# BAD - relies on implicit working directory
df.to_csv("output/data.csv")

# GOOD - explicit path anchoring
import os
base_path = os.getcwd()
output_dir = os.path.join(base_path, "output")
os.makedirs(output_dir, exist_ok=True)
df.to_csv(os.path.join(output_dir, "data.csv"))
# BAD
cd some_dir && python script.py

# GOOD
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"
python script.py
Decision Tree
execute_code_sandbox fails?
├── Yes, with syntax/import errors → Fix code, retry Level 1
├── Yes, with timeout/resource errors → Use Level 2 (run_shell heredoc)
├── Yes, with unknown/unclear errors → Use Level 3 (shell_agent)
└── No, success → Verify output file exists at expected path
Common Failure Scenarios & Solutions

| Error Type | Likely Cause | Recommended Fallback | |------------|--------------|---------------------| | ModuleNotFoundError | Missing packages | run_shell with pip install first | | Timeout | Long-running operation | shell_agent with progress tracking | | PermissionError | Wrong directory | Verify workspace path, use explicit paths | | Unknown error | Sandbox limitations | run_shell or shell_agent |

Example: Robust File Generation
# Step 1: Anchor workspace
import os
workspace = os.getcwd()
print(f"Workspace: {workspace}")

# Step 2: Create output directory explicitly
output_path = os.path.join(workspace, "deliverables")
os.makedirs(output_path, exist_ok=True)

# Step 3: Generate content with error handling
try:
    # Your generation logic here
    with open(os.path.join(output_path, "report.txt"), "w") as f:
        f.write("Content here")
    print(f"Success: File written to {output_path}")
except Exception as e:
    print(f"Error: {e}")
    # Signal to escalate to run_shell or shell_agent
    raise
Anti-Patterns to Avoid
  • ❌ Assuming current directory without verification
  • ❌ Using relative paths like ../output/file.txt without context
  • ❌ Repeatedly retrying failed execute_code_sandbox without changing approach
  • ❌ Not checking if output files exist after generation
  • ❌ Mixing implicit and explicit path styles in same task
Verification Checklist

After any code execution:

  • [ ] Confirm working directory was verified at start
  • [ ] Confirm output files exist at expected paths
  • [ ] Confirm file contents are non-empty and valid
  • [ ] If execution failed, escalate to next fallback level within 2 retries
按 MIT 许可原样转载,未经改动 · 在 GitHub 查看 →

评论

登录即可评论;带「已验证安装」的,是发布者名下有本店的安装或持有记录。