К основному содержанию
скилл CX Codex

airflow-hitl — скилл для Claude Code: пауза DAG до ответа человека

Скилл для сборки HITL-воркфлоу в Airflow: шаги согласования, ввод формы и ветвление по выбору человека. Нужен, когда DAG должен ждать ответа из UI.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add astronomer/agents --skill airflow-hitl -a claude-code
Открыть на GitHub

Что делает airflow-hitl

Скилл помогает писать DAG, которые останавливаются и ждут реакции человека через интерфейс Airflow или REST API. Операторы отложенные: пока идёт ожидание, слот воркера освобождается.

Внутри — пошаговый разбор: сначала выбор класса под задачу (ApprovalOperator для согласования, HITLOperator для набора опций, HITLBranchOperator для ветвления, HITLEntryOperator для формы, HITLTrigger для кастомных случаев), затем сверка актуальных сигнатур через af registry parameters standard. Имена классов зашиты только в таблице выбора — параметры провайдера меняются от релиза к релизу, поэтому скилл требует смотреть живой реестр, а не писать конструктор по памяти.

Нужен Airflow 3.1 и выше, проверить можно командой af config version. Ответы приходят из раздела Browse → Required Actions, а для внешних интеграций скилл показывает, как найти актуальный эндпоинт через af api ls --filter hitl и отвечать PATCH-запросом. Ограничение по правам ответа зависит от активного auth manager: имя параметра и формат идентификатора надо смотреть в реестре, потому что у Astro это ID пользователя, у FabAuthManager — email, у SimpleAuthManager — username.

Какие задачи решает

  • поставить шаг согласования перед запуском задачи
  • собрать форму и получить ввод прямо посреди прогона
  • разветвить DAG по выбору человека
  • освободить слот воркера на время ожидания ответа
  • отвечать на запросы HITL из внешнего сервиса

Примеры запросов агенту

  • собери DAG с ApprovalOperator: согласование отчёта перед публикацией
  • нужно ветвление по выбору человека — покажи пример с HITLBranchOperator
  • как ответить на pending HITL-задачу через REST API?

Как установить airflow-hitl

1Через Skills CLI (Vercel)

npx skills add astronomer/agents --skill airflow-hitl -a claude-code

2Вручную: положить файлы

~/.claude/skills/airflow-hitl/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/airflow-hitl/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о airflow-hitl

Как установить airflow-hitl в Claude?

Выполните npx skills add astronomer/agents --skill airflow-hitl -a claude-code. Файл скилла появится по пути ~/.claude/skills/airflow-hitl/SKILL.md.

Что делает airflow-hitl?

Помогает строить human-in-the-loop воркфлоу в Airflow: шаги approve/reject, сбор формы, ветвление по выбору человека. Операторы отложенные, поэтому воркер не занят во время ожидания.

Какая версия Airflow нужна?

Airflow 3.1 и выше. Проверить установленную версию можно командой af config version.

Исходный текст

SKILL.md · Apache-2.0
---
name: airflow-hitl
description: Builds human-in-the-loop (HITL) Airflow workflows - approval gates, form input, and human-driven branching. Use when a DAG needs a human in the loop - an approval or reject step, sign-off before a task runs, a decision or approval UI, branching on a human choice, or collecting form input mid-run; also on mentions of ApprovalOperator, HITLOperator, HITLBranchOperator, HITLEntryOperator, or HITLTrigger. Requires Airflow 3.1+. Not for AI/LLM task calls (see migrating-ai-sdk-to-common-ai).
---

# Airflow Human-in-the-Loop Operators

Pause a DAG until a human responds via the Airflow UI or REST API. HITL operators are deferrable — they release their worker slot while waiting.

> **Requires Airflow 3.1+** (`af config version`).
>
> **UI location**: Browse → Required Actions. Respond from the task instance page's Required Actions tab.
>
> **Cross-references**: `migrating-ai-sdk-to-common-ai` for AI/LLM task decorators; `airflow` for registry and API discovery commands used below.

---

## Step 1 — Pick the capability you need

| Capability | Class (verify in Step 2) |
|---|---|
| Approve or reject; downstream skips on reject | `ApprovalOperator` |
| Present N options and return which were chosen | `HITLOperator` |
| Branch to one or more downstream tasks based on a choice | `HITLBranchOperator` |
| Collect a form (no approve/select step) | `HITLEntryOperator` |
| Use the HITL trigger directly (advanced / custom operators) | `HITLTrigger` |

