error-recovery
/error-recovery
Handle errors, timeouts, and failures in multi-agent workflows. Use when dealing with external model timeouts, API failures, partial success, user cancellation, or graceful degradation.
- Author
- madappgang ↗
- Repository
- magus ↗
- Licence
- MIT
- Last repository change
- 26.10.2026
Assessment and security
- Files in this package
- 1
- Scripts
- 0
- HTML comments
- 0
- URLs in SKILL.md
- 1
No signals detected. Repository changed on 26.10.2026, without references to retired models or APIs.
MIT, open: use and modify while retaining author attribution.
What it does and when to use it
Handle errors, timeouts, and failures in multi-agent workflows. Use when dealing with external model timeouts, API failures, partial success, user cancellation, or graceful degradation.
Original author description
Handle errors, timeouts, and failures in multi-agent workflows. Use when dealing with external model timeouts, API failures, partial success, user cancellation, or graceful degradation.
How it works
- Overview
- Core Patterns
- Integration with Other Skills
- Best Practices
- Examples
- Troubleshooting
- Summary
SKILL.md preview
---
name: error-recovery
description: Handle errors, timeouts, and failures in multi-agent workflows. Use when dealing with external model timeouts, API failures, partial success, user cancellation, or graceful degradation.
user-invocable: false
---
# Error Recovery
**Version:** 1.2.0
**Purpose:** Patterns for handling failures in multi-agent workflows
**Status:** Production Ready
## Overview
Error recovery is the practice of handling failures gracefully in multi-agent workflows, ensuring that temporary errors, timeouts, or partial failures don't derail entire workflows. In production systems with external dependencies (AI models, APIs, network calls), failures are inevitable. The question is not "will it fail?" but "how will we handle it when it does?"
This skill provides battle-tested patterns for:
- **User escalation** (STOP and report before fallback — DEFAULT)
- **Timeout handling** (external models running longer than expected)
- **API failure recovery** (401, 500, network errors)
- **Partial success strategies** (some agents succeed, others fail)
- **User cancellation** (graceful Ctrl+C handling)
- **Missing tools** (claudish not installed)
- **Out of credits** (payment/quota errors)
- **Re-running a failed model** (only when the user chooses it)
With proper error recovery, workflows become **resilient** and **production-ready**.
## Core Patterns
### Pattern 0: User Escalation (DEFAULT — Read First)
**This is the MOST IMPORTANT pattern. It overrides all other patterns when the user has requested a specific model.**
**Rule: NEVER silently substitute, retry with a different model, or fall back to embedded Claude when the user requested a specific model. STOP and REPORT the failure first.**
**When this applies:**
- User explicitly requested a model (e.g., "use Gemini to redesign X")
- User selected specific models for a task
- Any workflow where the model choice was intentional
**When graceful degradation (Patterns 1-7) applies instead:**
- Automated pipelines where *any result* > *no result*
- User explicitly said "use whatever works"
- `/team` workflows where the command already handles failure reporting
**The Protocol:**
```
Step 1: Model fails (non-zero exit, empty output, API error, rate limit, binary crash)
Step 2: STOP immediately. Do NOT:
❌ Silently launch a different model
❌ Retry with a different provider prefix
❌ Fall back to embedded Claude without asking
❌ Run `claudish --top-models` or invent model IDs — use the live catalog (`list_models`) instead
❌ Substitute a "similar" model
Step 3: REPORT to the user with:
- What model was requested
- What happened (exact error message)
- How many attempts were made and what was tried
- Actionable options for the user to choose from
Step 4: WAIT for user's decision before proceeding
```
**Report Template:**
```
"{Model Name} failed — {error category}.
What happened:
1. Attempt 1: {what was tried} — {exact error}
2. Attempt 2: {what was tried} — {exact error}
Options:
(1) {Fix and retry} — {specific fix description}
(2) Use a different model — {suggest alternatives if known}
(3) Skip this model and continue without it
(4) Cancel the workflow
(5) Report this error to claudish developers
Which do you prefer?"
```
**Why this matters:** When a user says "use Gemini", they've made a deliberate choice — for its 1M context, its reasoning style, or for model diversity. Silently substituting another model defeats the purpose. The user should always be in control of model selection decisions.
---
### Pattern 1: Timeout Handling
**Scenario: A model is running longer than expected**
`team` has no timeout: a slot runs until it finishes, fails, or you cancel it.
`create_session` takes `timeout_seconds` (`/delegate` uses 300). A value in the tens of
seconds kills sessions that are working normally, because a model running a build or a
test suite goes quiet while the tool runs.
**Detection:** read `team(mode="status")`'s `idle_seconds_by_slot` together with
`activity_by_slot`:
- idle in `tool_executing` — a local tool is running; keep waiting
- idle in `running` — the model stopped mid-answer; candidate for cancel
- `starting` — the child is still starting up; keep waiting
- `finishing` — the answer is complete and the child is exiting; nothing to do
A team slot never reports `waiting_for_input`: its input is closed at spawn, so nothing can
wait for an answer.
**Recovery:** at your poll ceiling, report each still-running slot with its idle seconds
and activity, and ask the user whether to wait longer, cancel it and continue with the
others, or cancel the workflow. Do not cancel automatically.
**Graceful Degradation:**
```
Multi-Model Review Example:
Requested: 5 models (Claude, Grok, Gemini, GPT, DeepSeek)
Grok: still running at the poll ceiling; the user chose to cancel it
Result:
- Claude: Success ✓
- Grok: Cancelled ✗
- Gemini: Success ✓
- GPT: Success ✓
- DeepSeek: Success ✓
Successful: 4/5 models (80%)
dev:aggregator runs (N ≥ 2) ✓
Action:
Proceed with consolidation using 4 reviews
Notify user: "4/5 models completed (Grok cancelled). Proceeding with 4-model consensus."
Benefits:
- Workflow completes despite failure
- User gets results (4 models better than 1)
- Timeout doesn't derail entire workflow
```
**Example Implementation:**
```
# Via create_session MCP tool (timeout handled by the tool)
create_session(model="grok", prompt=PROMPT, timeout_seconds=300)
# Nothing is pushed. Poll list_sessions(include_completed=true) about every 10 s
# and read the session's row:
# - COMPLETED → get_output(session_id) → process result
# - TIMEOUT → the session hit timeout_seconds → get_diagnostics(session_id)
# - FAILED → read the row's reason and reason_detail, then get_diagnostics(session_id):
# - reason_detail names a 401 / missing key → API key issue
# - Other → general failure
# Via team MCP tool. There is NO per-model timeout any more — the parameter was
# removed, and passing one is silently ignored. You bound the wait yourself by
# bounding the poll loop.
team(mode="run", path=SESSION_DIR, models=["grok"], input_file=INPUT_MD,
require_pattern=<regex for the shape PROMPT mandates>)
team(mode="status", path=SESSION_DIR) # poll until no slot has state === "RUNNING"
# Check per-model status in the SETTLED status response, not the run response — run
# returns before any model has answered. A slot reported EMPTY with reason
# shape_mismatch is a FAILURE to recover from, not a short answer to accept — the
# model finished without producing the required shape.
#
# Before treating a quiet slot as hung, read idle_seconds_by_slot together with
# activity_by_slot: 90s idle in "tool_executing" is a build or test suite and is
# normal; 90s idle in "running" is a model that stopped mid-answer.
```
---
### Pattern 2: API Failure Recovery
**Common API Failure Scenarios:**
```
401 Unauthorized:
- Invalid API key (OPENROUTER_API_KEY incorrect)
- Expired API key
- API key not set in environment
500 Internal Server Error:
- Model service temporarily down
- Server overload
- Model deployment issue
Network Errors:
- Connection timeout (network slow/unstable)
- DNS resolution failure
- Firewall blocking request
429 Too Many Requests:
- Rate limit exceeded
- Too many concurrent requests
- Quota exhausted for time window
```
**Where the cause comes from.** You never see an HTTP status directly: every model call
goes through the claudish MCP tools, and claudish owns transport, routing and credentials.
Read the cause from what claudish reports:
- `team`: the settled `status` marks the slot FAILED; `errors/<slot>.log` in the session
directory holds the upstream error body.
- `create_session`: a `failed` or `timeout` event; call `get_diagnostics(session_id)` for
stderr, upstream error bodies and the resolved model chain.
- Credentials, billing or reachability in doubt (401, 402, "credits", "quota"): call
`preflight(models=[...])`. It reports which provider would serve each model, whether that
route is metered, and whether it answers now. It is a diagnostic for this moment, never a
step before a run.
Never check `OPENROUTER_API_KEY` or call a provider with `curl` yourself. Keys and routes are
claudish's; a copy of that logic here goes stale and routes around the real bug.
**Recovery is the same for every cause: no automatic retry.** claudish-usage states the rule
for every caller: a failed slot is shown as FAILED, the run continues with the survivors,
and nothing is retried or substituted on its own. A model that will not route is a claudish
bug to report (Pattern 8), not something to loop around.
| Cause (from the failure text) | What to tell the user | Their options |
|---|---|---|
| 401 / missing or invalid key | The provider rejected the credentials; name the model | Fix the key as claudish documents, then re-run that model |
| 402 / credits / quota | The account behind that route is out of credit (Pattern 6) | Add credit, pick another model, or skip it |
| 5xx | The provider failed on its side | Re-run that model once, pick another, or skip it |
| network error | The route was unreachable; say whether `preflight` reaches it now | Re-run that model once, or skip it |
| 429 / rate limited | Rate limited; quote any wait the error body names | Wait and re-run that model, or skip it |
| `prompt_not_accepted` in every slot | The children never took their prompt; a re-run fails the same way | Follow claudish-usage, "Every slot failed with `prompt_not_accepted`" |
A re-run happens only when the user picks it: one new `team` or `create_session` call for
the same model (Pattern 7). When the user named the model, Pattern 0 applies first.
**Graceful Degradation for All API Failures:**
> **Pattern 0 guard:** If the user requested specific models, apply Pattern 0 (stop and report with options) instead of auto-fallback. The fallback below applies only to automated pipelines or when the user pre-authorized graceful degradation.
```
Fallback Strategy:
If ALL external models fail (401, 500, network, etc.):
1. Log all failures
2. Notify user:
"⚠️ All external models failed. Falling back to embedded Claude.
Errors:
- Grok: Network timeout
- Gemini: 500 Internal Server Error
- GPT: Rate limited (429)
- DeepSeek: Authentication failed (401)
Proceeding with the internal reviewer only."
3. Run embedded Claude review
4. Present results with disclaimer:
"Review completed using Claude only (external models unavailable).
For multi-model consensus, try again later."
Benefits:
- User still gets results (better than nothing)
- Workflow completes (not aborted)
- Clear error communication (user knows what happened)
```
---
### Pattern 3: Partial Success Strategies
**Scenario: 2 of 4 Models Complete Successfully**
In multi-model workflows, it's common for some models to succeed while others fail.
**Tracking Success/Failure:**
```
// External models: one team call, then read the SETTLED status
team(mode="run", path=SESSION_DIR, models=[...resolved live...], input_file=INPUT_MD,
require_pattern=<shape the prompt mandates>)
team(mode="status", path=SESSION_DIR) // until no slot is RUNNING
const successful = slots.filter(s => status.models[s].state === "COMPLETED");
const failed = slots.filter(s => status.models[s].state !== "COMPLETED");
log(`Success: ${successful.length}/4`);
log(`Failed: ${failed.length}/4`);
```
**Decision Logic:**
```
If N ≥ 2 successful:
→ Dispatch dev:aggregator with the N review files
→ Notify user about failures, and offer to re-run them (Pattern 7)
If N = 1 successful:
→ Use that review as the result, with its own verdict; one review needs no
aggregator
→ Notify user about failures, and offer to re-run them (Pattern 7)
If N = 0:
→ Nothing to consolidate
→ Offer user choice:
1. Re-run the failed models (Pattern 7)
2. Abort workflow
3. Proceed with embedded Claude only (not when the user named the models — Pattern 0)
Example:
successful.length = 2 (Claude, Gemini)
failed.length = 2 (Grok cancelled at the poll ceiling, GPT 500 error)
Action:
notifyUser("2/4 models completed successfully. Proceeding with consolidation using 2 reviews.");
consolidateReviews([
"ai-docs/claude-review.md",
"ai-docs/gemini-review.md"
]);
presentResults({
totalModels: 4,
successful: 2,
failureReasons: {
grok: "Cancelled at the poll ceiling (user choice)",
gpt: "500 Internal Server Error"
}
});
```
**Communication Strategy:**
```
Be transparent with user about partial success:
❌ WRONG:
"Multi-model review complete!"
(User assumes all 4 models ran)
✅ CORRECT:
"Multi-model review complete (2/4 models succeeded).
Successful:
- internal ✓
- Gemini ✓
Failed:
- Grok: cancelled at the poll ceiling
- GPT: 500 Internal Server Error
Proceeding with 2-model consensus.
Top issues: [...]"
User knows:
- What succeeded (Claude, Gemini)
- What failed (Grok, GPT)
- Why they failed (cancelled, 500 error)
- What action was taken (2-model consensus)
```
**Consolidation Adapts to N Models:**
```
Consolidation logic must handle variable N:
✅ CORRECT - Flexible N:
function consolidateReviews(reviewFiles) {
const N = reviewFiles.length;
log(`Consolidating ${N} reviews`);
// Consensus thresholds adapt to N
const unanimousThreshold = N; // All N agree
const strongThreshold = Math.ceil(N * 0.67); // 67%+ agree
const majorityThreshold = Math.ceil(N * 0.5); // 50%+ agree
// Apply consensus analysis with dynamic thresholds
...
}
❌ WRONG - Hardcoded N:
// Assumes always 4 models
const unanimousThreshold = 4; // Breaks if N = 2!
```
---
### Pattern 4: User Cancellation Handling (Ctrl+C)
**Scenario: User Presses Ctrl+C During Workflow**
Users may cancel long-running workflows for various reasons:
- Taking too long
- Realized they want different configuration
- Accidentally triggered workflow
- Need to prioritize other work
**Cleanup Strategy:**
```
process.on('SIGINT', async () => {
log("⚠️ User cancelled workflow (Ctrl+C)");
// Step 1: Stop all running processes gracefully
await stopAllAgents();
// Step 2: Save partial results to files
const partialResults = await collectPartialResults();
await writeFile('ai-docs/partial-review.md', partialResults);
// Step 3: Log what was completed vs cancelled
log("Workflow cancelled");
log("Completed:");
log(" - PHASE 1: Requirements gathering ✓");
log(" - PHASE 2: Architecture planning ✓");
log("Cancelled:");
log(" - PHASE 3: Implementation (in progress)");
log(" - PHASE 4: Testing (not started)");
log(" - PHASE 5: Review (not started)");
// Step 4: Notify user
console.log("\n⚠️ Workflow cancelled by user.");
console.log("Partial results saved to ai-docs/partial-review.md");
console.log("Completed phases: 2/5");
// Step 5: Clean exit
process.exit(0);
});
```
**Save Partial Results:**
```
Partial Results Format:
# Workflow Cancelled by User
**Status:** Cancelled during PHASE 3 (Implementation)
**Completed:** 2/5 phases (40%)
**Duration:** 8 minutes (of estimated 20 minutes)
**Timestamp:** 2025-11-22T14:30:00Z
## Completed Phases
### PHASE 1: Requirements Gathering ✓
- User requirements documented
- See: ai-docs/requirements.md
### PHASE 2: Architecture Planning ✓
- Architecture plan generated
- See: ai-docs/architecture-plan.md
## Cancelled Phases
### PHASE 3: Implementation (IN PROGRESS)
- Status: 30% complete
- Files created: src/auth.ts (partial)
- Files pending: src/routes.ts, src/services.ts
### PHASE 4: Testing (NOT STARTED)
- Pending: Test suite creation
### PHASE 5: Code Review (NOT STARTED)
- Pending: Multi-model review
## How to Resume
To resume from PHASE 3:
1. Review partial implementation in src/auth.ts
2. Complete remaining implementation
3. Continue with PHASE 4 (Testing)
Or restart workflow from beginning with updated requirements.
```
**Resumable Workflows (Advanced):**
```
Save workflow state for potential resume:
// During workflow execution
await saveWorkflowState({
currentPhase: 3,
totalPhases: 5,
completedPhases: [1, 2],
pendingPhases: [3, 4, 5],
partialResults: {
phase1: "ai-docs/requirements.md",
phase2: "ai-docs/architecture-plan.md",
phase3: "src/auth.ts (partial)"
}
}, '.claude/workflow-state.json');
// On next invocation
const state = await loadWorkflowState('.claude/workflow-state.json');
if (state) {
askUser("Found incomplete workflow from previous session. Resume? (Yes/No)");
if (userSaysYes) {
resumeFromPhase(state.currentPhase);
} else {
deleteWorkflowState();
startFresh();
}
}
```
---
### Pattern 5: Claudish Not Installed
> **Pattern 0 guard:** If the user requested a specific external model (e.g., "use Gemini"), apply Pattern 0 (stop and report with options) instead of auto-fallback to embedded Claude. The fallback below applies only to automated pipelines or when the user pre-authorized graceful degradation.
**Scenario: User Requests Multi-Model Review but Claudish Missing**
**Detection:**
```
The claudish MCP tools (`team`, `create_session`, `list_models`) are absent from the
tools list. That, not a shell probe, is the signal: the tools are what the workflow calls,
and the plugin's MCP server registers only when the claudish CLI is installed.
```
**Recovery Strategy:**
```
Step 1: Detect Missing Claudish
hasClaudish = claudishMcpToolsInToolsList();
if (!hasClaudish) {
log("Claudish CLI not found");
notifyUser();
}
Step 2: Notify User with Installation Instructions
"⚠️ Claudish CLI not found. External AI models unavailable.
To enable multi-model review:
1. Install: npm install -g claudish
2. Configure a provider key as the claudish documentation describes
3. Re-run this command
For now, continuing with the internal reviewer only."
Step 3: Fallback to Embedded Claude
log("Falling back to embedded Claude review");
runEmbeddedReviewOnly();
Benefits:
- Workflow doesn't fail (graceful degradation)
- User gets results (Claude review)
- Clear instructions for enabling multi-model (future use)
```
**Example Implementation:**
```
Phase 2: Model Selection
If the claudish MCP tools are not in the tools list:
Tell the user: "claudish MCP tools unavailable. Install with
`npm install -g claudish`, then restart the session."
selectedModels = ["internal"] # only if the user named no external model
Otherwise:
selectedModels = ["internal", ...resolved live from list_models...]
```
---
### Pattern 6: Out of OpenRouter Credits
> **Pattern 0 guard:** If the user requested a specific external model, apply Pattern 0 (stop and report with options) instead of auto-fallback. The fallback below applies only to automated pipelines or when the user pre-authorized graceful degradation.
**Scenario: External Model API Call Fails Due to Insufficient Credits**
**Detection:**
```
API returns:
- 402 Payment Required (HTTP status)
- Or error message contains "credits", "quota", "billing"
Example error messages:
- "Insufficient credits"
- "Credit balance too low"
- "Quota exceeded"
- "Payment required"
```
**Recovery Strategy:**
```
Step 1: Detect Credit Exhaustion
The failure text (errors/<slot>.log for team, get_diagnostics for create_session)
names 402, "credits", "quota" or "billing".
Step 2: Log Event
log("Provider credits exhausted for {model}");
Step 3: Notify User
"⚠️ OpenRouter credits exhausted. External models unavailable.
To fix:
1. Visit https://openrouter.ai
2. Add credits to your account
3. Re-run this command
For now, continuing with the internal reviewer only."
Step 4: Skip All External Models
skipAllExternalModels();
Step 5: Fallback to Embedded Claude
runEmbeddedReviewOnly();
Benefits:
- Workflow completes (doesn't fail)
- User gets results (Claude review)
- Clear instructions for adding credits
```
**Checking a route before a large run:** when the user asks whether their models will run,
or a previous run failed on billing, call `preflight(models=[...])`. It reports, per model,
the provider that would serve it, whether that route is metered, and whether it answers
now. Do not query a provider's balance endpoint yourself.
---
### Pattern 7: Re-running a Failed Model
Nothing here retries on its own. A re-run is an option you offer, and it happens only when
the user chooses it.
```
When the user picks "re-run {model}":
1. Start ONE new call for the SAME model — a team run with just that slot, or a
create_session — with the same prompt.
2. Read its settled status the same way as the first run.
3. If it fails again, report both failures with their causes and stop. Offer the
remaining options (another model, skip, cancel, report to claudish); do not loop.
Never:
❌ wrap a call in a retry loop or an exponential backoff
❌ re-run a different model in place of the one that failed
❌ re-run a 401/402 failure before the credentials or credit are fixed
```
---
### Pattern 8: Claudish Error Reporting
**Purpose:** After handling an error with Patterns 0–7, optionally report it to claudish developers via the `report_error` MCP tool. This helps improve claudish reliability. Always ask the user first — data is sanitized before sending.
**The `report_error` Tool:**
```
Parameters:
error_type (required): "provider_failure" | "team_failure" | "stream_error" | "adapter_error" | "other"
model (optional): Model ID that failed (e.g., "grok")
stderr_snippet (optional): First 500 chars of error output (from the MCP result, the row's reason_detail, or get_diagnostics)
exit_code (optional): Process exit code (if CLI fallback was used)
error_log_path (optional): Path to full error log file
session_path (optional): Path to team session directory
additional_context (optional): Extra context (what was attempted, re-runs the user chose, etc.)
auto_send (optional): Mention auto-reporting option to user (bool)
```
**Consent Requirement:**
```
ALWAYS ask user before calling report_error.
Ask:
"Would you like to report this error to claudish developers?
Data is sanitized before sending (API keys, paths, and emails are stripped)."
Only call report_error if user says yes.
Never call report_error silently or automatically unless CLAUDISH_TELEMETRY=1 is set.
```
**Error Type Mapping:**
```
Timeout (Pattern 1) → "provider_failure"
500 / 503 errors (Pattern 2) → "provider_failure"
Stream interrupted → "stream_error"
Model adapter crash → "adapter_error"
Team session failure → "team_failure"
Unknown / other → "other"
```
**When to Offer Error Reporting:**
```
Offer after:
✅ Pattern 0 (user escalation) — add option (5) to the report template
✅ Pattern 1 (timeout) — if model times out repeatedly
✅ Pattern 2 (API failures) — for 500/503 provider errors
✅ Pattern 3 (partial success) — for models that failed in multi-model runs
Do NOT offer after:
❌ Pattern 5 (claudish not installed) — MCP tool is unavailable
❌ Pattern 6 (out of credits) — billing issue, not a claudish bug
```
**Example Flow:**
```
1. Model fails (detected by Pattern 0–7)
2. Handle error per the appropriate pattern (report, skip, escalate to user)
3. Ask user:
"Would you like to report this error to claudish developers?
Data is sanitized before sending."
4. If yes:
call report_error(
error_type: "provider_failure",
model: "grok",
stderr_snippet: "connection timed out after 30000ms...",
exit_code: 124,
additional_context: "Timed out on attempt 2 of 2"
)
5. If user reports errors frequently:
mention auto_send option:
"You can enable automatic reporting via claudish config → Privacy → Telemetry
or by setting CLAUDISH_TELEMETRY=1."
```
**Automatic Reporting:**
```
When CLAUDISH_TELEMETRY=1 is set (or enabled via claudish config → Privacy → Telemetry):
- Errors are reported automatically without asking
- Skip the consent step in the flow above
- Still log that a report was sent: "Error reported to claudish developers."
To inform users:
"Tip: Set CLAUDISH_TELEMETRY=1 to enable automatic error reporting."
```
---
## Integration with Other Skills
**error-recovery + multi-model-validation:**
```
Use Case: Handling external model failures in parallel execution
Step 1: Parallel Execution (multi-model-validation)
Launch 5 models simultaneously
Step 2: Error Recovery (error-recovery)
Model 1: Success ✓
Model 2: Timeout → Skip (timeout handling pattern)
Model 3: 500 error → Report it; no automatic retry or substitution
Model 4: Success ✓
Model 5: Success ✓
Step 3: Partial Success Strategy (error-recovery)
3/5 successful (dev:aggregator runs at N ≥ 2)
Proceed with consolidation using 3 reviews
Step 4: Consolidation (multi-model-validation)
Consolidate 3 successful reviews
Notify user about 2 failures
```
---
## Best Practices
**Do:**
- ✅ Bound the poll loop, and read idle seconds with activity before calling a slot hung
- ✅ Read the cause from claudish (errors/<slot>.log, get_diagnostics, preflight)
- ✅ Offer a re-run of a failed model; start it only when the user picks it
- ✅ Provide graceful degradation (fallback to embedded Claude)
- ✅ Save partial results on cancellation
- ✅ Communicate transparently (tell user what failed and why)
- ✅ Adapt to partial success (dev:aggregator at N ≥ 2; one review stands alone)
- ✅ Offer error reporting for provider/stream failures (report_error tool)
**Don't:**
- ❌ Silently substitute a different model than the user requested (Pattern 0 violation)
- ❌ Fall back to embedded Claude without asking when user requested a specific model
- ❌ Retry automatically, in a loop or with backoff (claudish-usage: no retry, no substitution)
- ❌ Check API keys or provider balances yourself (claudish owns credentials)
- ❌ Fail entire workflow for single model failure (graceful degradation)
- ❌ Hide errors from user (be transparent)
- ❌ Discard partial results on failure (save what succeeded)
- ❌ Ignore user cancellation (handle SIGINT gracefully)
- ❌ Call report_error without user consent (privacy requirement)
**Performance:**
- Graceful degradation: Workflows complete despite failures
- No automatic retry: a failed model costs one call, never a loop
---
## Examples
### Example 1: Timeout with Retry
**Scenario:** A delegated Grok session hits its timeout, user retries with a longer one
**Execution:**
```
Attempt 1:
create_session(model="grok", prompt=PROMPT, timeout_seconds=300)
Result: list_sessions row TIMEOUT after 300s — get_diagnostics shows it was mid-test-run
Notify user:
"⚠️ Grok hit its 300s timeout while running the test suite.
Options:
1. Retry with timeout_seconds=900
2. Skip Grok
3. Cancel workflow"
User selects: 1 (Retry)
Attempt 2:
create_session(model="grok", prompt=PROMPT, timeout_seconds=900)
Result: list_sessions row COMPLETED after 7 min
Log: "Grok review completed on retry (7 min)"
get_output(session_id) → process result
Continue with workflow
```
---
### Example 2: Partial Success (2/4 Models)
**Scenario:** 4 models selected, 2 fail, proceed with 2
**Execution:**
```
One team run, 4 slots:
internal (host model)
Grok (external)
Gemini (external)
GPT (external)
Results:
Claude: Success ✓ (2 min)
Grok: Cancelled ✗ (still running at the poll ceiling)
Gemini: 500 error ✗
GPT: Success ✓ (3 min)
successful.length = 2 (Claude, GPT)
2 ≥ 2 ✓ (dev:aggregator runs at N ≥ 2)
Notify user:
"2/4 models completed successfully.
Successful:
- internal ✓
- GPT ✓
Failed:
- Grok: cancelled at the poll ceiling
- Gemini: 500 Internal Server Error
Proceeding with 2-model consensus."
Consolidate:
consolidateReviews([
"ai-docs/claude-review.md",
"ai-docs/gpt-review.md"
]);
Present results with 2-model consensus
```
---
### Example 3: User Cancellation
**Scenario:** User presses Ctrl+C during PHASE 3
**Execution:**
```
Workflow starts:
PHASE 1: Requirements ✓ (30s)
PHASE 2: Architecture ✓ (2 min)
PHASE 3: Implementation (in progress, 3 min elapsed)
User presses Ctrl+C:
Signal: SIGINT received
Handler executes:
Log: "User cancelled workflow (Ctrl+C)"
Stop agents:
- backend-developer (currently executing)
- Terminate gracefully
Collect partial results:
- ai-docs/requirements.md ✓
- ai-docs/architecture-plan.md ✓
- src/auth.ts (30% complete)
Save to file:
Write: ai-docs/partial-implementation.md
"# Workflow Cancelled
Completed: PHASE 1, PHASE 2
Partial: PHASE 3 (30%)
Pending: PHASE 4, PHASE 5"
Notify user:
"⚠️ Workflow cancelled by user.
Partial results saved to ai-docs/partial-implementation.md
Completed: 2/5 phases (40%)"
Exit: process.exit(0)
```
---
## Troubleshooting
**Problem: Workflow fails after single model timeout**
Cause: No graceful degradation
Solution: Continue with remaining models
```
❌ Wrong:
if (timeout) {
throw new Error("Model timed out");
}
✅ Correct:
if (timeout) {
log("Model timed out, skipping");
skipModel();
continueWithRemaining();
}
```
---
**Problem: A failure is retried in a loop**
Cause: A retry loop around a model call. claudish owns transport and routing, and a loop
here hides the failure instead of reporting it.
Solution: Report the failure with its cause and offer a single re-run (Pattern 7).
```
❌ Wrong:
for (let i = 0; i < 3; i++) {
try { return await run(model); }
catch (e) { await sleep(delay); }
}
✅ Correct:
Report "{model} failed: {cause from errors/<slot>.log or get_diagnostics}"
Offer: re-run once, another model, skip, cancel, report to claudish
```
---
**Problem: No visibility into what failed**
Cause: Not communicating errors to user
Solution: Transparently report all failures
```
❌ Wrong:
"Review complete!" (hides 2 failures)
✅ Correct:
"Review complete (2/4 models succeeded).
Failed: Grok (timeout), Gemini (500 error)"
```
---
## Summary
Error recovery ensures resilient workflows through:
- **Timeout handling** (detect, then re-run with a longer timeout or skip, as the user chooses)
- **API failure recovery** (read the cause from claudish, report it, no automatic retry)
- **Partial success strategies** (dev:aggregator at N ≥ 2; adapt to failures)
- **User cancellation** (graceful Ctrl+C, save partial results)
- **Missing tools** (claudish not installed, fallback to embedded)
- **Out of credits** (402 error, report it; the user picks another model or adds credit)
- **Re-running a failed model** (one call, only when the user chooses it)
- **Error reporting** (report_error MCP tool, user consent required)
With these patterns, workflows are **production-ready** and **resilient** to inevitable failures.
---
**Extracted From:**
- `/review` command error handling (external model failures)
- `/implement` command PHASE 2.5 (test-driven loop error recovery)
- Production experience with Claudish proxy failures
- Multi-model validation resilience requirements
Versions
| Repository | Score | Licence |
|---|---|---|
| This page · madappgang/magus | 91 | MIT |
| marcusgoll/Spec-Flow | 100 | MIT |
| NoobyGains/godmode | 98 | MIT |
| bojieli/ai-agent-book | 90 | Apache-2.0 |
Database snapshot: 13.11.2026 · package version 0022533b9b87 (SHA-256 digest of the entire package)
Downloads in the last 30 days: 0 · ranking
Similar skills
- 90frontend-error-handling
Use this skill when the user says 'error handling', 'error boundary', 'error recovery', 'graceful degradation', 'fallback UI', 'error reporting', 'error logging', 'crash recovery', 'error fallback', 'retry pattern', 'error state', 'error boundary React', 'Vue error handler',… - 100model-debugging
Diagnose Pollinations model failures, error spikes, timeouts, and incorrect output using current gen/enter logs and Tinybird data. Use for incidents or specific failed requests; use model-management for catalog, routing, or pricing changes. - 100agent-tool-failure-recovery-fallback-loops
Use this skill when recovering from tool timeouts, API rate limits, schema rejections, and command failures using structured fallback paths. - 90add-llm-fallbacks
Use this to make an LLM app resilient to provider failures, rate limits, timeouts, and outages. Trigger on "handle LLM API errors", "add retries/fallbacks", "the app breaks when OpenAI is down", "rate limit errors", "make my LLM calls reliable", "timeout handling". Add retries,… - 100a2a-error-handling
Implement A2A error handling — JSON-RPC errors, A2A-specific error codes, task failure states, retry strategies, and graceful degradation. Use when building robust error handling in A2A agents. - 100frontend-resilience
Reference for making frontend applications fail safely and recover - classifying rendering, network, validation and business errors; React Error Boundary placement (app, route, component) and their limits; async and event-handler errors; API error normalization; timeouts;…