Skip to content
cccskills
FreePublished on GitHub

code-execution-fallback

Recover from failed code execution by simplifying code, switching to shell commands, or handing complex tasks to shell_agent. Explicit working directories and output checks help keep generated files in the expected location.

OriginalShow the original description

Handle code execution failures with fallback strategies and anchored workspace paths

See how to install

Good for

  • Recovering from sandbox execution failures
  • Keeping generated files in the intended folder
  • Checking output files after code execution
  • Handling data processing tasks that need retries

Files included (2)

  • SKILL.md4.3 KB
  • .skill_id37 B

SKILL.md (original)

Review the instructions the agent will receive before you install.

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 TypeLikely CauseRecommended Fallback
ModuleNotFoundErrorMissing packagesrun_shell with pip install first
TimeoutLong-running operationshell_agent with progress tracking
PermissionErrorWrong directoryVerify workspace path, use explicit paths
Unknown errorSandbox limitationsrun_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

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

Prepare audio stems, the separate parts of a track, for mixing by matching their durations with silence, loops, or crossfades. Verify each generated and processed file before moving to the next production step.

  • Match audio parts with different durations
  • Extend drums and melodic parts using suitable methods
  • Check audio specifications before mixing
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

Produce audio in separate stems, meaning individual instrument tracks, and verify each output as you go. Align track lengths with silence, loops, or crossfades, then apply effects, mix a master, and package the files.

  • Align instrument tracks to a reference audio file
  • Choose how to extend tracks that are too short
  • Verify audio properties after generation and effects
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

Build serverless endpoints that relay external API requests for a dashboard while keeping API keys on the server. Includes Vercel examples for input checks, caching, cross-origin access, and consistent JSON responses.

  • Connect a dashboard to external APIs without exposing API keys
  • Create endpoints for stock quotes and news
  • Standardize API responses and error handling
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

Produce a master track and separate audio parts through a structured Python workflow. Apply filters and reverb, export WAV files with consistent settings, package them in a ZIP archive, and check that the deliverables meet the requested specifications.

  • Export a master track with separate audio parts
  • Apply filters and reverb to audio
  • Check duration and format across deliverables
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

Keep document creation moving when web searches and page retrieval repeatedly fail. The skill preserves the original task, uses the model’s existing knowledge, and clearly identifies information that could not be checked against external sources.

  • Continue drafting after repeated web retrieval failures
  • Preserve task requirements during network errors
  • Mark information that could not be externally verified
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

When Python execution repeatedly fails in execute_code_sandbox, use a file-based alternative: save the script, run it through the shell, and capture results or errors. The guidance covers paths, imports, timeouts, structured output, and optional cleanup.

  • Retry Python work through the shell after repeated sandbox failures
  • Run longer tasks with an adjusted timeout
  • Execute Python work that needs multiple files or system utilities
HKUDS/OpenSpace7.8KUpdated Aug 13, 2026

See all skills by HKUDS

Report a problem with this skill