Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install kibana-workflows@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin kibana-workflows v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install kibana-workflows

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/kibana-workflows/

Extract the ZIP to .github/skills/ in your repo. The folder name must match kibana-workflows for Copilot to auto-discover it.

Skill Files (8)

SKILL.md 18.6 KB
---
name: kibana-workflows
description: >
  Author, validate, test, run, and inspect Elastic Workflow YAML definitions. Use
  when the user wants to turn natural language into a Kibana workflow, fix workflow
  YAML, understand triggers or steps, or run a quick test loop against a real Kibana.
metadata:
  author: elastic
  version: 0.5.0
  universal: true
compatibility: Kibana 9.4 or later with matching Elasticsearch and an Enterprise license,
  or an Elastic Serverless project with Workflows available; requires the `elastic`
  CLI ≥ 0.2 with `stack kb workflows` support. When Agent Builder is enabled on the
  target Kibana, the `platform.core.generate_workflow` and `platform.workflows.*`
  tools are preferred over the raw schema.
---

# Author Elastic Workflows

Create and iterate on Elastic Workflow YAML definitions. Workflows are declarative automations that run inside Kibana:
they query Elasticsearch, set data, branch, loop, call connectors, create cases, notify external systems, and invoke AI
steps.

<!-- begin-partial: preamble -->

## Environment Configuration

This skill executes Elasticsearch operations through the `elastic` CLI. If the
[`elastic` CLI](https://github.com/elastic/cli#configuration) is not installed, tell the user what it is needed for. Do
not guess credentials, call the HTTP API directly, or attempt other workarounds.

This skill references operations in HTTP-shorthand form (e.g., `GET /`, `GET /_cat/indices`, `GET /{index}/_mapping`,
`GET /{index}/_settings/index.mode`, `POST /_query`). The [Operations](#operations) table at the end of this document
maps each shorthand to the equivalent `elastic` CLI command — always use the CLI rather than calling the HTTP API
directly.

<!-- end-partial: preamble -->

If the user asks only for a draft or explanation and explicitly forbids live access, skip connection verification and do
not call the CLI or APIs. State that the draft was not validated against a target deployment.

If workflow APIs are unavailable, report the returned status and message. Common causes are an unsupported Kibana
version, insufficient license or feature privileges, or Workflows not being offered on the target project. The
`workflows:ui:enabled` setting controls the Kibana UI; it does not remove the public Workflows APIs.

## Pick the authoring path

Default to the **Discovery-tools path** below — the `platform.workflows.*` tools are registered by default on Kibana
9.5+ and Serverless. Confirm with one probe: `GET kbn:/api/agent_builder/tools` returns
`{ "results": [ { "id": ... } ] }`; save it to a file and grep for `"id": "platform.workflows."`. Two fallbacks, both
loaded only when needed:

- No `agent_builder` endpoint (404) or no `platform.workflows.*` ids (e.g. Kibana 9.4) → read
  [references/schema-path.md](references/schema-path.md) and hand-author from the raw JSON Schema.
- An LLM connector is wired into Agent Builder and the user prefers Kibana's own generator → read
  [references/generator-path.md](references/generator-path.md).

State which path you picked and why in one sentence before proceeding. Measured path benchmarks live in
[references/path-performance.md](references/path-performance.md).

## Guidelines (all paths)

- **Treat tests as executions.** `POST kbn:/api/workflows/test` runs the workflow graph, and
  `POST kbn:/api/workflows/step/test` runs the selected step. Test only when every executed action is read-only or the
  user authorized its effects. Otherwise test a copy whose writes, notifications, and external calls are replaced with
  `console`, then restore the real steps and save the workflow disabled.
- **Cite endpoints in HTTP shorthand, never raw transport.** This skill's body refers to operations like
  `POST kbn:/api/workflows/test`. The [Operations](#operations) table is the single place where shorthand binds to a
  concrete CLI command.
- **Prefer purpose-built actions over generic `http`.** For Slack/Jira/PagerDuty/etc., prefer the connector step type
  (e.g. `slack2.sendMessage`) over a raw `http` call. Discover the exact action type via `get_step_definitions` (or the
  strict schema on the fallback path).
- **Reference step outputs as `steps.<name>.output`, never `steps.<name>.with.*`.** Trigger event data is `event`, never
  `trigger.event` or `triggers.event`.
- **Don't guess connector ids.** Call `platform.workflows.get_connectors` (Discovery-tools path) or
  `GET kbn:/api/workflows/connectors` (Schema path), or ask the user. Placeholders should be obviously fake.
- **Handle failure deliberately.** Add retry or fallback behavior where the user's requirements call for resilience. Do
  not add `continue: true` everywhere: it can hide a failed action and allow the workflow to report false success.
- **Surface gates, don't paper over them.** If the API returns `403 ... not available`, report the required license or
  privileges; do not silently retry or blame the UI setting.

## Discovery-tools path

Use when `platform.workflows.*` tools are registered on the target Kibana. All calls go through
`POST kbn:/api/agent_builder/tools/_execute` with `{ "tool_id": "...", "tool_params": { ... } }`. Response shape:
`{ "results": [ { "type": "other", "data": { ... }, "tool_result_id": "..." } ] }` — the payload you want is
`.results[0].data`. Send the request body from a file and write the response to a file (see [Operations](#operations)),
then jq against that file; do not inline `python3 -c` on multi-line JSON.

**Keep context small; minimize round-trips.** Do NOT front-load the whole step catalog — pull only the targeted details
you need, keep large tool output in files (not the transcript), and author in as few turns as possible (measured
rationale: [references/path-performance.md](references/path-performance.md)).

1. **Capture the user's intent before writing YAML.** Identify, in order, the trigger (`manual` / `scheduled` /
   `alert`), the inputs the workflow will receive at runtime, the data sources it must read, the actions it must take,
   and the desired output. If a required dependency is unknown (e.g. a Slack connector id), ask the user or use a
   clearly-marked placeholder.

2. **Look up only what you'll use.** For the specific step types this workflow needs:
   - `platform.workflows.get_step_definitions` with an exact `stepType` (e.g. `"http"`, `"elasticsearch.esql.query"`,
     `"slack2.sendMessage"`), or with `search` to browse. The response includes input params, config params, an
     `outputSummary` when you pass `includeOutputSummary: true`, and usage examples. Pass `includeFullSchema: true` only
     if the compact summary is insufficient.
   - `platform.workflows.get_trigger_definitions` for the trigger event schema.
   - `platform.workflows.get_connectors` to resolve real `connector-id` values for connector actions.
   - `platform.workflows.get_examples` when you need a working YAML shape for a pattern.

   Write each response to a file and jq the field you need — don't let full tool output land in the transcript.

3. **Draft the whole workflow in one pass.** A workflow requires `name`, at least one trigger, and a non-empty `steps`
   array. Use 2-space indentation. Reference outputs as `steps.<name>.output.*`. Build the complete YAML in a single
   edit rather than growing it across many turns.

4. **Validate once.** Call `platform.workflows.validate_workflow` with `{ "yaml": "..." }`. On failure it returns
   errors + step definitions for referenced step types automatically, so you rarely need a second `get_step_definitions`
   call. Fix all reported issues in a single edit, then re-validate.

5. **Test, save, and run.** See [Test / save / run](#test--save--run) below. Use
   `platform.workflows.workflow_execute_step` to iterate on a single step (with `confirmation_body` for unsafe steps).

## Schema path (last resort)

Only for Kibanas without the `platform.workflows.*` tools (see the probe above). Full recipe:
[references/schema-path.md](references/schema-path.md).

## Test / save / run

Shared final phase for both paths.

1. **Test only an execution-safe draft.** Call `POST kbn:/api/workflows/test` with the YAML inline as `workflowYaml` and
   the run-time `inputs`. For any workflow that writes / notifies / calls external services, replace those steps with
   `console` in the tested copy first, then restore them and save the workflow disabled.

2. **Poll the execution.** The response carries a `workflowExecutionId`. Poll
   `GET kbn:/api/workflows/executions/{executionId}` until `status` is one of `completed`, `failed`, `cancelled`, or
   `timed_out`; then fetch `GET kbn:/api/workflows/executions/{executionId}/logs` for step-by-step output. Only treat
   `status: completed` as success.

3. **Save.** `POST kbn:/api/workflows/workflow` with `{ yaml, id? }`. Save side-effecting workflows with
   `enabled: false` until the user has authorized a real run. Subsequent edits use
   `PUT kbn:/api/workflows/workflow/{id}` and may update `yaml`, `enabled`, `name`, `tags`, or `description` (partial
   updates supported).

4. **Run only when authorized.** Enable the workflow, then call `POST kbn:/api/workflows/workflow/{id}/run` with the
   same `inputs` shape used at test time. Inspect via the execution + logs endpoints.

## Workflow YAML Quick Reference

```yaml
version: "1"
name: Manual Hello Workflow
description: Logs a hello message from a manual workflow
enabled: true
tags: ["demo", "workflow"]

triggers:
  - type: manual
    inputs:
      properties:
        name:
          type: string
          description: Name to greet
          default: "world"

steps:
  - name: log_hello
    type: console
    with:
      message: "Hello {{ inputs.name }}"
```

An ordinary action step can use fields like these when its strict schema allows them:

```yaml
- name: unique_step_name
  type: step_type
  with:
    param: value
  connector-id: connector-id-for-connector-actions # connector actions only
  if: "steps.previous.output.ok: true"
  timeout: "30s"
  on-failure:
    retry:
      max-attempts: 3
      delay: "5s"
    fallback:
      - name: handle_error
        type: console
        with:
          message: "Step failed"
```

Use `{{ ... }}` when rendering text. Use `${{ ... }}` when an entire value must retain its native type, for example
`documents: "${{ steps.search.output.hits.hits }}"`.

Common step types include:

| Step type                  | Use for                            |
| -------------------------- | ---------------------------------- |
| `console`                  | Debug logging during tests         |
| `elasticsearch.search`     | Query Elasticsearch with Query DSL |
| `elasticsearch.esql.query` | Query Elasticsearch with ES\|QL    |
| `elasticsearch.bulk`       | Bulk indexing                      |
| `kibana.request`           | Call a Kibana API                  |
| `data.set`                 | Set values under `variables`       |
| `if`                       | Branch on a KQL-style condition    |
| `foreach`                  | Loop over a collection             |
| `wait`                     | Pause execution                    |
| `http`                     | Generic HTTP requests              |
| `workflow.execute`         | Run another saved workflow         |

This is not an exhaustive compatibility list. On the Discovery-tools path, `platform.workflows.get_step_definitions`
answers "does step X exist and what does it take". On the schema path, `GET kbn:/api/workflows/schema?loose=false` is
the source of truth, and `GET kbn:/api/workflows/connectors` lists configured connector instances.

`data.set` stores variables for the current execution; it does not persist durable data. Use an Elasticsearch or Kibana
write action when the user asks to retain data after the execution.

## Examples

**Manual hello (smallest possible draft):** "Make a workflow that logs hello." → manual trigger + one `console` step
that prints `Hello {{ inputs.name | default: "world" }}`. Test with `POST kbn:/api/workflows/test`. See
[Demo Test Loop](references/demo-test-loop.md).

**Scheduled health check:** "Every 5 minutes, ping `https://api.example.com/health` and log the response." → `scheduled`
trigger (`every: 5m`) + `http` step + `console`. Look up the exact `with` shape with `get_step_definitions("http")`. Add
bounded retry if requested.

**Alert-triggered case + Slack notify:** "When a Security alert fires, create a case and post to #soc-incidents." →
`alert` trigger + `foreach` over `event.alerts` + connector actions. Use `get_step_definitions("cases.createCase")` and
`get_step_definitions(search: "slack")` (current fixtures use `cases.createCase` and `slack2.sendMessage`), then
`get_connectors` for the real `connector-id`s. See [Workflow Patterns](references/workflow-patterns.md).

For unfamiliar shapes on the schema path, read [Workflow Patterns](references/workflow-patterns.md) and
[Generation Tips](references/generation-tips.md) before drafting.

## Operations

The HTTP-shorthand references in the body above bind to the `elastic` CLI commands below. Multi-line YAML and JSON
payloads are easier to pass via `--input-file <path>` than as inline flags.

**Workflows API (both paths).**

| HTTP API (shorthand)                                      | `elastic` CLI command                                                                         |
| --------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `GET /`                                                   | `elastic es info`                                                                             |
| `GET kbn:/api/workflows`                                  | `elastic stack kb workflows get-workflows`                                                    |
| `GET kbn:/api/workflows/workflow/{id}`                    | `elastic stack kb workflows get-workflows-workflow-id --id <id>`                              |
| `POST kbn:/api/workflows/workflow`                        | `elastic stack kb workflows post-workflows-workflow --input-file <path>`                      |
| `PUT kbn:/api/workflows/workflow/{id}`                    | `elastic stack kb workflows put-workflows-workflow-id --id <id> --input-file <path>`          |
| `DELETE kbn:/api/workflows/workflow/{id}`                 | `elastic stack kb workflows delete-workflows-workflow-id --id <id>`                           |
| `DELETE kbn:/api/workflows/workflow/{id}?force=true`      | `elastic stack kb workflows delete-workflows-workflow-id --id <id> --force true`              |
| `POST kbn:/api/workflows/test`                            | `elastic stack kb workflows post-workflows-test --input-file <path>`                          |
| `POST kbn:/api/workflows/workflow/{id}/run`               | `elastic stack kb workflows post-workflows-workflow-id-run --id <id> --inputs <json>`         |
| `POST kbn:/api/workflows/step/test`                       | `elastic stack kb workflows post-workflows-step-test --input-file <path>`                     |
| `GET kbn:/api/workflows/executions/{executionId}`         | `elastic stack kb workflows get-workflows-executions-executionid --execution-id <id>`         |
| `GET kbn:/api/workflows/executions/{executionId}/logs`    | `elastic stack kb workflows get-workflows-executions-executionid-logs --execution-id <id>`    |
| `POST kbn:/api/workflows/executions/{executionId}/cancel` | `elastic stack kb workflows post-workflows-executions-executionid-cancel --execution-id <id>` |
| `POST kbn:/api/workflows/executions/{executionId}/resume` | `elastic stack kb workflows post-workflows-executions-executionid-resume --execution-id <id>` |
| `GET kbn:/api/workflows/workflow/{workflowId}/executions` | `elastic stack kb workflows get-workflows-workflow-workflowid-executions --workflow-id <id>`  |
| `GET kbn:/api/workflows/schema?loose=false`               | `elastic stack kb workflows get-workflows-schema --loose false`                               |
| `GET kbn:/api/workflows/connectors`                       | `elastic stack kb workflows get-workflows-connectors`                                         |

**Agent Builder tools (Discovery-tools path).**

Every tool below is invoked through the same execute endpoint. Pass `--input-file` a JSON file with
`{ "tool_id": "...", "tool_params": { ... } }`.

| HTTP API (shorthand)                         | `elastic` CLI command                                                                 |
| -------------------------------------------- | ------------------------------------------------------------------------------------- |
| `GET kbn:/api/agent_builder/tools`           | `elastic stack kb agent-builder get-agent-builder-tools`                              |
| `POST kbn:/api/agent_builder/tools/_execute` | `elastic stack kb agent-builder post-agent-builder-tools-execute --input-file <path>` |

Workflow-relevant `tool_id`s:

| `tool_id`                                    | Purpose                                                                                        |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `platform.workflows.validate_workflow`       | Validate a YAML string; failure response includes step definitions for referenced step types.  |
| `platform.workflows.workflow_execute_step`   | Execute one step against the real environment (with user confirmation for unsafe steps).       |
| `platform.workflows.get_step_definitions`    | Look up step type params, outputs, examples. `stepType` for exact match, `search` for keyword. |
| `platform.workflows.get_trigger_definitions` | Look up a trigger's full event schema.                                                         |
| `platform.workflows.get_connectors`          | List connector instances configured on the target.                                             |
| `platform.workflows.get_examples`            | Search the bundled example library for working YAML patterns.                                  |

**Notes.**

For `post-workflows-test`, the input file is JSON of the form `{ "workflowYaml": "...", "inputs": {} }` (or `workflowId`
in place of `workflowYaml`). For `post-workflows-workflow`, use `{ "yaml": "...", "id": "..." }` — `id` is optional. For
`put-workflows-workflow-id`, include only the fields to update from `name`, `enabled`, `tags`, `yaml`, and
`description`. Deletion is soft by default. Use `force=true` only when permanent deletion and immediate ID reuse are
intended. The Kibana API version is `2023-10-31`; the CLI sets it automatically.

When invoking read-only `get-` commands from a shell that leaves stdin open (some terminals and agent runtimes do this),
append `</dev/null` to avoid an `EAGAIN: resource temporarily unavailable` crash — e.g.
`elastic stack kb workflows get-workflows-executions-executionid --execution-id "{id}" </dev/null`.
references/
demo-test-loop.md 2.9 KB
# Demo Test Loop

A minimal, side-effect-free demo of the test, save, run, inspect, and delete lifecycle. Use it to sanity-check a fresh
environment or as the canonical "hello world" when teaching the skill.

## Prompt

```text
Use the kibana-workflows skill. Create a manual workflow named "Manual Hello Workflow" that accepts
a `name` input and logs `Hello {{ inputs.name }}`. Test the draft, then save, run, and inspect the
execution.
```

## Expected YAML Draft

```yaml
version: "1"
name: Manual Hello Workflow
description: Logs a greeting from a manual workflow
enabled: true
tags: ["demo", "workflow"]

triggers:
  - type: manual
    inputs:
      properties:
        name:
          type: string
          description: Name to greet
          default: "world"

steps:
  - name: log_hello
    type: console
    with:
      message: "Hello {{ inputs.name }}"
```

## 1. Test The Draft

Write the YAML to `workflow.yaml`, then build a JSON input file for `POST kbn:/api/workflows/test`:

```json
{
  "workflowYaml": "version: '1'\nname: Manual Hello Workflow\nenabled: true\ntriggers:\n  - type: manual\n    inputs:\n      properties:\n        name:\n          type: string\n          default: world\nsteps:\n  - name: log_hello\n    type: console\n    with:\n      message: \"Hello {{ inputs.name }}\"\n",
  "inputs": { "name": "world" }
}
```

Save as `/tmp/workflow-test.json`. The response includes `workflowExecutionId`.

Use the [Operations](../SKILL.md#operations) table to map each HTTP shorthand below to the corresponding `elastic` CLI
command.

## 2. Wait For The Execution

Poll `GET kbn:/api/workflows/executions/{executionId}` until `status` is one of `completed`, `failed`, `cancelled`, or
`timed_out`. If it never reaches a terminal state within a minute, something is wrong with the workflow or the host.

## 3. Inspect Logs

Call `GET kbn:/api/workflows/executions/{executionId}/logs` and confirm the `console` step printed `Hello world` (or
`Hello <inputs.name>` if a different value was passed).

## 4. Save And Run

Once the draft tests green, save it with `POST kbn:/api/workflows/workflow` using
`{ "yaml": "...", "id": "manual-hello-workflow" }`, then call `POST kbn:/api/workflows/workflow/{id}/run` with the same
inputs.

## 5. Clean Up

Permanently delete the disposable demo with `DELETE kbn:/api/workflows/workflow/{id}?force=true` so its explicit ID can
be reused. Omit `force=true` when normal recoverable deletion is preferable.

## Success Criteria

- The skill loads in the host agent (Claude Code, Cursor, Codex, agent-builder).
- The generated YAML uses explicit `version: '1'`, a manual trigger with `inputs.properties`, and a `console` step.
- `POST kbn:/api/workflows/test` returns a `workflowExecutionId` and the execution reaches `status=completed`.
- The execution logs include `Hello world` (or the alternate input value).
- The full lifecycle — test → save → run → execution → logs → delete — completes without errors.
generation-tips.md 5.0 KB
# Workflow Generation Tips

Guidelines for translating natural language into valid Elastic Workflow YAML.

## Generation Process

1. **Classify the trigger.**
   - "Run this now", "on demand", "manual" -> `manual`
   - "Every hour", "daily", "periodically" -> `scheduled`
   - "When an alert fires", "from a detection rule" -> `alert`

2. **Identify inputs and constants.**
   - Values users provide at run time belong in `inputs` on a `manual` trigger.
   - Fixed values such as index patterns, thresholds, or connector names belong in `consts`.

3. **Choose the smallest step sequence.**
   - Start with `console` for simple demos.
   - Use `elasticsearch.search` or `elasticsearch.esql.query` for data lookup.
   - Use `data.set` before conditions when a computed value is needed.
   - Use connector steps for external systems.

4. **Write YAML with explicit data flow.**
   - Give each step a stable snake_case `name`.
   - Reference prior step outputs through `steps.<name>.output`; reference `data.set` values through `variables.<key>`.
   - Use `foreach.item` only inside `foreach` child steps.

5. **Test safely.**
   - Remember that `POST kbn:/api/workflows/test` executes the graph rather than only validating YAML.
   - Test the complete draft only when it is read-only or its side effects are authorized.
   - Otherwise test a console-stubbed copy, then restore the action steps and save the workflow disabled.

## Critical Syntax Rules

### State The Workflow Version

The schema defaults the optional version to `1`; include it explicitly for readable, portable drafts:

```yaml
version: "1"
```

### Use `event`, Not `triggers.event`

The `triggers` block configures activation. Runtime data is available as `event`.

```yaml
# WRONG
message: "{{ triggers.event.rule.name }}"

# CORRECT
message: "{{ event.rule.name }}"
```

### Step Outputs Use `.output`

```yaml
# WRONG
message: "{{ steps.search.with.query }}"

# CORRECT
message: "{{ steps.search.output.hits.total.value }}"
```

### Use A Supported Condition Form

Conditions accept KQL-style strings. Dynamic expression form `${{ ... }}` is also used for comparisons and native
values. Do not interpolate a rendered `{{ ... }}` string and then append an operator.

```yaml
# WRONG
- name: check
  type: if
  condition: "{{ steps.search.output.hits | size }} > 0"

# BETTER
- name: set_count
  type: data.set
  with:
    count: "${{ steps.search.output.hits.hits | size }}"
- name: check
  type: if
  condition: "${{ variables.count > 0 }}"
```

### Connector Steps Need `connector-id`

```yaml
- name: notify
  type: slack2.sendMessage
  connector-id: my-slack-connector
  with:
    channel: C0123456789
    text: "Done"
```

This is an example from current Kibana eval fixtures, not a universal connector contract. Get the exact action type and
its `with` fields from `GET kbn:/api/workflows/schema?loose=false`, and get instance IDs from
`GET kbn:/api/workflows/connectors`. If the connector ID is unknown, ask or use a clearly marked placeholder.

### Step Config Does Not Always Belong In `with`

For `if` and `foreach`, child steps and control fields are step-level config:

```yaml
- name: for_each_alert
  type: foreach
  foreach: "${{ event.alerts }}"
  steps:
    - name: log_alert
      type: console
      with:
        message: "{{ foreach.item._id }}"
```

## Validation Strategy

Prefer this loop:

1. Generate YAML and write it to `workflow.yaml`.
2. Run a draft test against `POST kbn:/api/workflows/test` only when the graph is safe to execute; otherwise test a
   console-stubbed copy.
3. If validation fails, address every reported issue before retrying.
4. If runtime fails, inspect the execution at `GET kbn:/api/workflows/executions/{executionId}` and its logs at
   `GET kbn:/api/workflows/executions/{executionId}/logs`, then fix the step that failed in isolation.

## Repair Heuristics

| Error shape                           | Likely fix                                                       |
| ------------------------------------- | ---------------------------------------------------------------- |
| Unknown step type                     | Inspect the target's strict schema; do not guess a replacement   |
| Missing required property             | Move the field into `with` or add required step config           |
| Liquid variable resolves empty        | Check `steps.<name>.output` path or `event` availability         |
| Manual run has no alert data          | Add inputs or guard alert-only branches                          |
| Connector step fails before execution | Add or correct `connector-id`                                    |
| Query step returns no useful data     | Loosen filters, validate index/field names, or use sample output |

## Safe Defaults

- Use `manual` trigger for the first draft.
- Use `console` output in demos before adding side effects.
- Prefer read-only Elasticsearch queries before writes.
- Keep unexecuted side-effecting workflows disabled until the user approves enabling them.
- Ask before creating workflows that send notifications, write documents, or call external services.
generator-path.md 5.5 KB
# Generator path (optional, fastest-to-author / cheapest)

> Preserved reference. Not the default path — see [SKILL.md](../SKILL.md) for the shipped Discovery-tools path and the
> measured [path benchmark](../SKILL.md#path-performance-measured). This path drives Kibana's own
> `platform.core.generate_workflow` by proxying through an Agent Builder `converse` turn. It needs an LLM connector
> wired into Agent Builder. It is the **cheapest** measured path (most generation happens inside Kibana, not in the
> 3rd-party agent's billed context) and becomes the outright best once `generate_workflow` is exposed as a standalone
> API/CLI — tracked in [security-team#18614](https://github.com/elastic/security-team/issues/18614).

## Generator path

Direct `POST /api/agent_builder/tools/_execute` on `platform.core.generate_workflow` returns only an `attachment_id`
that lives on a conversation which doesn't exist outside of Agent Builder — the raw YAML can't be retrieved. The
practical way to reach the generator from a 3rd-party agent is to **proxy the request through an Agent Builder converse
turn**, then fetch the emitted workflow attachment from that conversation. One converse turn inside Kibana runs the AB
workflow-authoring skill end-to-end (typically <10s, ~4 LLM calls) and produces raw YAML you can then save, test, and
run through the plain workflows API.

Upstream tracking issue: [security-team#18614](https://github.com/elastic/security-team/issues/18614) asks for a
standalone endpoint that returns the YAML inline; until it lands, use the recipe below.

1. **Capture the user's intent as a natural-language brief.** Include: trigger (manual / scheduled / alert), the inputs
   the workflow receives at runtime, data sources to read, actions to take, and the desired output. If a required
   dependency is unknown (e.g. a Slack connector id), say so in the brief — the generator will slot in a placeholder or
   use a configured connector.

2. **Send the brief through Agent Builder converse, asking for inline YAML.** Build a JSON payload:

   ````json
   {
     "input": "<brief>. Return the full YAML in a fenced ```yaml code block in your reply, and do not save the workflow."
   }
   ````

   The trailing "return the full YAML in a fenced `yaml` block" instruction is load-bearing — without it, the AB agent
   only emits a `<render_attachment id="..."/>` placeholder and you need a second API call to fetch the body. With the
   instruction, the agent internally calls `attachments.read` on its own generated attachment and inlines the YAML in
   `.response.message`.

   Call `POST kbn:/api/agent_builder/converse` with the payload. Write the response to a file (do **not** pipe through
   inline `python3 -c` — multi-line JSON breaks trivially on shell quoting). Capture:
   - `conversation_id` — for cleanup in step 4.
   - `.response.message` — the assistant text containing the YAML in a fenced block.

   Do **not** pre-fetch step definitions, connectors, or the schema — the AB skill already has that knowledge built in.

3. **Extract the YAML.** Read the fenced `yaml` block from `.response.message` and save the raw YAML to a local file for
   the next steps. If the block is missing (rare), fall back to
   `GET kbn:/api/agent_builder/conversations/{conversation_id}/attachments` and read the `workflow.yaml` entry's
   `.versions[-1].data.yaml`.

4. **Clean up the throwaway conversation** with `DELETE kbn:/api/agent_builder/conversations/{conversation_id}` so it
   doesn't clutter the user's history.

5. **Validate before executing.** Call `platform.workflows.validate_workflow` via `/tools/_execute` with
   `{ "yaml": "..." }`. On failure it returns the errors _plus_ the step definitions for every referenced step type, so
   a second `get_step_definitions` call is usually unnecessary. Fix each error, then re-validate. If the AB generator
   produced invalid YAML, prefer sending a follow-up converse turn (`conversation_id: <the previous cid>`,
   `input: "the YAML failed validation with: ...  please fix"`) over hand-editing — the generator can re-emit a
   corrected attachment.

6. **Test only an execution-safe draft.** Use the standard workflow test path (`POST kbn:/api/workflows/test`) — Agent
   Builder does not replace this. For read-only or explicitly authorized workflows, test as-is. Otherwise, ask the AB
   generator to produce a "console-only" copy first (converse: "convert this workflow to replace every side-effecting
   step with a console log describing what it would do").

   For iterating on a single step in isolation, use `platform.workflows.workflow_execute_step`. Safe steps (read-only
   ES, `data.*`, `console`, `if`) run immediately. Unsafe steps (HTTP, ES writes, connectors, AI) require user
   confirmation via a `confirmation_body` param — always populate it with a Markdown preview describing resolved inputs,
   the side effect, and whether it's reversible.

7. **Save and run** via the plain workflows API: `POST kbn:/api/workflows/workflow` (leave `enabled: false` when the
   workflow has un-tested side effects), then `POST kbn:/api/workflows/workflow/{id}/run` when the user authorizes.

8. **Use discovery tools only for questions.** `get_step_definitions`, `get_trigger_definitions`, `get_examples`, and
   `get_connectors` are for answering the user's questions ("what does the http step output?", "which Slack connectors
   are configured?"), for debugging a validation error the generator couldn't fix, or for surfacing a legacy step type
   (`includeDeprecated: true`). They are not preparation for the generator turn.
path-performance.md 1.8 KB
# Path performance (measured)

Same task (hourly security-posture snapshot: 3× http, ES|QL, foreach+bulk, Slack), same local Kibana 9.6, sonnet.
Numbers are wall-clock / turns / USD cost for a 3rd-party agent (Claude Code):

| Path                                                | Wall     | Turns | Cost      | Why                                               |
| --------------------------------------------------- | -------- | ----- | --------- | ------------------------------------------------- |
| Discovery-tools (default)                           | **206s** | 25    | $0.57     | targeted `get_*` lookups, output kept in files    |
| Generator via converse ([ref](generator-path.md))   | 288s     | 17    | **$0.46** | LLM work runs in Kibana; ~2× 75s converse blocks  |
| Schema ([ref](schema-path.md))                      | 942s     | 50    | $1.63     | grinds the ~2 MB schema; 2.6M cache-read replayed |
| _(reference: Agent Builder in-process, 1 converse)_ | _131s_   | —     | —         | _in-process floor; not a 3rd-party path_          |

## Why not front-load the catalog?

Do **not** pull the full step/trigger catalog into context upfront to imitate the in-process generator — measured at
274s / $0.71, worse than targeted lookups. A context-replay harness re-sends everything every turn, so a big upfront
dump is paid dozens of times over. The generator can front-load because it runs in-process; a 3rd-party agent cannot.
Minimize round-trips and keep large tool output in files instead.

## Closing the gap to Agent Builder

The AB→3rd-party gap is harness tax (full-context replay per turn). Closing it fully requires the standalone
`generate_workflow` API — [security-team#18614](https://github.com/elastic/security-team/issues/18614); the
discovery-tools-as-APIs discussion is [security-team#18615](https://github.com/elastic/security-team/issues/18615).
schema-path.md 2.1 KB
# Schema path (last resort)

Hand-author workflow YAML from the raw JSON Schema. Use **only** when the `platform.workflows.*` discovery tools are not
registered on the target Kibana — in practice Kibana 9.4 or a deployment without Agent Builder; from 9.5 and on
Serverless the tools are registered and visible by default.

Measured cost of this path on a representative task: **942s wall / 50 turns / $1.63** vs 206s / 25 / $0.57 on the
Discovery-tools path — the ~2 MB schema keeps bleeding into context. Treat it as a compatibility fallback, never a
preference. See [path-performance.md](path-performance.md) for the full benchmark.

## Process

1. **Capture the user's intent before writing YAML.** Identify, in order, the trigger (`manual` / `scheduled` /
   `alert`), the runtime inputs, the data sources to read, the actions to take, and the desired output. If a required
   dependency is unknown (e.g. a Slack connector id), ask the user or use a clearly-marked placeholder.

2. **Discover the current schema.** Call `GET kbn:/api/workflows/schema?loose=false` — the strict, space-aware JSON
   Schema for every step type on the target Kibana. It is large (~2 MB); save it to a file and grep for the exact `type`
   consts you need rather than dumping it into context. Get connector instance ids from
   `GET kbn:/api/workflows/connectors`.

3. **Draft YAML that follows the discovered schema.** A workflow requires `name`, at least one trigger, and a non-empty
   `steps` array. `version: '1'` is optional and defaults to `1`. Use 2-space indentation. Fields outside `with` depend
   on the step type.

   Load references progressively:
   - [Workflow YAML Reference](workflow-yaml-reference.md) for root structure, triggers, templating, control flow.
   - [Generation Tips](generation-tips.md) when repairing or validating a draft.
   - [Workflow Patterns](workflow-patterns.md) when mapping a complex request to a workflow shape.
   - [Demo Test Loop](demo-test-loop.md) only for the safe hello-world lifecycle.

4. **Test, save, and run** per the Test / save / run section in [SKILL.md](../SKILL.md).
workflow-patterns.md 3.8 KB
# Workflow Patterns

Common natural-language requests and the workflow shapes they imply.

## Manual Demo Workflow

User says:

- "Create a simple workflow"
- "Make a workflow that logs hello"
- "Show me the fastest end-to-end workflow"

Use:

```yaml
version: "1"
name: Manual Hello Workflow
enabled: true
triggers:
  - type: manual
steps:
  - name: log_hello
    type: console
    with:
      message: "Hello from workflow"
```

This is the best first smoke test because it has no external dependencies.

## Scheduled Report

User says:

- "Every hour, check..."
- "Run daily and summarize..."
- "Generate a periodic report..."

Use:

```yaml
version: "1"
name: Scheduled Health Report
enabled: true
triggers:
  - type: scheduled
    with:
      every: "1h"
steps:
  - name: query_data
    type: elasticsearch.esql.query
    with:
      query: "FROM logs-* | WHERE @timestamp > NOW() - 1 hour | STATS count = COUNT(*)"
  - name: log_summary
    type: console
    with:
      message: "Query result: {{ steps.query_data.output | json }}"
```

Validate index names and field names before relying on this in a real environment.

## Alert Triage

User says:

- "When a critical alert fires..."
- "For each alert, enrich it..."
- "Create a case from alerts..."

Use an alert trigger and `event.alerts`:

```yaml
version: "1"
name: Alert Triage Workflow
enabled: true
triggers:
  - type: alert
steps:
  - name: log_alerts
    type: console
    with:
      message: "Received {{ event.alerts | size }} alerts from {{ event.rule.name }}"
  - name: process_alerts
    type: foreach
    foreach: "${{ event.alerts }}"
    steps:
      - name: log_alert
        type: console
        with:
          message: "Alert {{ foreach.item._id }} in {{ foreach.item._index }}"
```

If the same workflow must also run manually, add inputs or guard alert-only branches because manual runs do not have
`event.alerts`.

## Connector Notification

User says:

- "Send to Slack"
- "Create a Jira ticket"
- "Email the summary"

Use a connector step and require a connector ID:

```yaml
version: "1"
name: Notify Slack Workflow
enabled: true
triggers:
  - type: manual
steps:
  - name: send_slack
    type: slack2.sendMessage
    connector-id: my-slack-connector
    with:
      channel: C0123456789
      text: "Workflow completed"
```

This action shape comes from current Kibana eval fixtures. Confirm the exact type and fields with the target's strict
workflow schema. If the connector ID is unknown, do not invent a real one. Ask or use a placeholder in a disabled draft.

## Query Then Branch

User says:

- "If there are any errors..."
- "Only notify when count is greater than..."
- "Create a case when the query returns results..."

Use a query, compute a simple value, then branch:

```yaml
version: "1"
name: Query Then Branch
enabled: true
triggers:
  - type: manual
steps:
  - name: find_errors
    type: elasticsearch.esql.query
    with:
      query: 'FROM logs-* | WHERE @timestamp > NOW() - 1 hour | WHERE log.level == "error" | STATS errors = COUNT(*)'
  - name: set_error_count
    type: data.set
    with:
      count: "${{ steps.find_errors.output.values[0][0] | default: 0 }}"
  - name: has_errors
    type: if
    condition: "${{ variables.count > 0 }}"
    steps:
      - name: log_errors
        type: console
        with:
          message: "Errors found: {{ variables.count }}"
    else:
      - name: log_clean
        type: console
        with:
          message: "No errors found"
```

Output shape for query steps can vary by step implementation. Test-run before depending on an exact path.

## Local Test Cycle

For any pattern, first prove a safe version:

1. Replace side-effecting connector or HTTP steps with `console` steps.
2. Call `POST kbn:/api/workflows/test` with the safe copy.
3. Inspect output/logs.
4. Restore the side-effecting step once the control flow is correct.
workflow-yaml-reference.md 11.1 KB
# Workflow YAML Reference

Elastic Workflows are YAML documents executed by Kibana. They have metadata, triggers, optional constants and outputs,
and an ordered `steps` array. Manual inputs belong on the manual trigger.

## Root Structure

```yaml
version: "1"
name: Workflow Name
description: What this workflow does
enabled: true
tags: ["tag1", "tag2"]

consts:
  index: "logs-*"

triggers:
  - type: manual
    inputs:
      properties:
        severity:
          type: string
          description: Alert severity to process
          default: "critical"

steps:
  - name: first_step
    type: console
    with:
      message: "Workflow started"
```

## Triggers

### Manual

Use manual triggers for demos, testing, and user-initiated runs.

```yaml
triggers:
  - type: manual
    inputs:
      properties:
        severities:
          type: array
          items:
            type: string
          default: ["low", "high"]
```

Manual input definitions use JSON Schema. Arrays need an `items` schema; objects should declare their `properties`.

Manual runs do not have alert event context. If a workflow can run manually and from alerts, guard alert-only branches.

### Scheduled — interval

Use scheduled triggers for recurring checks or reports.

```yaml
triggers:
  - type: scheduled
    with:
      every: "1h" # units: s, m, h, d (minimum 1 minute)
```

### Scheduled — RRule

For calendar-aligned schedules (specific weekdays, month days, hours), use an RRule instead of `every`.

```yaml
triggers:
  - type: scheduled
    with:
      rrule:
        freq: DAILY # DAILY | WEEKLY | MONTHLY
        interval: 1
        tzid: UTC
        dtstart: "2026-01-01T09:00:00Z"
        byhour: [9, 17]
        byminute: [0]
        byweekday: [MO, TU, WE, TH, FR]
        bymonthday: [1, 15]
```

### Alert

Use alert triggers when a Kibana rule or Security detection should dispatch to the workflow.

```yaml
triggers:
  - type: alert
```

Alert runtime data is available under `event`:

- `{{ event.alerts }}` — array of alert documents
- `{{ event.alerts[0]._id }}` — alert ID
- `{{ event.alerts[0]._index }}` — alert index
- `{{ event.alerts[0]["@timestamp"] }}` — alert timestamp
- `{{ event.rule.name }}` — rule name
- `{{ event.spaceId }}` — Kibana space

For Security detection rule alerts, `event.alerts[0]` carries the alert document. Document fields depend on the rule and
solution; verify them against a representative alert. Common Security alert fields include:

```yaml
event.alerts[0]._id # alert document _id
event.alerts[0].kibana.alert.rule.name # detection rule name on a Security alert
event.alerts[0].host.name # affected host
event.alerts[0].host.ip # host IP(s)
event.alerts[0].user.name # affected user
event.alerts[0].kibana.alert.severity # alert severity
event.alerts[0].elastic.agent.id # Elastic Agent ID
event.alerts[0].process.name # process that triggered the alert
```

Never use `triggers.event`, `trigger.event`, or `triggers.event.*`.

#### Dual-trigger pattern (manual + alert)

When a workflow has both `manual` and `alert` triggers, alert event context is unavailable for manual runs. Keep alert
references out of the manual path; do not rely on a compound condition to make an unsafe event dereference harmless.

Split into two guarded branches: use `condition: "event: *"` for the alert path, and `condition: "inputs.<field>: *"`
for the manual path. Never mix `event` references into the manual path or vice versa.

```yaml
triggers:
  - type: manual
    inputs:
      properties:
        target_hash:
          type: string
  - type: alert

steps:
  - name: alert_path
    type: if
    condition: "event: *"
    steps:
      - name: process_alert
        type: console
        with:
          message: "Alert: {{ event.alerts[0].kibana.alert.rule.name }}"

  - name: manual_path
    type: if
    condition: "inputs.target_hash: *"
    steps:
      - name: process_manual
        type: console
        with:
          message: "Manual run for {{ inputs.target_hash }}"
```

## Inputs And Constants

Use `consts` for fixed workflow configuration. Declare runtime inputs on a manual trigger.

```yaml
consts:
  target_index: "logs-*"

triggers:
  - type: manual
    inputs:
      properties:
        service_name:
          type: string
          description: Service to inspect
```

Reference them with Liquid:

```yaml
with:
  message: "Checking {{ inputs.service_name }} in {{ consts.target_index }}"
```

`data.set` creates per-execution values under `variables`; it is not durable storage.

## Step Fields

Every step has:

- `name`: unique within the workflow
- `type`: step type ID or connector type
- `with`: input parameters when the selected step type defines them

Common optional fields, when the selected step's strict schema allows them:

- `connector-id`: connector instance ID for connector steps
- `if`: skip this step unless the expression is truthy
- `timeout`: step timeout
- `on-failure`: retry, fallback, and continuation behavior

Step config fields outside `with` depend on the step type:

- `if` step: `condition`, `steps`, `else`
- `foreach` step: `foreach`, `steps`

## Common Step Types

| Step type                  | Description                                |
| -------------------------- | ------------------------------------------ |
| `console`                  | Log a message for debugging or demo output |
| `elasticsearch.search`     | Execute Elasticsearch Query DSL            |
| `elasticsearch.esql.query` | Execute ES\|QL                             |
| `elasticsearch.bulk`       | Bulk index documents                       |
| `data.set`                 | Store values in workflow context           |
| `if`                       | Branch by KQL condition                    |
| `foreach`                  | Iterate over a collection                  |
| `while`                    | Repeat a body with do-while semantics      |
| `switch`                   | Select one of several branches             |
| `parallel`                 | Run branches concurrently                  |
| `wait`                     | Pause execution                            |
| `workflow.execute`         | Run another saved workflow                 |

`console`, `http`, `elasticsearch.*`, `kibana.*`, connector actions, and extension actions are also available when
registered on the target. Treat `GET kbn:/api/workflows/schema?loose=false` as the source of truth rather than this
summary.

## Connector Steps

Connector steps use the connector type as the step type and require a connector instance ID.

```yaml
- name: send_slack
  type: slack2.sendMessage
  connector-id: my-slack-connector
  with:
    channel: C0123456789
    text: "Workflow completed"
```

The example action ID and fields are verified by current Kibana eval fixtures, but connector definitions evolve. Query
the strict schema for the exact action ID and `with` shape, and query the connectors endpoint for a real instance ID.
Use generic `http` only when no purpose-built action exists or the user requests a custom HTTP API call.

## Liquid Templating

Use `{{ ... }}` to render text. Use `${{ ... }}` when the whole scalar is an expression and its native type (array,
object, number, boolean, or string) must be preserved:

```yaml
{{ inputs.input_name }}
{{ consts.constant_name }}
{{ steps.step_name.output.field }}
{{ foreach.item }}
{{ event }}
${{ steps.search.output.hits.hits }}
```

Common filters:

| Filter                                    | Example                                                 |
| ----------------------------------------- | ------------------------------------------------------- |
| `json`                                    | `{{ object \| json }}` — convert to JSON string         |
| `json:2`                                  | `{{ object \| json:2 }}` — pretty-printed JSON          |
| `json_parse`                              | `{{ string \| json_parse }}` — parse JSON to object     |
| `size`                                    | `{{ array \| size }}` — array length                    |
| `first` / `last`                          | `{{ items \| first }}`                                  |
| `map`                                     | `{{ users \| map: "name" }}`                            |
| `where`                                   | `{{ items \| where: "status", "active" }}`              |
| `where_exp`                               | `{{ items \| where_exp: "item", "item.price > 100" }}`  |
| `join`                                    | `{{ tags \| join: ", " }}`                              |
| `split`                                   | `{{ csv \| split: "," }}`                               |
| `default`                                 | `{{ name \| default: "Unknown" }}`                      |
| `upcase` / `downcase`                     | `{{ text \| upcase }}`                                  |
| `date`                                    | `{{ "now" \| date: "%Y-%m-%d" }}`                       |
| `base64_encode` / `base64_decode`         | `{{ text \| base64_encode }}`                           |
| `url_encode` / `url_decode`               | `{{ query \| url_encode }}`                             |
| `plus` / `minus` / `times` / `divided_by` | `{{ count \| plus: 1 }}`                                |
| `sort`                                    | `{{ items \| sort: "name" }}`                           |
| `entries`                                 | `{{ object \| entries }}` — emit `{ key, value }` pairs |
| `pick`                                    | `{{ object \| pick: "a", "b.c" }}` — retain fields      |

Only step outputs are addressable through `steps.<name>.output`. Step input parameters are not addressable through
`steps.<name>.with.*`. A `data.set` step also merges its key-value output into `variables`; later steps can use
`{{ variables.key }}` or `${{ variables.key }}`.

## Error Handling

Use `on-failure` for retries and fallback steps. Processing order is retry → fallback → continue.

### Step-level

```yaml
- name: call_service
  type: http
  with:
    method: GET
    url: "https://example.com/status"
  on-failure:
    retry:
      max-attempts: 3
      delay: "10s"
    fallback:
      - name: log_failure
        type: console
        with:
          message: "HTTP call failed"
```

### Workflow-level default

Set a workflow-wide `on-failure` block under `settings` to apply the same defaults to every step. Step-level
`on-failure` overrides the workflow default.

```yaml
settings:
  on-failure:
    retry:
      max-attempts: 2
      delay: "1s"
```

## Lifecycle

The fast loop, using the operations from [SKILL.md](../SKILL.md#operations):

1. Write YAML to a file.
2. If every step is read-only or authorized, `POST kbn:/api/workflows/test` with `{ workflowYaml, inputs }`. Otherwise
   test a console-stubbed copy because this endpoint executes the graph.
3. Fix validation or runtime errors surfaced by the execution and logs endpoints.
4. Restore action steps and `POST kbn:/api/workflows/workflow` with `{ yaml, id? }`; keep it disabled if the restored
   side effects have not been executed and approved.
5. Enable and `POST kbn:/api/workflows/workflow/{id}/run` with `{ inputs }` only when authorized.
6. Poll `GET kbn:/api/workflows/executions/{executionId}` and pull
   `GET kbn:/api/workflows/executions/{executionId}/logs` for step output.

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/elastic/agent-skills/blob/main/LICENSE