This is the only place class names are hardcoded. The provider adds, renames, and removes params across releases — do not copy parameter lists from memory. Fetch the current signature before writing code.

---

## Step 2 — Discover the current signatures from the Airflow Registry

Before writing HITL code, run these to see the live roster and constructor params (see the `airflow` skill for the full `af registry` reference):

```bash
# Every HITL-related module in the standard provider
af registry modules standard \
  | jq '.modules[] | select(.import_path | test("\\.hitl\\.")) | {name, type, import_path, short_description, docs_url}'

# Constructor signatures: name, type, default, required, description
af registry parameters standard \
  | jq '.classes | to_entries[] | select(.key | test("\\.hitl\\.")) | {fqn: .key, parameters: .value.parameters}'

# Pin to the exact installed provider version
af config providers \
  | jq '.providers[] | select(.package_name == "apache-airflow-providers-standard") | .version'
# then: af registry parameters standard --version <VERSION>
```

If the registry shows a param that this skill does not mention, prefer the registry. If the registry shows a class that is not in Step 1, treat it as additive — the decision table above may be stale.

---

## Step 3 — Canonical example (approval gate)

Starting point for any HITL task. Adapt by swapping the class name and params per Step 2.

```python
from airflow.providers.standard.operators.hitl import ApprovalOperator
from airflow.sdk import dag, task, chain, Param
from pendulum import datetime

@dag(start_date=datetime(2025, 1, 1), schedule="@daily")
def approval_example():
    @task
    def prepare():
        return "Review quarterly report"

    approval = ApprovalOperator(
        task_id="approve_report",
        subject="Report Approval",
        body="{{ ti.xcom_pull(task_ids='prepare') }}",
        defaults="Approve",              # Auto-selected on timeout
        params={"comments": Param("", type="string")},
    )

    @task
    def after_approval(result):
        print(f"Decision: {result['chosen_options']}")

    chain(prepare(), approval)
    after_approval(approval.output)

approval_example()
```

For the other classes in Step 1, the shape is the same (`task_id`, `subject`, plus class-specific params). Verify each constructor through Step 2 — for example, `HITLBranchOperator` requires every option either to match a downstream task id directly or to be resolved via a mapping param surfaced in the registry.

---

## Step 4 — Behavior contracts (stable across versions)

### Timeout
- With `defaults` set: task succeeds on timeout, default option(s) selected.
- Without `defaults`: task fails on timeout.

### Markdown + Jinja in `body`
`body` supports Markdown and is Jinja-templatable. Render XCom context directly:

```python
body = """**Total Budget:** {{ ti.xcom_pull(task_ids='get_budget') }}

| Category | Amount |
|----------|--------|
| Marketing | $1M |
"""
```

### Callbacks
All HITL operators accept the standard Airflow callback kwargs (`on_success_callback`, `on_failure_callback`, etc.).

### Notifiers
HITL operators accept a `notifiers` list. Inside a notifier's `notify(context)` method, build a link to the pending task with `HITLOperator.generate_link_to_ui_from_context(context, base_url=...)`.

### Restricting who can respond
The parameter name and accepted identifier format depend on the active auth manager. Do **not** hardcode — check which one is active and which kwarg the current provider exposes:

```bash
af config show | jq '.auth_manager // .core.auth_manager'
```

Then look up the current kwarg in Step 2 (at the time of writing it is `assigned_users`, accepting identifiers in whatever format the active auth manager uses — Astro uses the Astro user ID, FabAuthManager uses email, SimpleAuthManager uses username).

---

## Step 5 — Responding from external integrations

For Slack bots, custom apps, or scripts. Discover the live endpoint rather than hardcoding a path:

```bash
af api ls --filter hitl           # live endpoint list
af api spec \
  | jq '.paths | to_entries[] | select(.key | test("hitl"))'   # request/response schemas
```

The PATCH-to-respond pattern is stable; the exact path is discovered. Typical shape:

```python
import os, requests

HOST = os.environ["AIRFLOW_HOST"]
TOKEN = os.environ["AIRFLOW_API_TOKEN"]
HEADERS = {"Authorization": f"Bearer {TOKEN}"}

# List pending — use the path from `af api ls --filter hitl`
requests.get(f"{HOST}/<path>", headers=HEADERS, params={"state": "pending"})

# Respond — same discovered path family, PATCH
requests.patch(
    f"{HOST}/<path>/{dag_id}/{run_id}/{task_id}",
    headers=HEADERS,
    json={"chosen_options": ["Approve"], "params_input": {"comments": "ok"}},
)
```

