code-execution-fallback
하는 일
이 스킬은 코드를 실행하기 전에 작업 폴더를 확인하고, 필요할 때 셸 실행으로 대체하는 방법을 다룹니다. AI가 작성한 스크립트를 실행하는데 파일이 잘못된 위치에 저장되는 사람을 위한 것입니다.
사용하는 경우
- ✓AI 작업 중 파일이 계속 잘못된 폴더에 나타날 때.
- ✓샌드박스가 반복해서 실패하고 코드를 더 단순하게 만들어도 해결되지 않는 경우.
- ✓코드를 인라인으로 작성해 셸에서 Python을 실행하고 싶을 때.
스킬 링크
https://github.com/HKUDS/AgentPilot/blob/main/openspace/benchmarks/gdpval/skills/code-execution-fallback/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“AI가 계속 파일을 잘못된 곳에 저장하고 샌드박스도 계속 실패합니다. 폴더를 고치고 셸에서 스크립트를 실행해 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
AI는 먼저 작업 폴더를 확인하고, 더 단순한 코드를 시도한 다음, 코드를 인라인으로 넣은 셸 실행으로 옮깁니다. 출력을 확인해 실행이 성공했는지 확인합니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
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.txtwithout context - ❌ Repeatedly retrying failed
execute_code_sandboxwithout 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
자주 묻는 질문
인라인 셸 실행이란 무엇인가요?
샌드박스를 쓰지 않고, 셸 명령 하나에 여러 줄의 Python을 담아 실행하는 것입니다.
왜 작업 폴더를 먼저 확인하나요?
AI가 도구를 바꿀 때 파일이 예상치 못한 곳에 쓰이지 않도록 하기 위해서입니다.
셸 전환 전에는 무엇을 하나요?
안내서는 더 단순한 코드를 먼저 시도하고, 그래도 실패하면 셸 실행으로 전환하라고 제안합니다.
상세 정보
작성자의 원본 설명
Handle code execution failures with fallback strategies and anchored workspace paths
repo: HKUDS/AgentPilot
인기도
- GitHub 스타
- 7.8k
- 순위
- #12847
- 라이선스
- MIT
- 업데이트
- 2026. 11. 1.
댓글
- …
이 저장소의 다른 스킬
agentpilot
7.8k작업을 준비하고 AgentPilot 루프를 실행해 변경을 제안, 테스트, 점수화하면서 프로젝트를 단계적으로 개선하도록 돕습니다.
openspace
7.8k에이전트 스킬을 저장하고 가져오는 도구인 OpenSpace를 설정하고, MCP를 통해 AI 앱에 연결하도록 돕습니다.
rsi-arena
7.8kAIME나 Terminal-Bench 같은 표준 AI 벤치마크 테스트를 설정하고 실행해 서로 다른 개선 방법을 비교하도록 돕습니다.
experiment-guide
7.8k프로그램을 개선하는 방법을 조사하면서 작은 실험을 계획하고, 결과를 읽고, 발견 사항을 기록하도록 돕습니다.