Логотип External Tools

External Tools

Сообщество
dsifry
external-tools

Delegate implementation and review tasks to external AI CLI tools (Codex, Gemini) with cross-model adversarial review

Add to TypingMind

Обзор

Издательdsifry
Репозиторийmetaswarm
Название навыкаexternal-tools
Звёзды
421
Форки
54
Файлы в комплекте
4
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 4

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — dsifry. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ External Tools в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/dsifry/metaswarm/tree/main/skills/external-tools
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/dsifry/metaswarm.git /tmp/metaswarm
mkdir -p .claude/skills
cp -r /tmp/metaswarm/skills/external-tools .claude/skills/external-tools
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык External Tools в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык External Tools, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык External Tools не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

External Tools Skill

Purpose

This skill delegates implementation and review tasks to external AI CLI tools (OpenAI Codex CLI, Google Gemini CLI), enabling cost savings through cheaper models and cross-model adversarial review that eliminates single-model blind spots. Three core principles govern every interaction: one job per invocation (an external tool implements OR reviews, never self-validates), minimal permissions (sandboxed execution scoped to the task's working directory with only the tool's own API key), and the orchestrator verifies independently (external tools report facts only, the orchestrator judges pass/fail).


Prerequisites

Required Tools

ToolInstallAuth
OpenAI Codex CLInpm i -g @openai/codexAPI key or ChatGPT subscription
Google Gemini CLInpm i -g @google/gemini-cliGoogle login (free 1K req/day) or API key

Neither tool is strictly required. The skill adapts based on what is available (see Escalation Model below).

Configuration

Per-project config at .metaswarm/external-tools.yaml (optional -- if absent, external tools are not used):

yaml
adapters:
  codex:
    enabled: true
    model: "gpt-5.3-codex"
    timeout_seconds: 300
    sandbox: docker          # docker | platform | none
  gemini:
    enabled: true
    model: "pro"
    timeout_seconds: 300
    sandbox: docker

routing:
  default_implementer: "cheapest-available"
  escalation_order: ["codex", "gemini", "claude"]

budget:
  per_task_usd: 2.00        # circuit breaker per task
  per_session_usd: 20.00    # circuit breaker per session

Fallback Behavior

  • Both tools available: Full cross-model delegation and review
  • One tool available: Reduced chain with mutual review between the tool and Claude
  • No tools available: Existing metaswarm behavior unchanged; skill is a no-op

Quick Reference

Health Check

bash
# Check if Codex is installed, authenticated, and reachable
adapters/codex.sh health

# Check Gemini
adapters/gemini.sh health

Returns JSON with status: "ready|degraded|unavailable".

Implement

bash
adapters/codex.sh implement \
  --worktree "/tmp/ext-codex-task-42" \
  --prompt-file "/private/tmp/xt-abc123/prompt.md" \
  --attempt 1 \
  --timeout 300

Review

bash
adapters/gemini.sh review \
  --worktree "/tmp/ext-codex-task-42" \
  --rubric-file "./rubrics/external-tool-review-rubric.md" \
  --spec-file "/private/tmp/xt-abc123/spec.md" \
  --timeout 300

All commands return a uniform JSON envelope with facts only (exit code, files changed, cost, duration). The orchestrator interprets results -- adapters never self-judge.


Workflow: Routing & Dispatch

Phase 0: Tool Discovery (Health Checks)

Before dispatching any task, the orchestrator runs health checks to determine which tools are available:

bash
# Run health checks for all configured adapters
for adapter in adapters/*.sh; do
  result=$("$adapter" health)
  # Parse status: ready | degraded | unavailable
done

Health is checked per task dispatch, not just at session start. Auth tokens can expire mid-session, network conditions change, and rate limits reset. A tool that was ready five minutes ago may now be unavailable.

Build the available tools list:

python
available_tools = [t for t in adapters if t.health() == "ready"]

Phase 1: IMPLEMENT (External Tool or Claude)

If an external tool is selected as implementer:

  1. Create worktree -- git worktree add "$WORKTREE_PATH" -b "external/$TOOL/$TASK_ID" for isolation
  2. Package context -- Gather relevant files, spec, acceptance criteria into a prompt file in a secure temp dir (mode 700, trap cleanup). Token-budget the context to fit the model's window.
  3. Invoke -- safe_invoke() with timeout wrapper; capture JSON output
  4. Scope check -- Verify all file changes are within the declared file scope; revert any out-of-scope changes
  5. Capture output -- Facts only: exit code, files changed, diff stats, cost, duration

If Claude is selected (escalation or no external tools), use the existing Task() mechanism unchanged.

Phase 2: VALIDATE (Always Orchestrator -- Unchanged)

The orchestrator independently runs all quality gates:

  • npm test / npx vitest run
  • npx tsc --noEmit
  • npx eslint <changed-files>
  • Coverage enforcement via .coverage-thresholds.json
  • File scope verification via git diff --name-only

This phase is identical whether the implementer was an external tool or Claude. Never trust the implementer's self-report.

Phase 3: ADVERSARIAL REVIEW (Cross-Model)

The key advantage of external tools: the writer is always reviewed by a different model.

ImplementerReviewer 1Reviewer 2
CodexGemini (via adapter)Claude (via Task)
GeminiCodex (via adapter)Claude (via Task)
ClaudeCodex (via adapter)Gemini (via adapter)

Review is invoked via the adapter's review command. The orchestrator reads the reviewer's raw log and evaluates it independently -- the adapter never returns a pass/fail verdict.

Phase 4: COMMIT (Unchanged)

After passing adversarial review:

  1. Merge the worktree branch into the working branch
  2. Clean up the worktree (git worktree remove)
  3. Log the session for self-reflection
  4. Commit with DoD verification in the commit message

Escalation Model (Availability-Aware)

The orchestrator adapts its escalation chain based on which tools passed their health checks.

Scenario 1: Two External Tools Available (5 attempts max)

Model A implements (attempt 1)
  Orchestrator validates + cross-model review (B + Claude)
  FAIL -> feedback to Model A

Model A implements (attempt 2, with review feedback)
  Orchestrator validates + cross-model review
  FAIL -> escalate to Model B

Model B implements (attempt 1, with Model A's branch as reference)
  Orchestrator validates + cross-model review (A + Claude)
  FAIL -> feedback to Model B

Model B implements (attempt 2, with review feedback)
  Orchestrator validates + cross-model review
  FAIL -> escalate to Claude

Claude implements (with both branches as reference)
  Orchestrator validates + cross-model review (A + B)
  FAIL -> alert user with all branches, findings, CI results

Worst case: A(2) + B(2) + Claude(1) = 5 attempts before user alert.

Scenario 2: One External Tool Available (3 attempts max)

Model A implements (attempt 1)
  Orchestrator validates + review (Claude reviews)
  FAIL -> feedback to Model A

Model A implements (attempt 2, with review feedback)
  Orchestrator validates + review (Claude reviews)
  FAIL -> escalate to Claude

Claude implements (with Model A's branch as reference)
  Orchestrator validates + review (Model A reviews)
  FAIL -> alert user

Worst case: A(2) + Claude(1) = 3 attempts before user alert.

Scenario 3: No External Tools Available

Existing metaswarm behavior unchanged.
Claude implements via Task() mechanism.
Standard adversarial review (fresh Task() instance).

No change to the current workflow. The skill is a no-op.


Routing Logic

The orchestrator selects the implementer for each task using cheapest-available selection:

python
available_tools = [t for t in adapters if t.health() == "ready"]

if len(available_tools) == 2:
    implementer = cheapest(available_tools)
    reviewers = [other_tool, claude]
    escalation = [implementer, other_tool, claude, user]
elif len(available_tools) == 1:
    implementer = available_tools[0]
    reviewers = [implementer, claude]  # mutual review
    escalation = [implementer, claude, user]
else:
    # pure metaswarm, no change
    implementer = claude
    reviewers = [claude_fresh_task]
    escalation = [claude, user]

Selection criteria for cheapest():

  1. Pick the tool with lower estimated cost per invocation (based on model pricing and average token usage from session logs)
  2. On tie, prefer the tool with higher historical success rate for this task type
  3. If no historical data, prefer Gemini (free tier) over Codex

Prompt File Format

The prompt file is the key interface between the orchestrator and external tools. It must be self-contained -- the external tool has no access to BEADS, knowledge base, or conversation history.

markdown
# Task: [task title]

## Acceptance Criteria
- [ ] criterion 1
- [ ] criterion 2
- [ ] criterion 3

## Context
[relevant file contents, token-budgeted]
[prioritized: changed files > test files > imports > surrounding context]

## Coding Standards
[extracted from project's CLAUDE.md / coding standards guide]
[language-specific rules, naming conventions, patterns]

## Test Expectations
[what tests should pass after implementation]
[coverage requirements from .coverage-thresholds.json]
[test runner command: e.g., npx vitest run]

## Previous Attempt (if retry)
[review feedback from last attempt -- what to fix]
[DO NOT include full prior output, only the actionable feedback summary]

## Prior Model's Attempt (if escalation)
[diff summary from previous model's branch -- what was tried, why it failed]
[DO NOT include full branch, only the relevant diff summary]

Token budgeting rules (handled by package_context() in _common.sh):

  • Estimate tokens per file using chars/4 heuristic
  • Prioritize context: changed files > test files > imports > surrounding context
  • Truncate to the model's context budget (configurable per adapter)
  • On retry: include review feedback summary, not full prior output
  • On escalation: include prior branch diff summary, not full branch

Error Handling

When an adapter returns exit_code != 0, the error_type field determines the orchestrator's response:

Error TypeMeaningOrchestrator Action
tool_not_installedBinary not foundSkip adapter, try next in escalation chain
auth_expiredAPI key invalid or expiredEscalate to user with setup instructions
auth_missingNo API key configuredEscalate to user with setup instructions
network_errorCannot reach APIRetry with exponential backoff, then skip adapter
rate_limitedAPI rate limit hitWait and retry (respect Retry-After if provided)
timeoutTool exceeded time limitRetry once with increased timeout, then skip adapter
context_too_largeInput exceeds context windowReduce context via package_context(), retry
cost_limit_exceededWould exceed budgetSkip adapter, alert user about budget status
tool_crashUnexpected exitRetry once, then skip adapter
output_parse_errorMalformed JSON outputLog raw output for debugging, treat as failure

General rules:

  • "Skip adapter" means move to the next tool in the escalation chain, not abort the task
  • All errors are logged to ~/.claude/sessions/ for self-reflection
  • Auth errors always escalate to the user -- the orchestrator cannot fix credentials
  • Network and rate-limit errors get transient-failure treatment (backoff + retry)

Budget Enforcement

Two circuit breakers prevent runaway costs:

Per-Task Budget (per_task_usd)

Before each adapter invocation, the orchestrator checks cumulative cost for the current task:

if task_cost_so_far + estimated_cost > per_task_usd:
    error_type = "cost_limit_exceeded"
    skip adapter, try next in escalation chain (or Claude)

Default: $2.00 per task.

Per-Session Budget (per_session_usd)

Before each adapter invocation, the orchestrator checks cumulative cost across all tasks in the session:

if session_cost_so_far + estimated_cost > per_session_usd:
    error_type = "cost_limit_exceeded"
    alert user: "Session budget exhausted. External tools disabled for remaining tasks."
    fall back to Claude for all remaining work

Default: $20.00 per session.

Cost Tracking

Cost is extracted post-execution from the adapter's JSON output (cost.input_tokens, cost.output_tokens) and converted to USD using known model pricing. Cost estimation is approximate (~15-30% variance due to different tokenizers per model). There is no pre-execution cost prediction in v1 -- cost is measured after execution, not capped before.


Anti-Patterns

#Anti-PatternWhy It's WrongWhat to Do Instead
1Trusting external tool self-reports -- tool says "all tests pass" and orchestrator believes itExternal tools can hallucinate, skip steps, or misinterpret results; same reasoning as the no-self-certification rule for subagentsOrchestrator runs Phase 2 (VALIDATE) independently; adapter output contains facts only, never verdicts
2Skipping cross-model review -- "the external tool's code looks fine, committing directly"Single-model blind spots are the whole reason this skill exists; bypassing review defeats the purposeAlways run Phase 3 with a different model as reviewer; cross-model review is mandatory
3Running without timeout -- invoking an adapter without safe_invoke() timeout wrapperExternal CLIs can hang on rate limits, network issues, or infinite loops; an unmonitored invocation blocks the entire pipelineAlways use safe_invoke() with the configured timeout_seconds; handle timeout as a retryable error
4Passing the full environment -- running the external tool with the orchestrator's full env varsLeaks API keys, session tokens, and internal state to an external process that only needs its own credentialsUse env -i to pass only HOME, PATH, and the tool's own API key; see Minimal Environment in the design doc
5Working in the main repo -- running external tools directly in the project working directory instead of a worktreeConcurrent invocations corrupt each other's state; failed attempts leave dirty files; no clean rollback pathAlways create an isolated git worktree per invocation; merge only after all phases pass

Logging

All adapter invocations produce structured session log entries in ~/.claude/sessions/:

Session log entry:
  - timestamp, tool, command, model, attempt
  - prompt content hash (what we asked)
  - output JSON (facts: exit code, files changed, cost)
  - CI gate results (from orchestrator's Phase 2)
  - review output (from cross-model Phase 3)
  - outcome: success | retry | escalated | user_alert
  - cost (tokens used, estimated USD)

These logs feed the existing /self-reflect pipeline. Over time, the knowledge base accumulates routing intelligence:

  • Patterns: "Codex excels at single-file TypeScript implementations"
  • Gotchas: "Gemini tends to skip error handling in async functions"
  • Routing decisions: "Route database migration tasks directly to Claude (external tools fail 80%)"

Future routing decisions improve automatically as the knowledge base grows from session log analysis.

Файлы в комплекте

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ External Tools?

Delegate implementation and review tasks to external AI CLI tools (Codex, Gemini) with cross-model adversarial review

Зачем использовать External Tools в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. External Tools — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить External Tools в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/dsifry/metaswarm/tree/main/skills/external-tools. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать External Tools?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать External Tools?

С любым количеством. В TypingMind вы можете использовать External Tools с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ External Tools?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — dsifry. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все
Логотип openclaw

Clawsweeper

openclaw
ОрганизацияПопулярный

Для любых задач ClawSweeper: отчёты о проверке issue/PR в OpenClaw, задания на исправление, PR с облачными исправлениями, команды упоминания сопровождающих @clawsweeper, доверенные автоисправления и автомерж после проверки ClawSweeper, мониторинг GitHub Actions…

82.2K
391K
Файлы: 1
Открыть
Логотип openclaw

Control Ui E2e

openclaw
ОрганизацияПопулярный

Используйте при проектировании, тестировании, исправлении или расширении графического интерфейса OpenClaw Control UI, включая галереи стресс-тестов интерфейса с полями для отзывов, сквозные проверки Vitest + Playwright, сценарии Gateway с заглушками…

82.2K
391K
Файлы: 1
Открыть
Логотип openclaw

Deslop

openclaw
ОрганизацияПопулярный

Очистка AI-slop только в изменениях ветки: удалите лишние комментарии и защитные проверки, маскировку типов и отклонения от стиля перед автоматическим ревью.

82.2K
391K
Инструкции
Открыть
Логотип openclaw

Discord Clawd

openclaw
ОрганизацияПопулярный

Используйте для общения с агентом или сессией OpenClaw, связанными с Discord; не используйте для поиска по архиву.

82.2K
391K
Файлы: 1
Открыть

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