---

## Step 6 — Safety checks

- [ ] Airflow version ≥ 3.1 (`af config version`).
- [ ] Constructor kwargs match the current registry output from Step 2 — no `respondents`-vs-`assigned_users` style drift.
- [ ] For branching: every option resolves to a downstream task id (directly or via the mapping kwarg from Step 2).
- [ ] Every value in `defaults` is also in `options`.
- [ ] `execution_timeout` set; `defaults` configured if timeout should succeed rather than fail.
- [ ] API token configured if external responders are part of the flow.

---

## References

The upstream docs URL is surfaced per-module by the registry — do not hardcode:

```bash
af registry modules standard \
  | jq '.modules[] | select(.import_path | test("\\.hitl\\.")) | {name, docs_url}'
```

## Related skills

- **airflow** — `af registry`, `af api`, `af config` command reference.
- **migrating-ai-sdk-to-common-ai** — AI/LLM task decorators and GenAI patterns (common-ai provider).
- **authoring-dags** — general DAG writing best practices.
- **testing-dags** — iterative test → debug → fix cycles.

© astronomer · Apache-2.0 · astronomer/agents

Похожие скиллы

Всё по теме «DevOps и инфраструктура» →
apache-airflow-orchestration reason-machines Скилл даёт агенту знания по Apache Airflow: сборка DAG, расписания, операторы, сенсоры, разбор падений задач. CX Codex +1 2 400установок airflow-dag-patterns Seth Hobson Скилл помогает проектировать DAG в Apache Airflow, связывать задачи и проверять пайплайны. Подойдёт для ETL, пакетных заданий и отладки запусков. CX Codex 11 000установок managed-airflow-dag-authoring официальный google Помогает создавать и проверять DAG Apache Airflow для Managed Service for Apache Airflow. Нужен при разработке или расширении DAG. CX Codex 4 100установок managed-airflow-dag-troubleshooting официальный google Разбирает сбои DAG run и task instance в Managed Service for Apache Airflow по логам, состояниям задач и исходному коду DAG. CX Codex 3 500установок testing-mwaa-workflow aws Скилл запускает и проверяет пайплайны в Amazon MWAA до финального статуса. Он помогает протестировать Python DAG или Serverless-сценарий перед сдачей в работу. CX Codex +1 861установок langchain-middleware langchain-ai Скилл добавляет промежуточные хуки для LangChain-агентов: останавливает выполнение перед опасными вызовами инструментов, даёт человеку одобрить, отредактировать или отклонить действие, перехватывает вызовы для логирования и retry-логики. CX Codex +1 16 200установок

Из того же набора23

tracing-downstream-lineage Скилл находит всё, что зависит от таблицы или DAG, и показывает, что сломается при изменении. Пригодится перед правкой схемы. CX Codex +1 1 000установок profiling-tables Скилл для глубокого анализа таблиц базы данных. Помогает изучить структуру, статистику по колонкам и оценить качество данных перед работой. CX Codex +1 1 000установок tracing-upstream-lineage Скилл для агента, который отвечает на вопрос «откуда взялись эти данные»: ищет DAG, читает исходники и строит цепочку до внешних систем. CX Codex +1 1 000установок cosmos-dbt-core Превращает проект dbt Core в Airflow DAG или TaskGroup через Astronomer Cosmos. Пригодится, когда нужно расписание и ретраи для моделей dbt. CX Codex +1 962установок creating-openlineage-extractors Скилл помогает настроить сбор OpenLineage для операторов Airflow без встроенной поддержки. Полезен, когда нужны метаданные уровня колонок или кастомная логика происхождения данных. CX Codex +1 933установок warehouse-init Собирает метаданные всех баз, схем и таблиц хранилища в .astro/warehouse.md, чтобы агент находил нужную таблицу без запросов к складу. CX Codex +1 814установок deploying-airflow Скилл для деплоя DAG и проектов Airflow: команды Astro CLI, Docker Compose и Helm. Пригодится, когда нужно выкатить пайплайны в прод. CX Codex +1 786установок troubleshooting-astro-deployments Скилл ведёт агента по шагам диагностики продакшн-развёртываний Astronomer через Astro CLI: логи, ошибки, переменные окружения. CX Codex +1 622установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой