
Delegation Core
- 126 installs
- 325 repo stars
- Updated August 2, 2026
- athola/claude-night-market
delegation-core is an agent skill that supplies token cost tables, budget tiers, and a benefit-versus-cost decision framework for external LLM delegation.
About
delegation-core (documented as cost-estimation under the conjure delegation framework) gives solo and indie builders concrete math for external LLM delegation: compare Gemini and Qwen input/output pricing, plug in expected token volumes, and judge whether time saved and quality gains justify spend. It pairs operational dependencies—quota management and usage logging—so estimates are not theoretical. Use it when you are about to fan out repetitive codebase tasks, large summarization jobs, or bulk generation to a cheaper model and need a consistent rule instead of guessing. The worked examples span low-cost grep-style delegations through medium architecture passes to high-cost full-repo reviews. It does not replace provider dashboards or your own rate limits; it standardizes when to delegate and how to think about marginal cost per task.
- Per-1M-token rate tables for Gemini 2.0 Pro/Flash and Qwen with context-window notes
- Cost-benefit formula: delegate only when benefit exceeds cost × 3 safety margin
- Tiered examples from sub-cent counts to $0.10+ large-context reviews
- Parent skill conjure:delegation-core with dependencies leyline:quota-management and leyline:usage-logging
- Estimated ~250 tokens in the skill package for quick reference during delegation decisions
Delegation Core by the numbers
- 126 all-time installs (skills.sh)
- Ranked #3,743 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Security screen: HIGH risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/athola/claude-night-market --skill delegation-coreAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 126 |
|---|---|
| repo stars | ★ 325 |
| Security audit | 1 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | athola/claude-night-market ↗ |
What it does
Estimate token spend and apply a cost-benefit gate before routing work to external LLMs like Gemini or Qwen.
Who is it for?
Agent developers who routinely delegate scans, summaries, or codegen to Gemini Flash/Pro or Qwen and need a repeatable cost gate.
Skip if: Skip if you only use a single in-agent model with no external API billing, or and already enforce hard monthly caps without per-task estimation.
When should I use this skill?
Before routing repetitive file scans, large summarization, or bulk generation to Gemini, Qwen, or other billed external models.
What you get
You can price a delegation in dollars, apply the 3× safety-margin rule, and align spend with leyline quota and usage logging before the call runs.
- Dollar estimate for a planned delegation from input/output token counts
- Go/no-go decision using the cost-benefit ratio with 3× margin
By the numbers
- Benefit must exceed Cost × 3 before delegating per the documented safety margin
- Gemini 2.0 Flash listed at $0.075 input and $0.30 output per 1M tokens
- Skill frontmatter estimates ~250 tokens for the package body
Files
Table of Contents
- Overview
- When to Use
- Philosophy
- Delegation Flow
- Quick Decision Matrix
- Detailed Workflow Steps
- 1. Task Assessment (`delegation-core:task-assessed`)
- 2. Suitability Evaluation (`delegation-core:delegation-suitability`)
- 3. Handoff Planning (`delegation-core:handoff-planned`)
- 4. Execution & Integration (`delegation-core:results-integrated`)
- Leyline Infrastructure
- Service-Specific Skills
- Module Reference
- Exit Criteria
Delegation Core Framework
Overview
A method for deciding when and how to delegate tasks to external LLM services. Core principle: delegate execution, retain high-level reasoning.
When To Use
- Before invoking external LLMs for task assistance.
- When operations are token-heavy and exceed local context limits.
- When batch processing benefits from different model characteristics.
- When tasks require routing between models.
When NOT To Use
- Task requires reasoning by Claude
Philosophy
Delegate execution, retain reasoning. Claude handles architecture, strategy, design, and review. External LLMs perform data processing, pattern extraction, bulk operations, and summarization.
Delegation Flow
1. Task Assessment: Classify task by complexity and context size. 2. Suitability Evaluation: Check prerequisites and service fit. 3. Handoff Planning: Formulate request and document plan. 4. Execution & Integration: Run delegation, validate, and integrate results.
Quick Decision Matrix
| Complexity | Context | Recommendation |
|---|---|---|
| High | Any | Keep local |
| Low | Large | Delegate |
| Low | Small | Either |
High Complexity: Architecture, design decisions, trade-offs, creative problem solving.
Low Complexity: Pattern counting, bulk extraction, boilerplate generation, summarization.
Detailed Workflow Steps
1. Task Assessment (delegation-core:task-assessed)
Classify the task:
- See
modules/task-assessment.mdfor classification criteria. - Use token estimates to determine thresholds.
- Apply the decision matrix.
Exit Criteria: Task classified with complexity level, context size, and delegation recommendation.
2. Suitability Evaluation (delegation-core:delegation-suitability)
Verify prerequisites:
- See
modules/handoff-patterns.mdfor checklist. - Evaluate cost-benefit ratio using
modules/cost-estimation.md. - Check for red flags (security, real-time iteration).
Exit Criteria: Service authenticated, quotas verified, cost justified.
3. Handoff Planning (delegation-core:handoff-planned)
Create a delegation plan:
- See
modules/handoff-patterns.mdfor request template. - Document service, command, input context, expected output.
- Define validation method.
Exit Criteria: Delegation plan documented.
4. Execution & Integration (delegation-core:results-integrated)
Execute and validate results:
- Run delegation and capture output.
- Validate format and correctness.
- Integrate only after validation passes.
- Log usage.
Exit Criteria: Results validated and integrated, usage logged.
MCP Authentication
OAuth Client Credentials (Claude Code 2.1.30+)
For MCP servers that don't support Dynamic Client Registration (e.g., Slack), pre-configured OAuth client credentials can be provided:
claude mcp add <server-name> --client-id <id> --client-secret <secret>This enables delegation workflows through MCP servers that require pre-configured OAuth, expanding the range of external services available for task delegation.
Claude.ai MCP Connectors (Claude Code 2.1.46+)
As an alternative to manual OAuth setup, users can configure MCP servers directly in claude.ai at claude.ai/settings/connectors. These connectors are automatically available in Claude Code when logged in with a claude.ai account: no claude mcp add or credential management required. This provides a browser-based auth flow that may be simpler for services with complex OAuth requirements.
Worktree Isolation for File-Modifying Delegations (Claude Code 2.1.49+)
When delegating tasks that modify files to subagents, use isolation: worktree in the agent frontmatter to run each agent in a temporary git worktree. This prevents file conflicts when multiple delegated agents operate in parallel on overlapping paths. The worktree is auto-cleaned if no changes are made; preserved with commits if the agent produces changes.
# Agent frontmatter for isolated delegation
isolation: worktreeLeyline Infrastructure
Conjure uses leyline infrastructure:
| Leyline Skill | Used For |
|---|---|
quota-management | Track service quotas and thresholds. |
usage-logging | Session-aware audit trails. |
service-registry | Unified service configuration. |
error-patterns | Consistent error handling. |
authentication-patterns | Auth verification. |
See modules/cost-estimation.md for leyline integration examples.
Service-Specific Skills
For detailed service workflows:
Skill(conjure:gemini-delegation): Gemini CLI specifics.Skill(conjure:qwen-delegation): Qwen MCP specifics.
Execution Modes
When delegating to multiple agents, choose the appropriate execution mode:
| Mode | When to Use | How It Works |
|---|---|---|
| single-session | Sequential tasks, same-file edits | Claude works through tasks in order |
| subagents | Parallel independent tasks | Agents work independently, report back |
| agent-team | Parallel coordinated tasks | Agents can communicate with each other |
See references/execution-modes.md for the selection decision matrix, mode compatibility notes, and anti-patterns to avoid.
Module Reference
- task-assessment.md: Complexity classification, decision matrix.
- cost-estimation.md: Pricing, budgets, cost tracking.
- handoff-patterns.md: Request templates, workflows.
- troubleshooting.md: Common problems, service failures.
Exit Criteria
- [ ] Task assessed and classified.
- [ ] Delegation decision justified.
- [ ] Results validated before integration.
- [ ] Lessons captured.
Cost Estimation and Budget Guidelines
Service Cost Comparisons
Gemini 2.0 Models (per 1M tokens):
- Input: $0.50, Output: $1.50 (Pro version)
- Input: $0.075, Output: $0.30 (Flash version)
- Context: Up to 1M tokens
Qwen Models (per 1M tokens):
- Input: $0.20-0.50, Output: $0.60-1.20 (varies by provider)
- Context: Up to 100K+ tokens
- Sandbox execution: Typically $0.001-0.01 per request
Cost Decision Framework
Calculate Cost-Benefit Ratio:
Cost = (input_tokens * input_rate) + (output_tokens * output_rate)
Benefit = time_saved * hourly_rate + quality_improvement_value
Delegate if: Benefit > Cost * 3 (safety margin for quality risks)Practical Cost Examples
Low-Cost Delegations (<$0.01):
- Count function occurrences: 50 files × 30 tokens = $0.000015
- Extract import statements: 100 files × 50 tokens = $0.000025
- Generate 10 boilerplate files: ~2K output tokens = $0.003
Medium-Cost Delegations ($0.01-0.10):
- Summarize 50K lines of code: ~125K tokens = $0.06-0.19
- Analyze architecture of 100 files: ~80K tokens = $0.04-0.12
- Generate 20 API endpoints: ~3K output tokens = $0.005
High-Cost Delegations ($0.10+):
- Review entire codebase (500K+ tokens): $0.25-0.75
- Generate detailed documentation: $0.15-0.45
- Complex refactoring analysis: $0.20-0.60
Cost Optimization Strategies
Input Optimization:
- Remove comments, tests, examples when not needed
- Use selective file patterns instead of entire directories
- Pre-filter with grep/awk for relevant content
- Compress multiple small queries into one request
Model Selection:
- Use Flash/cheaper models for simple extraction tasks
- Reserve Pro models for complex analysis only
- Consider batch processing for repetitive tasks
Cheapest-Capable Model Selection
When dispatching subagents, select the cheapest model that can handle the task. This is a recommendation, not a mandate; override when judgment dictates.
| Task Type | Has Detailed Plan? | Recommended Model |
|---|---|---|
| Implementation | Yes | haiku |
| Implementation | No | sonnet |
| Planning/reasoning | Any | sonnet/opus |
| Security/safety review | Any | sonnet minimum, prefer opus |
| Code review | Any | sonnet minimum |
Security/safety task types (never downgrade):
- Security audit
- Secret scanning
- Permissions analysis
- Auth-critical review
- Dependency vulnerability scanning
If a code review surfaces security-relevant findings, the reviewer should note "security-relevant" in its output to prevent downstream model downgrade.
Fallback: When a downgrade rule triggers but the task type is ambiguous, default to sonnet.
Rationale: Implementation tasks with detailed plans are well-scoped and predictable; haiku handles these effectively. Planning and security tasks require reasoning depth that cheaper models may lack.
Alternative Strategies:
- Break large tasks into smaller, targeted analyses
- Use local processing for sensitive operations
- Cache results for repeated analysis requests
Cost Monitoring
Set Daily/Weekly Budgets:
- Development: $1-5/day
- Batch processing: $10-50/month
- Enterprise: $100-500/month
Tracking Methods:
- Use built-in usage logging tools
- Monitor API dashboard for consumption
- Set up alerts for unexpected spikes
Using Leyline for Cost Tracking:
from leyline.quota_tracker import QuotaTracker
from leyline.usage_logger import UsageLogger
# Initialize for your service
tracker = QuotaTracker(service="gemini")
logger = UsageLogger(service="gemini")
# Check quota before operation
level, warnings = tracker.get_quota_status()
if level == "critical":
# Defer or use secondary logic
pass
# Log after operation
logger.log_usage("analyze_files", tokens=5000, success=True, duration=2.5)Handoff Patterns and Request Formulation
Suitability Evaluation
Check Prerequisites:
- [ ] Authenticate and verify external service is reachable
- [ ] Confirm quota/rate limits have capacity for the task
- [ ] Verify task does not involve sensitive data requiring local processing
- [ ] Verify expected output format is well-defined
Evaluate Service Fit:
- Does the external model excel at this task type?
- Is the latency acceptable for the workflow?
- Can results be easily validated?
Request Formulation
Four-Step Process: 1. Write a clear, self-contained prompt 2. Include all necessary context (files, constraints, examples) 3. Specify the exact output format expected 4. Define success criteria for validation
Delegation Plan Template
## Delegation Plan
- **Service**: [Gemini CLI / Qwen MCP / Other]
- **Command/Call**: [Exact invocation]
- **Input Context**: [Files, data provided]
- **Expected Output**: [Format, content type]
- **Validation Method**: [How to verify correctness]
- **Contingency**: [What to do if delegation fails]Execution and Integration
Execute: 1. Run the delegation with the planned command 2. Capture full output (save to file for audit trail) 3. Log usage metrics (tokens, duration, success/failure)
Validate:
- Does output match the expected format?
- Are results factually plausible?
- Do code suggestions compile/lint?
- Are there obvious errors or hallucinations?
Integrate:
- Apply results only after validation
- Document what was delegated and the outcome
- Note lessons learned for future delegations
Collaborative Workflows
For complex tasks requiring both intelligence AND scale:
1. Claude: Define framework, criteria, evaluation rubric
2. External: Process data, extract patterns, generate candidates
3. Claude: Analyze results, make decisions, provide recommendationsExample - Large Codebase Review: 1. Claude: Define architectural principles to evaluate 2. Gemini: Catalog all modules, extract dependency graphs 3. Claude: Analyze patterns against principles, recommend changes
Anti-Patterns vs Good Patterns
Don't Delegate:
- "Review this code and tell me if it's good" (intelligence task)
- "What's the best architecture for X?" (strategic decision)
- "Fix the bugs in this file" (requires understanding intent)
Do Delegate:
- "List all functions in these 50 files" (extraction)
- "Count occurrences of pattern X across codebase" (counting)
- "Generate boilerplate for these 20 endpoints" (templating)
Task Assessment for Delegation
Intelligence Level Classification
High Intelligence (Keep Local):
- Architecture analysis
- Design decisions
- Trade-off evaluation
- Strategic recommendations
- Nuanced code review
- Creative problem solving
Low Intelligence (Delegate):
- Pattern counting
- Bulk extraction
- Boilerplate generation
- Large-file summarization
- Repetitive transformations
Context Requirements
Large Context (Favor Delegation):
- Multi-file analysis
- Codebase-wide searches
- Log processing
Small Context (Either):
- Single-file operations
- Focused queries
Decision Matrix
| Intelligence | Context | Recommendation |
|---|---|---|
| High | Any | Keep local |
| Low | Large | Delegate |
| Low | Small | Either |
Assessment Checklist
Record the following for each task:
- [ ] Task Objective: What needs to be accomplished?
- [ ] Files Involved: How many and what size?
- [ ] Intelligence Level: High or Low?
- [ ] Context Size: Large or Small?
- [ ] Failure Impact: What happens if delegation fails?
Token Usage Estimates
Low Intelligence Tasks (Good for Delegation):
- Pattern counting across files: 10-50 tokens/file
- Bulk data extraction: 20-100 tokens/file
- Boilerplate generation: 100-500 tokens/template
- Large file summarization: 1-5% of file size tokens
Context Size Estimations:
- Single Python file (500 lines): ~2,000-3,000 tokens
- Small module (10 files): ~15,000-25,000 tokens
- Medium project (50 files): ~75,000-150,000 tokens
- Large codebase (200+ files): 300,000+ tokens
Delegation Thresholds:
- Efficient to delegate: >25,000 total tokens or >50 files
- Consider delegation: 10,000-25,000 tokens or 20-50 files
- Keep local: <10,000 tokens and <20 files
Red Flags (Stay Local)
- Security-sensitive operations (auth, crypto, secrets)
- Tasks requiring real-time iteration
- Complex multi-step reasoning chains
- Subjective quality judgments
Delegation Troubleshooting Guide
Delegation Decision Issues
Problem: Uncertain whether to delegate
- Solution: Use the decision matrix. If high intelligence required, keep local.
- Check: Does this task require understanding intent, context, or making judgments?
Problem: Delegated task produces poor results
- Common Causes:
- Task was actually high-intelligence (reclassify)
- Instructions were ambiguous (make more specific)
- Context was insufficient (add more examples)
- Wrong tool for the job (try different service)
Problem: External service fails unexpectedly
- Immediate: Default to local processing
- Investigation: Check authentication, quotas, service status
- Prevention: Validate prerequisites before delegation
Quality Control Issues
Problem: Can't validate delegated results
- Solution: Break task into smaller, verifiable chunks
- Alternative: Include self-validation in the delegation prompt
- Prevention: Always define success criteria before delegating
Problem: Results integrate poorly
- Common Causes:
- Output format mismatch (specify exact format)
- Style inconsistencies (provide style examples)
- Missing context (include integration patterns)
Service-Specific Issues
Problem: Quota exhaustion
- Immediate: Pause delegations, check quota status
- Long-term: Implement quota monitoring and throttling
- See:
Skill(leyline:quota-management)for tracking patterns
Problem: Authentication failures
- Check: API keys, environment variables, service
status
- Verify: Token expiration, permission scopes
- See:
Skill(leyline:authentication-patterns)for
setup
Problem: SDK caller account metadata missing
- Context: Early telemetry events may lack account
info due to async initialization
- Solution (2.1.51+): Set these env vars before
launching Claude Code to provide account info synchronously:
CLAUDE_CODE_ACCOUNT_UUID- account identifierCLAUDE_CODE_USER_EMAIL- user email addressCLAUDE_CODE_ORGANIZATION_UUID- organization ID- Benefit: Eliminates race condition where early
events lack metadata
Problem: Rate limiting
- Solution: Implement exponential backoff
- Prevention: Track request patterns, batch when possible
- See:
Skill(leyline:error-patterns)for retry strategies
Integration Failures
Problem: Output doesn't match expected format
- Solution: Validate schema before integration
- Fix: Update prompt with explicit format examples
- Secondary Strategy: Manual transformation or re-delegation
Problem: Partial results returned
- Check: Context window limits, timeout settings
- Solution: Break into smaller chunks
- Alternative: Use streaming if supported
Problem: Results conflict with existing code
- Prevention: Include existing patterns in delegation context
- Solution: Manual reconciliation with validation
- Long-term: Improve context specification
Execution Modes: Selection Guide
Criteria for choosing between single-session, subagents, and agent-team execution modes.
Purpose
Execution modes determine how Claude coordinates work across multiple tasks or agents. The right mode balances parallelism with coordination overhead, ensuring efficient execution without excessive context switching or communication complexity.
Quick Selection
| Scenario | Mode | Why |
|---|---|---|
| One file, sequential changes | single-session | No parallelism benefit |
| Multiple files, no dependencies | subagents | Parallelism helps |
| Multiple files, shared interfaces | agent-team | Need coordination |
| User will iterate with feedback | single-session | Easy to adjust |
| Independent research tasks | subagents | Report back only |
When to Use Each Mode
Use single-session when:
- Tasks are sequential (each depends on previous)
- Heavy same-file editing (no coordination needed)
- User wants to iterate with feedback
- Complexity is low, quick iteration matters
Use subagents when:
- Tasks are independent (no shared mutable state)
- Files don't overlap (clear ownership)
- Work is research or exploration
- Parallel execution saves significant time
Use agent-team when:
- Tasks have shared interfaces that need coordination
- Work spans multiple files with cross-dependencies
- Real-time coordination would prevent conflicts
- Mission complexity is critical (Level 3)
Getting Started
1. List your tasks and their dependencies 2. Check file overlap: do tasks touch the same files? 3. Check interface coordination: do tasks share APIs/contracts? 4. Apply the decision flowchart below 5. If agent-team, enable experimental feature first
Why This Pattern
The wrong execution mode creates problems:
- Single-session for parallel tasks: Wastes time, no parallelism
- Subagents for same-file edits: Conflicts, wasted coordination
- Agent-team for independent tasks: Overhead exceeds benefit
The selection criteria are derived from observing what works: independent tasks benefit from parallelism, but coordination overhead grows faster than linear. The break-even point is roughly 3+ independent files for subagents, and 5+ coordinated files for agent-team.
This pattern emerged from watching agent teams struggle with file conflicts that could have been avoided with the right mode.
Mode Definitions
Single-Session
How it works: Claude works through tasks sequentially within one conversation session.
Characteristics:
- No agent spawning overhead
- Full context maintained throughout
- Easy to adjust course mid-execution
- Limited parallelism
Best for:
- Sequential tasks where each depends on the previous
- Heavy same-file editing (no coordination needed)
- Low complexity work
- Quick iterations with user feedback
Example:
Tasks:
1. Fix bug in parser.py
2. Update tests for parser.py
3. Update documentation
Mode: single-session (all tasks touch same files sequentially)Subagents
How it works: Claude spawns independent subagents that work on tasks in parallel and report results back to the coordinator.
Characteristics:
- True parallelism for independent tasks
- Each subagent has isolated context
- Coordinator synthesizes results
- Workers don't communicate with each other
Best for:
- Parallel tasks with clear boundaries
- Tasks that don't share mutable state
- Research or exploration tasks
- Independent file modifications
Example:
Tasks:
1. Analyze src/api/ for error handling patterns
2. Analyze src/db/ for error handling patterns
3. Analyze src/utils/ for error handling patterns
Mode: subagents (independent analysis, report back to coordinator)Agent-Team
How it works: Claude creates a team of agents that can communicate with each other directly, not just through the coordinator.
Characteristics:
- Full peer-to-peer communication
- Shared workspace awareness
- Can coordinate on shared interfaces
- Higher coordination overhead
Best for:
- Parallel tasks with shared interfaces
- Work requiring real-time coordination
- Complex multi-component changes
- Critical missions (Station 3)
Example:
Tasks:
1. Implement frontend component A
2. Implement frontend component B
3. Integrate A and B with shared state
4. Write integration tests for A+B
Mode: agent-team (A and B need to coordinate on shared state)Note: Agent-team mode is experimental. Enable with:
{
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
}
}Selection Decision Matrix
| Factor | Single-Session | Subagents | Agent-Team |
|---|---|---|---|
| Task dependencies | Sequential | Independent | Interdependent |
| File overlap | Heavy | None/Light | Moderate |
| Parallelism benefit | Low | High | High |
| Coordination need | N/A | Low | High |
| Complexity | Low | Medium | High |
| Risk level | Any | Station 0-2 | Station 2-3 |
Selection Flowchart
START
│
├─ Do tasks share mutable files? ──────────────── YES ─┐
│ │
│ ├─→ Single-Session
│ │
├─ Do tasks need to coordinate with each other? ─ YES ─┤
│ │
│ ├─→ Agent-Team
│ │ (if enabled)
├─ Are tasks independent? ─────────────────────── YES ─┤
│ │
│ ├─→ Subagents
│ │
└─ Otherwise ──────────────────────────────────────────→ Single-SessionMode Compatibility
Subagents and Worktrees
For parallel tasks with potential file conflicts, combine subagents with git worktrees:
Agent A: worktree/feature-a/
Agent B: worktree/feature-b/
Each agent works in isolated worktree, results merged later.Agent-Team and Shared Workspace
Agent-team mode works best when agents share awareness of:
- File modifications (who's editing what)
- Interface contracts (agreed APIs)
- Progress state (what's done, what's blocked)
Mode Transitions
You can transition between modes mid-mission:
1. Single-session → Subagents: Spawn agents for independent research phases 2. Subagents → Single-session: Consolidate findings and implement sequentially 3. Agent-team → Subagents: Simplify if coordination proves unnecessary
Never transition away from agent-team mid-task if agents are actively coordinating.
Examples
Example 1: Feature Research (Subagents)
Mission: Research best practices for implementing rate limiting
Tasks:
1. Research rate limiting algorithms
2. Research Redis-based rate limiting
3. Research rate limiting in similar frameworks
Mode: subagents
Rationale: Independent research tasks, no file modificationsExample 2: Bug Fix (Single-Session)
Mission: Fix null pointer exception in user service
Tasks:
1. Locate the bug
2. Write a failing test
3. Fix the bug
4. Verify test passes
Mode: single-session
Rationale: Sequential tasks in same file, quick iterationExample 3: API and Frontend (Agent-Team)
Mission: Implement user preferences feature
Tasks:
1. Create API endpoints for preferences
2. Create database schema
3. Build frontend preferences UI
4. Write integration tests
Mode: agent-team
Rationale: Tasks 1-3 need to coordinate on data structure,
task 4 depends on 1-3Anti-Patterns
Anti-Pattern 1: Subagents for Same-File Edits
# BAD: Two agents editing same file
Agent A: Modify src/api.py (add endpoint)
Agent B: Modify src/api.py (fix bug)
# GOOD: Single-session
Claude: Modify src/api.py (add endpoint, then fix bug)Anti-Pattern 2: Single-Session for Independent Research
# BAD: Sequential research
1. Research Redis rate limiting (15 min)
2. Research Memcached rate limiting (15 min)
3. Compare results
# GOOD: Parallel subagents
Agent A: Research Redis (15 min)
Agent B: Research Memcached (15 min)
Coordinator: Compare (5 min)
Total: 20 min vs 35 minAnti-Pattern 3: Agent-Team Without Coordination Need
# BAD: Agent-team for truly independent tasks
Agent A: Fix typo in README.md
Agent B: Fix typo in CONTRIBUTING.md
# GOOD: Subagents or single-session
These don't need to coordinate. Agent-team adds overhead.Integration with Squadron Composition
See ../agent-teams/references/squadron-composition.md for:
- Team sizing by mission complexity
- Role definitions (Admiral, Captain, Red-cell)
- File ownership rules
Source
Adapted from Nelson by Harry Munro, used under MIT license.
Shared Shell Execution Capability
Overview
This module provides shared shell execution functionality for all delegation services (Gemini, Qwen, etc.). It standardizes command construction, execution, error handling, and logging across different external LLM services.
Core Components
1. Service Registry
class DelegationService:
"""Registry for external LLM delegation services"""
def __init__(self, name: str, command_prefix: str, auth_method: str):
self.name = name
self.command_prefix = command_prefix
self.auth_method = auth_method
self.quota_manager = None
self.usage_logger = None2. Command Builder
class CommandBuilder:
"""Builds standardized commands for different services"""
def build_command(self, service: DelegationService, prompt: str,
files: List[str], options: Dict) -> str:
"""Build service-specific command with standard options"""3. Execution Engine
class ExecutionEngine:
"""Handles command execution with common patterns"""
def execute(self, command: str, service: DelegationService) -> ExecutionResult:
"""Execute command with error handling and logging"""Supported Services
Gemini CLI
# Standard pattern
gemini -p "@path/to/file Analyze this code"
gemini --model gemini-2.5-pro-exp -p "..."
gemini --output-format json -p "..."Qwen CLI (when available)
# Assuming Qwen has similar CLI interface
qwen -p "@path/to/file Analyze this code"
qwen --model qwen-max -p "..."
qwen --format markdown -p "..."Common Delegation Flow
1. Service Selection: Choose appropriate service based on task requirements 2. Authentication: Verify service authentication using service-specific methods 3. Quota Check: Check service-specific limits and usage 4. Command Construction: Build standardized command using shared builder 5. Execution: Execute with common error handling and logging 6. Result Processing: Standardized result validation and integration
Configuration
Service Configuration
{
"services": {
"gemini": {
"command": "gemini",
"auth_method": "api_key",
"quota_limits": {
"requests_per_minute": 60,
"requests_per_day": 1000,
"tokens_per_day": 1000000
}
},
"qwen": {
"command": "qwen",
"auth_method": "mcp",
"quota_limits": {
"requests_per_minute": 120,
"requests_per_day": 2000,
"tokens_per_day": 2000000
}
}
}
}Usage Examples
Basic Delegation
from delegation_core import Delegator
delegator = Delegator()
result = delegator.delegate(
service="gemini",
prompt="Analyze these files for security issues",
files=["src/main.py", "src/auth.py"],
options={"model": "gemini-2.0-pro-exp"}
)Service Selection Based on Requirements
# Auto-select best service
result = delegator.smart_delegate(
prompt="Summarize this large codebase",
files=["src/**/*"],
requirements={"large_context": True, "fast_response": False}
)Related skills
How it compares
Use for token-dollar math on delegated LLM calls, not for writing API reference docs or implementing barcode capture SDKs.
FAQ
Who is delegation-core for?
Developers shipping agent workflows who pay per token on external models and want delegation-core’s rates and cost-benefit rule before firing another API.
When should I use delegation-core?
Use it in Operate when reviewing agent bills and quotas, in Build when designing which tasks to route to Flash versus Pro, and before any medium- or high-cost delegation (summaries, architecture passes, bulk codegen).
Is delegation-core safe to install?
It is reference math and guidelines; review the Security Audits panel on this Prism page and treat any real API keys only in your own quota/logging setup, not inside the skill text.