Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

feat: add n8n workflow automation harness (v2.4.5)

Juan Jose Sanchez Bernalcf8c5a6150fc
diff --git a/.gitignore b/.gitignore
index d44f3d223..475c26c44 100644
--- a/.gitignore
+++ b/.gitignore
@@ -226,3 +226,5 @@ assets/gen_typing_gif.py
!/intelwatch/agent-harness/
!/intelwatch/
!/exa/
+!/n8n/
+!/n8n/agent-harness/
diff --git a/README.md b/README.md
index 1a54e30c1..58983cf24 100644
--- a/README.md
+++ b/README.md
@@ -785,6 +785,13 @@ Each application received complete, production-ready CLI interfaces — not demo
<td align="center">✅ 158</td>
</tr>
<tr>
+<td align="center"><strong>⚡ <a href="n8n/agent-harness/">n8n</a></strong></td>
+<td>Workflow Automation</td>
+<td><code>cli-anything-n8n</code></td>
+<td>n8n REST API v1.1.1</td>
+<td align="center">✅ <a href="n8n/agent-harness/">55+ cmds</a></td>
+</tr>
+<tr>
<td align="center"><strong>📚 <a href="zotero/agent-harness/">Zotero</a></strong></td>
<td>Reference Management</td>
<td><code>cli-anything-zotero</code></td>
diff --git a/n8n/agent-harness/CHANGELOG.md b/n8n/agent-harness/CHANGELOG.md
new file mode 100644
index 000000000..176fc7745
--- /dev/null
+++ b/n8n/agent-harness/CHANGELOG.md
@@ -0,0 +1,205 @@
+# Changelog
+
+## [2.2.0] - 2026-04-02
+
+### Hardening (review round 6)
+- **Defensive dict access**: Replaced ALL `dict['key']` with `dict.get('key', default)` in display code for external API data (templates, npm nodes, bulk operations). Prevents KeyError crashes from malformed API responses.
+- 15+ unsafe dict accesses fixed across template search, node search, node info, bulk activate/deactivate, and scaffold display
+
+## [2.1.9] - 2026-04-02
+
+### Fixes (manual review + round 6)
+- **API key in config show**: No longer shows partial key preview — just "configured" or empty
+- Consistent with health --diagnostic which already used this approach
+
+## [2.1.8] - 2026-04-02
+
+### Fixes (adversarial security bounty — round 5)
+- **REPL quoted args**: REPL now uses `shlex.split()` — handles `'{"name": "my workflow"}'` correctly
+- **Error message leaking**: Server error responses no longer leak raw text (only JSON "message" field, truncated to 200 chars)
+
+## [2.1.7] - 2026-04-02
+
+### Critical Fixes (adversarial bug bounty — round 5)
+- **Silent data corruption in autofix**: Connection key fix ("0"->"main") now MERGES instead of overwriting existing "main" connections
+- **Rollback could reactivate workflows**: `versions rollback` now strips `active` field — use `activate` command explicitly
+- **Scaffold pattern mutation**: `get_scaffold()` now returns deep copy — calling code can't corrupt templates
+- **Lying test fixed**: `test_export_import_roundtrip` now uses real `_clean_for_api()` instead of reimplementing the logic
+
+## [2.1.6] - 2026-04-02
+
+### Bug Fixes (review round 4)
+- **IndexError in `patch --connect`**: Fixed crash when node's "main" connection list exists but is empty
+- **AttributeError in `patch --remove-node/--disconnect`**: Connection list items can be None/malformed — now filtered safely
+- **JSONDecodeError in config load**: Corrupted `config.json` no longer crashes the entire CLI — falls back to defaults
+
+## [2.1.5] - 2026-04-02
+
+### Critical Bug Fixes (review round 3 — code agent)
+- **Data corruption in autofix**: `_set_nested()` now correctly handles bracket notation (`assignments[0].value`) — previously created corrupt keys like `"assignments[0]"` instead of updating list items
+- **Crash on malformed workflows**: `autofix()` no longer crashes when `nodes` or `connections` are `None` — handles gracefully
+- Hardened all node/connection iteration with type checks
+- Added regression tests for both bugs
+
+## [2.1.4] - 2026-04-01
+
+### Security Fixes (review round 3)
+- **Prevent accidental workflow activation**: `create`, `update`, `import`, `restore-all`, `template deploy` now explicitly force `active=False`. Use `activate` command to enable.
+- **npm registry data validation**: Truncate and validate all fields from untrusted npm responses
+- **template deploy**: Force `active=False` on deployed templates
+
+## [2.1.3] - 2026-04-01
+
+### Security Fixes (review round 2 — security agent)
+- **Path traversal**: 3 additional file reads in diff/validate/autofix now use centralized `_load_json_arg()` with `Path.resolve()`
+- **Webhook URL sanitization**: Strip special chars from webhook path to prevent URL manipulation
+- **Error message leaking**: Removed raw server response from error output
+
+## [2.1.2] - 2026-04-01
+
+### Fixes (from review round 2)
+- **SQLite race condition**: Added WAL journal mode + 10s timeout for concurrent access
+- **Filename encoding**: Safe filename sanitization for workflows with unicode/special chars
+- **Watch busy-loop**: Reject `--interval 0` to prevent CPU burn
+- **Duplicate dict key**: Removed duplicate `api_key_set` in health diagnostic
+- **Versions diff same**: Warn when comparing version with itself
+- Added `_safe_filename()` helper for cross-platform filename safety
+
+## [2.1.1] - 2026-04-01
+
+### Security Fixes (from 3-agent code review)
+- **Path traversal prevention**: `_load_json_arg()` now resolves paths before opening
+- **API key no longer exposed**: `health --diagnostic` shows only "configured/NOT SET"
+- **File permissions**: config.json (0600) and versions.db directory (0700) are now restricted
+- **Specific exceptions**: Replaced bare `except Exception: pass` with targeted exception types
+
+### Code Quality Fixes
+- Extracted `_clean_for_api()` helper — eliminated 7 duplicated filter expressions
+- Added `_INTERNAL_FIELDS` constant for workflow metadata fields
+- Fixed `versions_diff` missing `@click.pass_context` decorator
+- Fixed `_iter_params` to detect expressions inside lists (not just dicts)
+- Reviewed by: code-reviewer, security-reviewer, python-reviewer agents
+
+## [2.1.0] - 2026-04-01
+
+### Added
+- `node search <query>` — search 26,000+ n8n community node packages on npm
+- `node info <package>` — get package details, nodes provided, install command
+- New module: `core/nodes.py`
+
+## [2.0.0] - 2026-04-01
+
+### Added
+- `workflow scaffold <pattern>` — generate workflows from 5 proven patterns (webhook, api, database, ai-agent, scheduled)
+- `workflow patterns` — list available scaffold patterns
+- `expression <expr>` — validate n8n expression syntax offline
+- New modules: `core/scaffolds.py`, `core/expressions.py`
+
+### Changed
+- Version bump to 2.0.0 — the CLI is now feature-complete for the n8n Public API
+- 10 core modules, 60+ commands, 80+ tests
+
+## [1.7.0] - 2026-04-01
+
+### Added
+- `workflow versions list/show/rollback/diff/prune/stats` — full version tracking with local SQLite
+- Auto-snapshot before every write operation (update, patch, autofix --apply)
+- Rollback to any previous version with automatic pre-rollback backup
+- Version diff between any two stored snapshots
+- Storage stats and pruning for disk management
+
+## [1.6.0] - 2026-04-01
+
+### Added
+- `workflow autofix` — detect and repair 6 types of common issues (expression format, webhook paths, broken connections, duplicate names, numeric connection keys, unused error outputs). Preview mode by default.
+- `workflow patch` — incremental updates: `--rename`, `--enable-node`, `--disable-node`, `--remove-node`, `--connect`, `--disconnect`. No need to send the full workflow JSON.
+- `health` — full health check with response time, connectivity test, and `--diagnostic` mode
+- New module `core/fixers.py` with pluggable fix engine
+
+### Inspired by
+- `WorkflowAutoFixer` and `WorkflowDiffEngine` from [n8n-mcp](https://github.com/czlonkowski/n8n-mcp)
+
+## [1.5.0] - 2026-04-01
+
+### Added
+- `template search <query>` — search 2,700+ templates on n8n.io
+- `template get <id>` — view template details
+- `template deploy <id>` — deploy template directly to your n8n instance
+- `workflow validate <id|@file>` — validate workflow structure (nodes, connections, triggers, duplicates)
+- `workflow test <id>` — trigger webhook-based workflows with test data
+
+### Inspired by
+- Features from [n8n-mcp](https://github.com/czlonkowski/n8n-mcp) adapted for CLI usage
+
+## [1.4.0] - 2026-04-01
+
+### Added
+- `workflow backup-all` — backup ALL workflows to a folder (disaster recovery)
+- `workflow restore-all` — restore workflows from a backup folder (with `--dry-run`)
+- `workflow diff` — compare two workflows or a workflow vs a local file (colored diff)
+- `execution errors` — quick view of recent failures with optional `--details`
+
+## [1.3.0] - 2026-04-01
+
+### Added
+- `config test` — verify your n8n connection works before doing anything
+- `workflow search <query>` — find workflows by name (case-insensitive)
+- `workflow bulk-activate --tag X` / `--search X` — activate multiple workflows at once
+- `workflow bulk-deactivate --tag X` / `--search X` — deactivate multiple workflows at once
+- `completions bash|zsh|fish` — generate shell completion scripts
+- Colored status/active columns in table output (green=success, red=error, etc.)
+
+## [1.2.0] - 2026-04-01
+
+### Added
+- `workflow export` — save any workflow to a portable JSON file
+- `workflow import` — create a workflow from a JSON file (with optional name override)
+- `execution watch` — live monitoring of executions with real-time polling
+- `status` — dashboard showing workflows, recent executions, and errors at a glance
+- REPL tab-completion for all commands and subcommands
+- GitHub Actions CI (Python 3.10-3.13)
+
+## [1.1.0] - 2026-03-31
+
+### Changed
+- **BREAKING**: Removed `credential list` and `credential update` commands (not supported by n8n Public API v1.1.1)
+- **BREAKING**: Removed `execution stop` command (not in public API)
+- **BREAKING**: Removed `table` command group (Data Tables not in public API v1.1.1)
+- Aligned all endpoints with verified n8n OpenAPI spec v1.1.1
+- Version bumped to 1.1.0
+
+### Added
+- `workflow set-tags` command to update workflow tags
+- `workflow transfer` command to transfer workflows between projects
+- `credential transfer` command to transfer credentials between projects
+- URL validation in `config set base_url`
+- Configurable timeout via `N8N_TIMEOUT` env var (default: 30s)
+- Ellipsis indicator when table columns are truncated
+- Better JSON error messages (`@file.json` not found, invalid JSON)
+
+### Fixed
+- `credential list` no longer crashes with 405 (command removed — API doesn't support it)
+- `_load_json_arg` now shows clear error for missing files and invalid JSON
+- API key is always masked in `config show`, even with `--json`
+
+### Removed
+- `setup.py` (replaced by `pyproject.toml`)
+- `core/session.py` (unused REPL state dataclass)
+- `core/tables.py` (Data Tables not in n8n Public API)
+- `execution stop/stop-all` (not in public API)
+- `execution tags/set-tags` (not in public API)
+
+## [1.0.0] - 2026-03-31
+
+### Added
+- Initial release
+- CLI harness following CLI-Anything pattern
+- Workflow management (list, get, create, update, delete, activate, deactivate, tags)
+- Execution management (list, get, delete, retry)
+- Credential management (create, delete, schema)
+- Variable management (CRUD)
+- Tag management (CRUD)
+- Interactive REPL mode with colored output
+- JSON output mode (`--json`)
+- Config persistence (`~/.cli-anything/n8n/config.json`)
+- 29 unit tests, E2E test suite
diff --git a/n8n/agent-harness/LICENSE b/n8n/agent-harness/LICENSE
new file mode 100644
index 000000000..420954035
--- /dev/null
+++ b/n8n/agent-harness/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Juan Jose Sanchez Bernal / Webcomunica Soluciones Informaticas
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/n8n/agent-harness/N8N.md b/n8n/agent-harness/N8N.md
new file mode 100644
index 000000000..038f75939
--- /dev/null
+++ b/n8n/agent-harness/N8N.md
@@ -0,0 +1,63 @@
+# N8N.md — Architecture
+
+## Overview
+
+`cli-anything-n8n` wraps the n8n Public API v1.1.1 into a Click-based CLI, following the CLI-Anything harness pattern by HKUDS. Only verified endpoints from the OpenAPI spec are exposed.
+
+## n8n Compatibility
+
+- **Minimum version**: n8n >= 1.0.0
+- **API version**: Public API v1.1.1
+- **Verified against**: n8n 2.43.0
+- **OpenAPI spec**: fetched from `/api/v1/openapi.yml`
+
+## Architecture
+
+```
+cli_anything/n8n/
+├── n8n_cli.py # Click CLI (groups, commands, REPL, error handling)
+├── core/ # Business logic (thin wrappers over backend)
+│ ├── workflows.py # 9 endpoints (CRUD, activate, tags, transfer)
+│ ├── executions.py # 4 endpoints (list, get, delete, retry)
+│ ├── credentials.py # 4 endpoints (create, delete, schema, transfer)
+│ ├── variables.py # 4 endpoints (CRUD)
+│ ├── tags.py # 5 endpoints (CRUD)
+│ └── project.py # Config load/save
+├── utils/
+│ ├── n8n_backend.py # HTTP client (sole module making requests)
+│ └── repl_skin.py # Banner, colors, table formatting
+├── skills/
+│ └── SKILL.md # AI agent discovery
+└── tests/
+ ├── test_core.py # Unit tests (mocked)
+ └── test_full_e2e.py # E2E tests (live n8n)
+```
+
+## Data Flow
+
+```
+User/Agent -> n8n_cli.py (Click) -> core/*.py -> n8n_backend.py -> n8n REST API
+```
+
+## Authentication
+
+Header-based: `X-N8N-API-KEY: <key>`
+
+Resolution order: CLI `--api-key` > env `N8N_API_KEY` > config file
+
+## What's NOT in the Public API
+
+These n8n features are NOT available through the public REST API v1.1.1:
+- **Data Tables**: no endpoints at all
+- **Credential listing/updating**: only create, delete, schema, transfer
+- **Execution stop**: only list, get, delete, retry
+- **Workflow execute**: not in public API (use internal API or n8n UI)
+- **Audit logs**: POST-only, not exposed in CLI
+
+## Conventions
+
+- All core functions accept `base_url` and `api_key` as keyword args
+- All commands support `--json` for parseable output
+- PEP 420 namespace: `cli_anything/` has NO `__init__.py`
+- Entry point: `cli-anything-n8n` -> `cli_anything.n8n.n8n_cli:main`
+- Timeout configurable via `N8N_TIMEOUT` env var (default: 30s)
diff --git a/n8n/agent-harness/cli_anything/n8n/README.md b/n8n/agent-harness/cli_anything/n8n/README.md
new file mode 100644
index 000000000..257ece798
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/README.md
@@ -0,0 +1,249 @@
+# cli-anything-n8n
+
+[![PyPI](https://img.shields.io/pypi/v/cli-anything-n8n.svg)](https://pypi.org/project/cli-anything-n8n/)
+[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
+[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
+[![CLI-Anything](https://img.shields.io/badge/CLI--Anything-harness-orange.svg)](https://github.com/HKUDS/CLI-Anything)
+[![n8n API v1.1.1](https://img.shields.io/badge/n8n-API%20v1.1.1-EA4B71.svg)](https://docs.n8n.io/api/api-reference/)
+
+> [Leer en Español](#spanish) | [Read in English](#english)
+
+---
+
+<a id="english"></a>
+
+## English
+
+Control your [n8n](https://n8n.io) instance from the terminal. List workflows, check executions, manage tags — all without opening the browser.
+
+Built with the [CLI-Anything](https://github.com/HKUDS/CLI-Anything) pattern, so AI agents can use it too.
+
+### Try it now (2 minutes)
+
+```bash
+# 1. Install
+pip install cli-anything-n8n
+
+# 2. Connect to your n8n
+export N8N_BASE_URL=https://your-n8n-instance.com
+export N8N_API_KEY=your-api-key
+
+# 3. Try it!
+cli-anything-n8n workflow list
+```
+
+> **Where do I get my API key?** In n8n, go to Settings > API > Create API Key.
+
+### What can I do?
+
+```bash
+# List your workflows
+cli-anything-n8n workflow list
+
+# See only active workflows
+cli-anything-n8n workflow list --active
+
+# Check failed executions
+cli-anything-n8n execution list --status error
+
+# Get details of a specific workflow
+cli-anything-n8n workflow get ABC123
+
+# Create a tag
+cli-anything-n8n tag create "production"
+
+# Get JSON output (for scripts or AI agents)
+cli-anything-n8n --json workflow list
+
+# Interactive mode — just type commands
+cli-anything-n8n
+n8n> workflow list
+n8n> tag list
+n8n> exit
+```
+
+### All commands
+
+| Group | Commands | What it does |
+|-------|----------|--------------|
+| **workflow** | list, get, create, update, delete, activate, deactivate, tags, set-tags, transfer | Manage your workflows |
+| **execution** | list, get, delete, retry | Check and retry executions |
+| **credential** | create, delete, schema, transfer | Manage credentials |
+| **variable** | list, create, update, delete | Manage environment variables |
+| **tag** | list, get, create, update, delete | Organize with tags |
+| **config** | show, set | Save your connection settings |
+
+### Save your connection (so you don't type it every time)
+
+```bash
+cli-anything-n8n config set base_url https://your-n8n-instance.com
+cli-anything-n8n config set api_key your-api-key
+
+# Now just use it directly
+cli-anything-n8n workflow list
+```
+
+### Configuration options
+
+| Method | Priority | Example |
+|--------|----------|---------|
+| CLI flags | 1 (highest) | `--url https://... --api-key xxx` |
+| Environment variables | 2 | `N8N_BASE_URL`, `N8N_API_KEY` |
+| Config file | 3 | `cli-anything-n8n config set ...` |
+
+Extra env vars: `N8N_TIMEOUT` (default: 30 seconds)
+
+### For AI agents and scripts
+
+```bash
+# Always use --json for machine-readable output
+cli-anything-n8n --json workflow list
+
+# Pass complex data from files
+cli-anything-n8n workflow create @my-workflow.json
+
+# Check exit codes
+cli-anything-n8n workflow get ABC123 && echo "OK" || echo "FAILED"
+```
+
+### n8n compatibility
+
+Verified against **n8n 2.43.0** (Public API v1.1.1). Works with any n8n >= 1.0.0.
+
+> **Note**: Some n8n features (Data Tables, credential listing, execution stop) are not available through the public API. This CLI only exposes verified, working endpoints.
+
+### Development
+
+```bash
+git clone https://github.com/webcomunicasolutions/cli-n8n.git
+cd cli-n8n
+pip install -e .
+
+# Run tests (no n8n needed)
+pip install pytest
+pytest cli_anything/n8n/tests/test_core.py -v
+
+# Run E2E tests (needs a running n8n)
+export N8N_BASE_URL=https://your-n8n.com
+export N8N_API_KEY=your-key
+pytest cli_anything/n8n/tests/test_full_e2e.py -v
+```
+
+### Project structure
+
+```
+cli_anything/n8n/
+├── n8n_cli.py # CLI + interactive REPL
+├── core/ # API wrappers (one file per resource)
+│ ├── workflows.py
+│ ├── executions.py
+│ ├── credentials.py
+│ ├── variables.py
+│ ├── tags.py
+│ └── project.py # Config management
+├── utils/
+│ ├── n8n_backend.py # HTTP client
+│ └── repl_skin.py # Terminal UI
+└── tests/
+ ├── test_core.py # Unit tests (mocked)
+ └── test_full_e2e.py # E2E tests (live n8n)
+```
+
+### License
+
+MIT - Juan Jose Sanchez Bernal / [Webcomunica Soluciones Informaticas](https://webcomunica.solutions)
+
+---
+
+<a id="spanish"></a>
+
+## Español
+
+Controla tu instancia de [n8n](https://n8n.io) desde la terminal. Lista workflows, revisa ejecuciones, gestiona tags — todo sin abrir el navegador.
+
+Construido con el patron [CLI-Anything](https://github.com/HKUDS/CLI-Anything), para que agentes IA tambien puedan usarlo.
+
+### Pruebalo ahora (2 minutos)
+
+```bash
+# 1. Instalar
+pip install cli-anything-n8n
+
+# 2. Conectar a tu n8n
+export N8N_BASE_URL=https://tu-instancia-n8n.com
+export N8N_API_KEY=tu-api-key
+
+# 3. Probar!
+cli-anything-n8n workflow list
+```
+
+> **Donde consigo mi API key?** En n8n, ve a Settings > API > Create API Key.
+
+### Que puedo hacer?
+
+```bash
+# Listar workflows
+cli-anything-n8n workflow list
+
+# Solo los activos
+cli-anything-n8n workflow list --active
+
+# Ver ejecuciones fallidas
+cli-anything-n8n execution list --status error
+
+# Detalle de un workflow
+cli-anything-n8n workflow get ABC123
+
+# Crear un tag
+cli-anything-n8n tag create "produccion"
+
+# Salida JSON (para scripts o agentes IA)
+cli-anything-n8n --json workflow list
+
+# Modo interactivo
+cli-anything-n8n
+n8n> workflow list
+n8n> tag list
+n8n> exit
+```
+
+### Todos los comandos
+
+| Grupo | Comandos | Que hace |
+|-------|----------|----------|
+| **workflow** | list, get, create, update, delete, activate, deactivate, tags, set-tags, transfer | Gestionar workflows |
+| **execution** | list, get, delete, retry | Revisar y reintentar ejecuciones |
+| **credential** | create, delete, schema, transfer | Gestionar credenciales |
+| **variable** | list, create, update, delete | Gestionar variables de entorno |
+| **tag** | list, get, create, update, delete | Organizar con tags |
+| **config** | show, set | Guardar configuracion de conexion |
+
+### Guardar conexion (para no escribirla cada vez)
+
+```bash
+cli-anything-n8n config set base_url https://tu-instancia-n8n.com
+cli-anything-n8n config set api_key tu-api-key
+
+# Ahora usalo directamente
+cli-anything-n8n workflow list
+```
+
+### Compatibilidad con n8n
+
+Verificado contra **n8n 2.43.0** (API publica v1.1.1). Funciona con cualquier n8n >= 1.0.0.
+
+> **Nota**: Algunas funcionalidades de n8n (Data Tables, listar credenciales, parar ejecuciones) no estan disponibles via la API publica. Este CLI solo expone endpoints verificados y funcionales.
+
+### Desarrollo
+
+```bash
+git clone https://github.com/webcomunicasolutions/cli-n8n.git
+cd cli-n8n
+pip install -e .
+pip install pytest
+pytest cli_anything/n8n/tests/test_core.py -v
+```
+
+### Licencia
+
+MIT - Juan Jose Sanchez Bernal / [Webcomunica Soluciones Informaticas](https://webcomunica.solutions)
diff --git a/n8n/agent-harness/cli_anything/n8n/__init__.py b/n8n/agent-harness/cli_anything/n8n/__init__.py
new file mode 100644
index 000000000..7583f6baa
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/__init__.py
@@ -0,0 +1 @@
+# cli_anything.n8n — CLI harness for n8n workflow automation
diff --git a/n8n/agent-harness/cli_anything/n8n/__main__.py b/n8n/agent-harness/cli_anything/n8n/__main__.py
new file mode 100644
index 000000000..b844729af
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/__main__.py
@@ -0,0 +1,5 @@
+"""Enable python -m cli_anything.n8n"""
+from cli_anything.n8n.n8n_cli import main
+
+if __name__ == "__main__":
+ main()
diff --git a/n8n/agent-harness/cli_anything/n8n/core/__init__.py b/n8n/agent-harness/cli_anything/n8n/core/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/n8n/agent-harness/cli_anything/n8n/core/credentials.py b/n8n/agent-harness/cli_anything/n8n/core/credentials.py
new file mode 100644
index 000000000..803a2da4a
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/credentials.py
@@ -0,0 +1,33 @@
+"""Credential management — create, delete, schema, transfer.
+
+Note: n8n Public API v1.1.1 does NOT support listing or updating credentials
+via GET/PATCH. This is by design — credentials contain sensitive data.
+Available operations: POST (create), DELETE, GET schema, PUT transfer.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from cli_anything.n8n.utils.n8n_backend import (
+ api_delete,
+ api_get,
+ api_post,
+ api_put,
+)
+
+
+def create_credential(data: dict[str, Any], *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_post("/credentials", data, base_url=base_url, api_key=api_key)
+
+
+def delete_credential(credential_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_delete(f"/credentials/{credential_id}", base_url=base_url, api_key=api_key)
+
+
+def get_credential_schema(credential_type: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_get(f"/credentials/schema/{credential_type}", base_url=base_url, api_key=api_key)
+
+
+def transfer_credential(credential_id: str, project_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_put(f"/credentials/{credential_id}/transfer", {"destinationProjectId": project_id}, base_url=base_url, api_key=api_key)
diff --git a/n8n/agent-harness/cli_anything/n8n/core/executions.py b/n8n/agent-harness/cli_anything/n8n/core/executions.py
new file mode 100644
index 000000000..f0e54b41d
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/executions.py
@@ -0,0 +1,52 @@
+"""Execution management — list, get, delete, retry.
+
+Note: n8n Public API v1.1.1 does NOT support stop or tags on executions.
+Available: GET list, GET detail, DELETE, POST retry.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from cli_anything.n8n.utils.n8n_backend import (
+ api_delete,
+ api_get,
+ api_post,
+)
+
+
+def list_executions(
+ *,
+ base_url: str | None = None,
+ api_key: str | None = None,
+ status: str | None = None,
+ workflow_id: str | None = None,
+ limit: int = 20,
+ cursor: str | None = None,
+ include_data: bool = False,
+) -> Any:
+ params: dict[str, Any] = {"limit": limit}
+ if status:
+ params["status"] = status
+ if workflow_id:
+ params["workflowId"] = workflow_id
+ if cursor:
+ params["cursor"] = cursor
+ if include_data:
+ params["includeData"] = "true"
+ return api_get("/executions", base_url=base_url, api_key=api_key, params=params)
+
+
+def get_execution(execution_id: str, *, base_url: str | None = None, api_key: str | None = None, include_data: bool = True) -> Any:
+ params: dict[str, Any] = {}
+ if include_data:
+ params["includeData"] = "true"
+ return api_get(f"/executions/{execution_id}", base_url=base_url, api_key=api_key, params=params)
+
+
+def delete_execution(execution_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_delete(f"/executions/{execution_id}", base_url=base_url, api_key=api_key)
+
+
+def retry_execution(execution_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_post(f"/executions/{execution_id}/retry", base_url=base_url, api_key=api_key)
diff --git a/n8n/agent-harness/cli_anything/n8n/core/expressions.py b/n8n/agent-harness/cli_anything/n8n/core/expressions.py
new file mode 100644
index 000000000..f33512ce3
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/expressions.py
@@ -0,0 +1,81 @@
+"""n8n expression validator — check expression syntax offline.
+
+Based on n8n expression syntax rules from documentation.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+
+@dataclass
+class ExpressionResult:
+ valid: bool
+ expression: str
+ issues: list[str]
+ warnings: list[str]
+
+
+MAX_EXPR_LENGTH = 100_000
+
+
+def validate_expression(expr: str) -> ExpressionResult:
+ """Validate an n8n expression string."""
+ if len(expr) > MAX_EXPR_LENGTH:
+ return ExpressionResult(False, expr[:100], [f"Expression too long ({len(expr)} chars, max {MAX_EXPR_LENGTH})"], [])
+
+ issues: list[str] = []
+ warnings: list[str] = []
+
+ # Must start with = for dynamic expressions in n8n fields
+ if not expr.startswith("="):
+ if "{{" in expr:
+ warnings.append("Expression should start with '=' prefix for n8n fields (e.g., ={{$json.name}})")
+
+ # Check brace matching
+ inner = expr.lstrip("=")
+ open_count = inner.count("{{")
+ close_count = inner.count("}}")
+ if open_count != close_count:
+ issues.append(f"Mismatched braces: {open_count} opening '{{{{' vs {close_count} closing '}}}}'")
+
+ # Check for single braces (common mistake)
+ single_open = inner.count("{") - inner.count("{{") * 2
+ single_close = inner.count("}") - inner.count("}}") * 2
+ if single_open > 0 or single_close > 0:
+ warnings.append("Found single '{' or '}' braces — n8n expressions use double '{{' and '}}'")
+
+ # Extract expressions inside {{ }}
+ expressions = re.findall(r"\{\{(.*?)\}\}", inner, re.DOTALL)
+
+ for i, exp in enumerate(expressions):
+ exp = exp.strip()
+
+ # Check for common n8n variables and valid JS globals
+ valid_prefixes = ("$json", "$node", "$input", "$binary", "$env", "$now", "$today",
+ "$workflow", "$execution", "$prevNode", "$runIndex", "$itemIndex",
+ "$parameter", "$position", "$fromAI", "$if", "$ifEmpty",
+ "Math.", "Date.", "Object.", "Array.", "JSON.", "String.",
+ "Number.", "parseInt", "parseFloat", "encodeURI", "decodeURI",
+ "btoa", "atob", "DateTime", "true", "false", "null", "undefined",
+ "new ", "typeof ", "instanceof ")
+
+ # Check for common mistakes
+ if "$json[" in exp and "'" not in exp and '"' not in exp:
+ issues.append(f"$json[] needs quotes around key: $json['key'] not $json[key]")
+
+ if '$node["' in exp and '"].json' not in exp and '"].first()' not in exp:
+ warnings.append(f"$node reference may be incomplete — usually needs .json.field or .first().json.field")
+
+ # Check $fromAI usage
+ if "$fromAI" in exp:
+ if "(" not in exp:
+ issues.append("$fromAI needs parentheses: $fromAI('fieldName', 'description', 'type')")
+
+ return ExpressionResult(
+ valid=len(issues) == 0,
+ expression=expr,
+ issues=issues,
+ warnings=warnings,
+ )
diff --git a/n8n/agent-harness/cli_anything/n8n/core/fixers.py b/n8n/agent-harness/cli_anything/n8n/core/fixers.py
new file mode 100644
index 000000000..f8209098e
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/fixers.py
@@ -0,0 +1,223 @@
+"""Workflow auto-fixer — detect and repair common workflow issues.
+
+Inspired by n8n-mcp's WorkflowAutoFixer. Operates purely on workflow JSON.
+"""
+
+from __future__ import annotations
+
+import re
+import uuid
+from dataclasses import dataclass
+from typing import Any
+
+
+@dataclass
+class Fix:
+ """A single fix that can be applied to a workflow."""
+
+ fix_type: str
+ description: str
+ confidence: str # HIGH, MEDIUM, LOW
+ node_name: str | None = None
+
+
+def autofix(workflow: dict[str, Any], *, apply: bool = False) -> tuple[dict[str, Any], list[Fix]]:
+ """Detect and optionally fix common workflow issues.
+
+ Returns (possibly modified workflow, list of fixes detected).
+ """
+ fixes: list[Fix] = []
+ nodes = workflow.get("nodes", [])
+ connections = workflow.get("connections", {})
+
+ if not isinstance(nodes, list):
+ nodes = []
+ if not isinstance(connections, dict):
+ connections = {}
+
+ node_names = {n.get("name") for n in nodes if isinstance(n, dict)}
+
+ # 1. Expression format: missing = prefix
+ for node in nodes:
+ if not isinstance(node, dict):
+ continue
+ params = node.get("parameters")
+ if not isinstance(params, dict):
+ continue
+ for key, val in _iter_params(params):
+ if isinstance(val, str) and "{{" in val and not val.startswith("="):
+ fixes.append(Fix(
+ "expression-format",
+ f"Expression missing '=' prefix in {node.get('name', '?')}.{key}: {val[:50]}",
+ "HIGH", node.get("name"),
+ ))
+ if apply:
+ _set_nested(params, key, f"={val}")
+
+ # 2. Webhook missing path
+ for node in nodes:
+ if not isinstance(node, dict):
+ continue
+ node_type = node.get("type", "").lower()
+ if "webhook" in node_type:
+ params = node.get("parameters") or {}
+ if not params.get("path"):
+ new_path = uuid.uuid4().hex[:12]
+ fixes.append(Fix(
+ "webhook-missing-path",
+ f"Webhook node '{node.get('name', '?')}' has no path, generating: {new_path}",
+ "HIGH", node.get("name"),
+ ))
+ if apply:
+ node.setdefault("parameters", {})["path"] = new_path
+ node["webhookId"] = str(uuid.uuid4())
+
+ # 3. Connections to non-existent nodes
+ nodes_to_check = list(connections.keys())
+ for source_name in nodes_to_check:
+ if source_name not in node_names:
+ fixes.append(Fix("connection-orphan-source", f"Connection from non-existent node: '{source_name}'", "HIGH"))
+ if apply:
+ del connections[source_name]
+ continue
+ conns = connections[source_name]
+ if isinstance(conns, dict):
+ for conn_type, outputs in conns.items():
+ if isinstance(outputs, list):
+ for output_list in outputs:
+ if isinstance(output_list, list):
+ for i, target in enumerate(output_list):
+ if isinstance(target, dict):
+ target_name = target.get("node", "")
+ if target_name and target_name not in node_names:
+ fixes.append(Fix("connection-orphan-target", f"Connection to non-existent node: '{target_name}' (from '{source_name}')", "HIGH"))
+ if apply:
+ output_list[i] = None
+ if apply:
+ output_list[:] = [t for t in output_list if t is not None]
+
+ # 4. Duplicate node names
+ seen: dict[str, int] = {}
+ for node in nodes:
+ if not isinstance(node, dict):
+ continue
+ name = node.get("name", "")
+ if name in seen:
+ new_name = f"{name}_{seen[name]}"
+ fixes.append(Fix("duplicate-node-name", f"Duplicate name '{name}' renamed to '{new_name}'", "MEDIUM", name))
+ if apply:
+ if name in connections:
+ connections[new_name] = connections.pop(name)
+ for src_conns in connections.values():
+ if isinstance(src_conns, dict):
+ for outputs in src_conns.values():
+ if isinstance(outputs, list):
+ for output_list in outputs:
+ if isinstance(output_list, list):
+ for target in output_list:
+ if isinstance(target, dict) and target.get("node") == name:
+ target["node"] = new_name
+ node["name"] = new_name
+ seen[name] += 1
+ else:
+ seen[name] = 1
+
+ # 5. Connection type corrections (numeric keys like "0" -> "main")
+ for source_name, conns in connections.items():
+ if isinstance(conns, dict):
+ bad_keys = [k for k in conns if k.isdigit()]
+ for bk in bad_keys:
+ fixes.append(Fix("connection-numeric-key", f"Connection type '{bk}' should be 'main' (from '{source_name}')", "HIGH"))
+ if apply:
+ moved = conns.pop(bk)
+ if "main" in conns and isinstance(conns["main"], list):
+ conns["main"].extend(moved)
+ else:
+ conns["main"] = moved
+
+ # 6. Error output without error connections
+ for node in nodes:
+ if not isinstance(node, dict):
+ continue
+ if node.get("onError") == "continueErrorOutput":
+ has_error_conn = False
+ name = node.get("name", "")
+ conns = connections.get(name, {})
+ if isinstance(conns, dict):
+ for conn_type, outputs in conns.items():
+ if isinstance(outputs, list) and len(outputs) > 1:
+ has_error_conn = True
+ if not has_error_conn:
+ fixes.append(Fix("error-output-unused", f"Node '{name}' has continueErrorOutput but no error branch", "MEDIUM", name))
+ if apply:
+ del node["onError"]
+
+ return workflow, fixes
+
+
+def _iter_params(params: dict[str, Any], prefix: str = "") -> list[tuple[str, Any]]:
+ """Recursively iterate parameter key-value pairs.
+
+ Returns (dotted_key, string_value) tuples. Keys with list indices use
+ bracket notation: 'assignments[0].value'.
+ Note: _set_nested handles these bracket keys correctly.
+ """
+ result = []
+ for k, v in params.items():
+ full_key = f"{prefix}.{k}" if prefix else k
+ if isinstance(v, dict):
+ result.extend(_iter_params(v, full_key))
+ elif isinstance(v, list):
+ for i, item in enumerate(v):
+ if isinstance(item, dict):
+ result.extend(_iter_params(item, f"{full_key}[{i}]"))
+ elif isinstance(item, str):
+ result.append((f"{full_key}[{i}]", item))
+ elif isinstance(v, str):
+ result.append((full_key, v))
+ return result
+
+
+# Regex to split keys like "assignments[0].value" into parts
+_KEY_PART_RE = re.compile(r'([^\[.\]]+)|\[(\d+)\]')
+
+
+def _set_nested(d: dict[str, Any], key: str, value: Any) -> bool:
+ """Set a nested value using dot/bracket notation.
+
+ Handles keys like 'a.b', 'a[0].b', 'a.b[1].c' correctly,
+ navigating into both dicts and lists. Returns True if value was set.
+ """
+ parts: list[str | int] = []
+ for match in _KEY_PART_RE.finditer(key):
+ if match.group(1) is not None:
+ parts.append(match.group(1))
+ elif match.group(2) is not None:
+ parts.append(int(match.group(2)))
+
+ if not parts:
+ return False
+
+ current: Any = d
+ for part in parts[:-1]:
+ if isinstance(part, int):
+ if isinstance(current, list) and 0 <= part < len(current):
+ current = current[part]
+ else:
+ return False
+ else:
+ if isinstance(current, dict):
+ current = current.setdefault(part, {})
+ else:
+ return False
+
+ last = parts[-1]
+ if isinstance(last, int):
+ if isinstance(current, list) and 0 <= last < len(current):
+ current[last] = value
+ return True
+ return False
+ elif isinstance(current, dict):
+ current[last] = value
+ return True
+ return False
diff --git a/n8n/agent-harness/cli_anything/n8n/core/nodes.py b/n8n/agent-harness/cli_anything/n8n/core/nodes.py
new file mode 100644
index 000000000..5f7ebaf35
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/nodes.py
@@ -0,0 +1,80 @@
+"""Node discovery — search n8n community nodes via npm registry.
+
+Uses the npm registry API to search for n8n community node packages.
+No authentication needed.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import requests
+
+
+NPM_SEARCH_URL = "https://registry.npmjs.com/-/v1/search"
+
+
+def search_nodes(query: str, *, limit: int = 15) -> dict[str, Any]:
+ """Search for n8n community node packages on npm."""
+ resp = requests.get(
+ NPM_SEARCH_URL,
+ params={"text": f"n8n-nodes {query}", "size": limit},
+ timeout=15,
+ )
+ resp.raise_for_status()
+ data = resp.json()
+
+ packages = []
+ for obj in data.get("objects", []):
+ pkg = obj.get("package", {})
+ name = pkg.get("name", "")
+ # Filter out non-node packages
+ if not name.startswith("n8n-nodes") and "n8n-nodes" not in name:
+ continue
+ packages.append({
+ "name": name,
+ "version": pkg.get("version", ""),
+ "description": pkg.get("description", "")[:120],
+ "author": pkg.get("publisher", {}).get("username", pkg.get("author", {}).get("name", "")),
+ "npm_url": f"https://www.npmjs.com/package/{name}",
+ "popularity_score": obj.get("score", {}).get("detail", {}).get("popularity", 0),
+ })
+
+ return {"total": data.get("total", 0), "packages": packages}
+
+
+def get_node_info(package_name: str) -> dict[str, Any]:
+ """Get detailed info about an npm node package."""
+ resp = requests.get(
+ f"https://registry.npmjs.com/{package_name}",
+ timeout=15,
+ )
+ resp.raise_for_status()
+ data = resp.json()
+
+ latest = data.get("dist-tags", {}).get("latest", "")
+ latest_data = data.get("versions", {}).get(latest, {})
+
+ # Extract n8n-specific metadata (validate and limit untrusted data)
+ n8n_meta = latest_data.get("n8n", {}) if isinstance(latest_data.get("n8n"), dict) else {}
+ node_list = n8n_meta.get("nodes", [])[:50] if isinstance(n8n_meta.get("nodes"), list) else []
+ credential_list = n8n_meta.get("credentials", [])[:20] if isinstance(n8n_meta.get("credentials"), list) else []
+
+ pkg_name = str(data.get("name", ""))[:100]
+ author_raw = data.get("author", {})
+ author_name = (author_raw.get("name", "") if isinstance(author_raw, dict) else str(author_raw))[:100]
+
+ return {
+ "name": pkg_name,
+ "version": str(latest)[:20],
+ "description": str(data.get("description", ""))[:500],
+ "author": author_name,
+ "license": str(latest_data.get("license", ""))[:50],
+ "homepage": str(data.get("homepage", ""))[:200],
+ "repository": (data.get("repository", {}).get("url", "") if isinstance(data.get("repository"), dict) else "")[:200],
+ "npm_url": f"https://www.npmjs.com/package/{pkg_name}",
+ "n8n_nodes": [str(n.get("type", n) if isinstance(n, dict) else n)[:100] for n in node_list],
+ "n8n_credentials": [str(c.get("type", c) if isinstance(c, dict) else c)[:100] for c in credential_list],
+ "install_cmd": f"cd ~/.n8n && npm install {pkg_name}",
+ "keywords": latest_data.get("keywords", [])[:10],
+ }
diff --git a/n8n/agent-harness/cli_anything/n8n/core/project.py b/n8n/agent-harness/cli_anything/n8n/core/project.py
new file mode 100644
index 000000000..055c003c1
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/project.py
@@ -0,0 +1,62 @@
+"""Configuration management — load/save from JSON file + env vars."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+from typing import Any
+
+
+CONFIG_DIR = Path.home() / ".cli-anything" / "n8n"
+CONFIG_FILE = CONFIG_DIR / "config.json"
+
+DEFAULTS: dict[str, Any] = {
+ "base_url": "",
+ "api_key": "",
+}
+
+
+def load_config() -> dict[str, Any]:
+ """Load config from file, overlaid with env vars."""
+ cfg = dict(DEFAULTS)
+ if CONFIG_FILE.exists():
+ try:
+ with open(CONFIG_FILE) as f:
+ cfg.update(json.load(f))
+ except (json.JSONDecodeError, ValueError):
+ pass # Corrupted config — fall back to defaults + env vars
+ if url := os.environ.get("N8N_BASE_URL"):
+ cfg["base_url"] = url
+ if key := os.environ.get("N8N_API_KEY"):
+ cfg["api_key"] = key
+ return cfg
+
+
+def save_config(cfg: dict[str, Any]) -> Path:
+ """Persist config to disk with restricted permissions."""
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
+ try:
+ os.chmod(str(CONFIG_DIR), 0o700)
+ except OSError:
+ pass
+ with open(CONFIG_FILE, "w") as f:
+ json.dump(cfg, f, indent=2)
+ try:
+ os.chmod(str(CONFIG_FILE), 0o600)
+ except OSError:
+ pass
+ return CONFIG_FILE
+
+
+def get_connection(
+ base_url: str | None = None,
+ api_key: str | None = None,
+) -> tuple[str, str]:
+ """Resolve base_url and api_key from args > env > config file."""
+ cfg = load_config()
+ url = base_url or cfg["base_url"]
+ if url and not url.startswith(("http://", "https://")):
+ url = f"https://{url}"
+ key = api_key or cfg["api_key"]
+ return url, key
diff --git a/n8n/agent-harness/cli_anything/n8n/core/scaffolds.py b/n8n/agent-harness/cli_anything/n8n/core/scaffolds.py
new file mode 100644
index 000000000..2420c0e4e
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/scaffolds.py
@@ -0,0 +1,119 @@
+"""Workflow scaffolds — ready-to-use workflow templates based on proven patterns.
+
+Based on the 5 core patterns from real n8n workflow analysis.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+PATTERNS: dict[str, dict[str, Any]] = {
+ "webhook": {
+ "description": "Receive HTTP requests, process, and respond",
+ "workflow": {
+ "name": "Webhook Processing",
+ "nodes": [
+ {"parameters": {"path": "my-webhook", "responseMode": "responseNode", "options": {}}, "type": "n8n-nodes-base.webhook", "typeVersion": 2, "position": [0, 0], "name": "Webhook", "webhookId": "scaffold-webhook"},
+ {"parameters": {"conditions": {"options": {"caseSensitive": True, "leftValue": "", "typeValidation": "strict", "version": 2}, "conditions": [], "combinator": "and"}, "options": {}}, "type": "n8n-nodes-base.if", "typeVersion": 2.2, "position": [220, 0], "name": "Validate"},
+ {"parameters": {"options": {}}, "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [440, -80], "name": "Transform"},
+ {"parameters": {"respondWith": "json", "responseBody": "={{ JSON.stringify({ success: true, data: $json }) }}", "options": {}}, "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1.1, "position": [660, -80], "name": "Respond OK"},
+ {"parameters": {"respondWith": "json", "responseBody": "={{ JSON.stringify({ success: false, error: 'Validation failed' }) }}", "responseCode": 400, "options": {}}, "type": "n8n-nodes-base.respondToWebhook", "typeVersion": 1.1, "position": [440, 120], "name": "Respond Error"},
+ ],
+ "connections": {
+ "Webhook": {"main": [[{"node": "Validate", "type": "main", "index": 0}]]},
+ "Validate": {"main": [[{"node": "Transform", "type": "main", "index": 0}], [{"node": "Respond Error", "type": "main", "index": 0}]]},
+ "Transform": {"main": [[{"node": "Respond OK", "type": "main", "index": 0}]]},
+ },
+ "settings": {"executionOrder": "v1"},
+ },
+ },
+ "api": {
+ "description": "Fetch from REST API, transform, and store",
+ "workflow": {
+ "name": "API Integration",
+ "nodes": [
+ {"parameters": {}, "type": "n8n-nodes-base.manualTrigger", "typeVersion": 1, "position": [0, 0], "name": "Manual Trigger"},
+ {"parameters": {"url": "https://api.example.com/data", "options": {}}, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [220, 0], "name": "HTTP Request"},
+ {"parameters": {"options": {}}, "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [440, 0], "name": "Transform Data"},
+ {"parameters": {"options": {}}, "type": "n8n-nodes-base.noOp", "typeVersion": 1, "position": [660, 0], "name": "Output"},
+ ],
+ "connections": {
+ "Manual Trigger": {"main": [[{"node": "HTTP Request", "type": "main", "index": 0}]]},
+ "HTTP Request": {"main": [[{"node": "Transform Data", "type": "main", "index": 0}]]},
+ "Transform Data": {"main": [[{"node": "Output", "type": "main", "index": 0}]]},
+ },
+ "settings": {"executionOrder": "v1"},
+ },
+ },
+ "database": {
+ "description": "Read from database, transform, write to destination",
+ "workflow": {
+ "name": "Database Sync",
+ "nodes": [
+ {"parameters": {"rule": {"interval": [{"field": "hours", "hoursInterval": 1}]}}, "type": "n8n-nodes-base.scheduleTrigger", "typeVersion": 1.2, "position": [0, 0], "name": "Schedule"},
+ {"parameters": {"operation": "executeQuery", "query": "SELECT * FROM source_table LIMIT 100", "options": {}}, "type": "n8n-nodes-base.postgres", "typeVersion": 2.5, "position": [220, 0], "name": "Read Source"},
+ {"parameters": {"options": {}}, "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [440, 0], "name": "Transform"},
+ {"parameters": {"options": {}}, "type": "n8n-nodes-base.noOp", "typeVersion": 1, "position": [660, 0], "name": "Write Destination"},
+ ],
+ "connections": {
+ "Schedule": {"main": [[{"node": "Read Source", "type": "main", "index": 0}]]},
+ "Read Source": {"main": [[{"node": "Transform", "type": "main", "index": 0}]]},
+ "Transform": {"main": [[{"node": "Write Destination", "type": "main", "index": 0}]]},
+ },
+ "settings": {"executionOrder": "v1"},
+ },
+ },
+ "ai-agent": {
+ "description": "AI agent with tools and memory",
+ "workflow": {
+ "name": "AI Agent",
+ "nodes": [
+ {"parameters": {"options": {"systemMessage": "You are a helpful assistant."}}, "type": "@n8n/n8n-nodes-langchain.agent", "typeVersion": 1.7, "position": [440, 0], "name": "AI Agent"},
+ {"parameters": {}, "type": "n8n-nodes-base.manualTrigger", "typeVersion": 1, "position": [0, 0], "name": "Manual Trigger"},
+ {"parameters": {"options": {"model": "gpt-4o-mini"}}, "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi", "typeVersion": 1.2, "position": [220, 200], "name": "OpenAI Chat Model"},
+ {"parameters": {}, "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow", "typeVersion": 1.3, "position": [460, 200], "name": "Window Buffer Memory"},
+ ],
+ "connections": {
+ "Manual Trigger": {"main": [[{"node": "AI Agent", "type": "main", "index": 0}]]},
+ "OpenAI Chat Model": {"ai_languageModel": [[{"node": "AI Agent", "type": "ai_languageModel", "index": 0}]]},
+ "Window Buffer Memory": {"ai_memory": [[{"node": "AI Agent", "type": "ai_memory", "index": 0}]]},
+ },
+ "settings": {"executionOrder": "v1"},
+ },
+ },
+ "scheduled": {
+ "description": "Recurring task: fetch, process, deliver, log",
+ "workflow": {
+ "name": "Scheduled Task",
+ "nodes": [
+ {"parameters": {"rule": {"interval": [{"field": "days", "daysInterval": 1, "triggerAtHour": 8}]}}, "type": "n8n-nodes-base.scheduleTrigger", "typeVersion": 1.2, "position": [0, 0], "name": "Daily 8AM"},
+ {"parameters": {"url": "https://api.example.com/report", "options": {}}, "type": "n8n-nodes-base.httpRequest", "typeVersion": 4.2, "position": [220, 0], "name": "Fetch Data"},
+ {"parameters": {"options": {}}, "type": "n8n-nodes-base.set", "typeVersion": 3.4, "position": [440, 0], "name": "Process"},
+ {"parameters": {"options": {}}, "type": "n8n-nodes-base.noOp", "typeVersion": 1, "position": [660, 0], "name": "Deliver"},
+ ],
+ "connections": {
+ "Daily 8AM": {"main": [[{"node": "Fetch Data", "type": "main", "index": 0}]]},
+ "Fetch Data": {"main": [[{"node": "Process", "type": "main", "index": 0}]]},
+ "Process": {"main": [[{"node": "Deliver", "type": "main", "index": 0}]]},
+ },
+ "settings": {"executionOrder": "v1"},
+ },
+ },
+}
+
+
+def list_patterns() -> list[dict[str, str]]:
+ """List available scaffold patterns."""
+ return [{"name": name, "description": p["description"]} for name, p in PATTERNS.items()]
+
+
+def get_scaffold(pattern: str, *, name: str | None = None) -> dict[str, Any]:
+ """Get a scaffold workflow for a pattern. Returns a deep copy."""
+ import copy
+ if pattern not in PATTERNS:
+ raise ValueError(f"Unknown pattern: {pattern}. Available: {', '.join(PATTERNS.keys())}")
+ wf = copy.deepcopy(PATTERNS[pattern]["workflow"])
+ if name:
+ wf["name"] = name
+ return wf
diff --git a/n8n/agent-harness/cli_anything/n8n/core/tags.py b/n8n/agent-harness/cli_anything/n8n/core/tags.py
new file mode 100644
index 000000000..bb9b9dfdd
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/tags.py
@@ -0,0 +1,32 @@
+"""Tag management — CRUD."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from cli_anything.n8n.utils.n8n_backend import (
+ api_delete,
+ api_get,
+ api_post,
+ api_put,
+)
+
+
+def list_tags(*, base_url: str | None = None, api_key: str | None = None, limit: int = 50) -> Any:
+ return api_get("/tags", base_url=base_url, api_key=api_key, params={"limit": limit})
+
+
+def get_tag(tag_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_get(f"/tags/{tag_id}", base_url=base_url, api_key=api_key)
+
+
+def create_tag(name: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_post("/tags", {"name": name}, base_url=base_url, api_key=api_key)
+
+
+def update_tag(tag_id: str, name: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_put(f"/tags/{tag_id}", {"name": name}, base_url=base_url, api_key=api_key)
+
+
+def delete_tag(tag_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_delete(f"/tags/{tag_id}", base_url=base_url, api_key=api_key)
diff --git a/n8n/agent-harness/cli_anything/n8n/core/templates.py b/n8n/agent-harness/cli_anything/n8n/core/templates.py
new file mode 100644
index 000000000..fa9e70da2
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/templates.py
@@ -0,0 +1,27 @@
+"""n8n.io template search and fetch — uses the public n8n.io API (no auth needed)."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import requests
+
+TEMPLATES_API = "https://api.n8n.io/api/templates"
+
+
+def search_templates(query: str, *, limit: int = 10) -> dict[str, Any]:
+ """Search templates on n8n.io by keyword."""
+ resp = requests.get(
+ f"{TEMPLATES_API}/search",
+ params={"search": query, "rows": limit},
+ timeout=15,
+ )
+ resp.raise_for_status()
+ return resp.json()
+
+
+def get_template(template_id: int) -> dict[str, Any]:
+ """Fetch a template's full workflow JSON from n8n.io."""
+ resp = requests.get(f"{TEMPLATES_API}/workflows/{template_id}", timeout=15)
+ resp.raise_for_status()
+ return resp.json()
diff --git a/n8n/agent-harness/cli_anything/n8n/core/variables.py b/n8n/agent-harness/cli_anything/n8n/core/variables.py
new file mode 100644
index 000000000..39a97f5b1
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/variables.py
@@ -0,0 +1,28 @@
+"""Variable management — CRUD."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from cli_anything.n8n.utils.n8n_backend import (
+ api_delete,
+ api_get,
+ api_post,
+ api_put,
+)
+
+
+def list_variables(*, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_get("/variables", base_url=base_url, api_key=api_key)
+
+
+def create_variable(key: str, value: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_post("/variables", {"key": key, "value": value}, base_url=base_url, api_key=api_key)
+
+
+def update_variable(variable_id: str, key: str, value: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_put(f"/variables/{variable_id}", {"key": key, "value": value}, base_url=base_url, api_key=api_key)
+
+
+def delete_variable(variable_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_delete(f"/variables/{variable_id}", base_url=base_url, api_key=api_key)
diff --git a/n8n/agent-harness/cli_anything/n8n/core/versions.py b/n8n/agent-harness/cli_anything/n8n/core/versions.py
new file mode 100644
index 000000000..fb984ae02
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/versions.py
@@ -0,0 +1,186 @@
+"""Workflow version tracking — local SQLite storage for snapshots and rollback.
+
+Stores a snapshot of each workflow before any write operation (update, patch, autofix).
+Enables viewing history and rolling back to any previous version.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sqlite3
+import time
+from pathlib import Path
+from typing import Any
+
+
+DB_DIR = Path.home() / ".cli-anything" / "n8n"
+DB_PATH = DB_DIR / "versions.db"
+
+
+def _connect() -> sqlite3.Connection:
+ DB_DIR.mkdir(parents=True, exist_ok=True)
+ try:
+ os.chmod(str(DB_DIR), 0o700)
+ except OSError:
+ pass
+ conn = sqlite3.connect(str(DB_PATH), timeout=10.0)
+ conn.row_factory = sqlite3.Row
+ conn.execute("PRAGMA journal_mode=WAL")
+ conn.execute("PRAGMA synchronous=NORMAL")
+ conn.execute("""
+ CREATE TABLE IF NOT EXISTS workflow_versions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ workflow_id TEXT NOT NULL,
+ version_number INTEGER NOT NULL,
+ workflow_name TEXT,
+ snapshot TEXT NOT NULL,
+ trigger TEXT NOT NULL,
+ created_at TEXT NOT NULL
+ )
+ """)
+ conn.execute("""
+ CREATE INDEX IF NOT EXISTS idx_wf_versions_wfid
+ ON workflow_versions (workflow_id, version_number DESC)
+ """)
+ conn.commit()
+ return conn
+
+
+def save_snapshot(
+ workflow_id: str,
+ workflow_data: dict[str, Any],
+ trigger: str = "manual",
+) -> int:
+ """Save a workflow snapshot before modifying it. Returns version number."""
+ conn = _connect()
+ try:
+ row = conn.execute(
+ "SELECT COALESCE(MAX(version_number), 0) FROM workflow_versions WHERE workflow_id = ?",
+ (workflow_id,),
+ ).fetchone()
+ next_version = row[0] + 1
+
+ conn.execute(
+ """INSERT INTO workflow_versions
+ (workflow_id, version_number, workflow_name, snapshot, trigger, created_at)
+ VALUES (?, ?, ?, ?, ?, ?)""",
+ (
+ workflow_id,
+ next_version,
+ workflow_data.get("name", ""),
+ json.dumps(workflow_data, default=str),
+ trigger,
+ time.strftime("%Y-%m-%dT%H:%M:%S"),
+ ),
+ )
+ conn.commit()
+
+ # Auto-prune: keep max 50 versions per workflow
+ _auto_prune(conn, workflow_id, keep=50)
+
+ return next_version
+ finally:
+ conn.close()
+
+
+def _auto_prune(conn: sqlite3.Connection, workflow_id: str, keep: int = 50) -> None:
+ """Auto-prune old versions to prevent infinite DB growth."""
+ rows = conn.execute(
+ "SELECT id FROM workflow_versions WHERE workflow_id = ? ORDER BY version_number DESC",
+ (workflow_id,),
+ ).fetchall()
+ to_delete = [r["id"] for r in rows[keep:]]
+ if to_delete:
+ placeholders = ",".join("?" for _ in to_delete)
+ with conn:
+ conn.execute(f"DELETE FROM workflow_versions WHERE id IN ({placeholders})", to_delete)
+
+
+def list_versions(workflow_id: str, *, limit: int = 20) -> list[dict[str, Any]]:
+ """List stored versions for a workflow, newest first."""
+ conn = _connect()
+ try:
+ rows = conn.execute(
+ """SELECT id, workflow_id, version_number, workflow_name, trigger, created_at
+ FROM workflow_versions
+ WHERE workflow_id = ?
+ ORDER BY version_number DESC
+ LIMIT ?""",
+ (workflow_id, limit),
+ ).fetchall()
+ return [dict(r) for r in rows]
+ finally:
+ conn.close()
+
+
+def get_version(version_id: int) -> dict[str, Any] | None:
+ """Get a specific version by its database ID."""
+ conn = _connect()
+ try:
+ row = conn.execute(
+ "SELECT * FROM workflow_versions WHERE id = ?", (version_id,)
+ ).fetchone()
+ if not row:
+ return None
+ result = dict(row)
+ try:
+ result["snapshot"] = json.loads(result["snapshot"])
+ except (json.JSONDecodeError, TypeError):
+ result["snapshot"] = {}
+ return result
+ finally:
+ conn.close()
+
+
+def get_snapshot(workflow_id: str, version_number: int) -> dict[str, Any] | None:
+ """Get the workflow snapshot for a specific version number."""
+ conn = _connect()
+ try:
+ row = conn.execute(
+ "SELECT snapshot FROM workflow_versions WHERE workflow_id = ? AND version_number = ?",
+ (workflow_id, version_number),
+ ).fetchone()
+ if not row:
+ return None
+ try:
+ return json.loads(row["snapshot"])
+ except (json.JSONDecodeError, TypeError):
+ return None
+ finally:
+ conn.close()
+
+
+def prune_versions(workflow_id: str, *, keep: int = 10) -> int:
+ """Delete old versions, keeping only the N most recent. Returns count deleted."""
+ conn = _connect()
+ try:
+ rows = conn.execute(
+ """SELECT id FROM workflow_versions
+ WHERE workflow_id = ?
+ ORDER BY version_number DESC""",
+ (workflow_id,),
+ ).fetchall()
+ to_delete = [r["id"] for r in rows[keep:]]
+ if to_delete:
+ placeholders = ",".join("?" for _ in to_delete)
+ with conn:
+ conn.execute(
+ f"DELETE FROM workflow_versions WHERE id IN ({placeholders})",
+ to_delete,
+ )
+ return len(to_delete)
+ finally:
+ conn.close()
+
+
+def stats() -> dict[str, Any]:
+ """Get overall version storage stats."""
+ conn = _connect()
+ try:
+ total = conn.execute("SELECT COUNT(*) FROM workflow_versions").fetchone()[0]
+ workflows = conn.execute("SELECT COUNT(DISTINCT workflow_id) FROM workflow_versions").fetchone()[0]
+ db_size = DB_PATH.stat().st_size if DB_PATH.exists() else 0
+ return {"total_versions": total, "workflows_tracked": workflows, "db_size_bytes": db_size, "db_path": str(DB_PATH)}
+ finally:
+ conn.close()
diff --git a/n8n/agent-harness/cli_anything/n8n/core/workflows.py b/n8n/agent-harness/cli_anything/n8n/core/workflows.py
new file mode 100644
index 000000000..db80f9f81
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/core/workflows.py
@@ -0,0 +1,70 @@
+"""Workflow management — CRUD, activate/deactivate, tags, versions."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from cli_anything.n8n.utils.n8n_backend import (
+ api_delete,
+ api_get,
+ api_post,
+ api_put,
+)
+
+
+def list_workflows(
+ *,
+ base_url: str | None = None,
+ api_key: str | None = None,
+ active: bool | None = None,
+ tags: str | None = None,
+ name: str | None = None,
+ limit: int = 50,
+ cursor: str | None = None,
+) -> Any:
+ params: dict[str, Any] = {"limit": limit}
+ if active is not None:
+ params["active"] = str(active).lower()
+ if tags:
+ params["tags"] = tags
+ if name:
+ params["name"] = name
+ if cursor:
+ params["cursor"] = cursor
+ return api_get("/workflows", base_url=base_url, api_key=api_key, params=params)
+
+
+def get_workflow(workflow_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_get(f"/workflows/{workflow_id}", base_url=base_url, api_key=api_key)
+
+
+def create_workflow(data: dict[str, Any], *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_post("/workflows", data, base_url=base_url, api_key=api_key)
+
+
+def update_workflow(workflow_id: str, data: dict[str, Any], *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_put(f"/workflows/{workflow_id}", data, base_url=base_url, api_key=api_key)
+
+
+def delete_workflow(workflow_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_delete(f"/workflows/{workflow_id}", base_url=base_url, api_key=api_key)
+
+
+def activate_workflow(workflow_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_post(f"/workflows/{workflow_id}/activate", base_url=base_url, api_key=api_key)
+
+
+def deactivate_workflow(workflow_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_post(f"/workflows/{workflow_id}/deactivate", base_url=base_url, api_key=api_key)
+
+
+def get_workflow_tags(workflow_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_get(f"/workflows/{workflow_id}/tags", base_url=base_url, api_key=api_key)
+
+
+def update_workflow_tags(workflow_id: str, tag_ids: list[dict[str, str]], *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_put(f"/workflows/{workflow_id}/tags", tag_ids, base_url=base_url, api_key=api_key)
+
+
+def transfer_workflow(workflow_id: str, project_id: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_put(f"/workflows/{workflow_id}/transfer", {"destinationProjectId": project_id}, base_url=base_url, api_key=api_key)
diff --git a/n8n/agent-harness/cli_anything/n8n/n8n_cli.py b/n8n/agent-harness/cli_anything/n8n/n8n_cli.py
new file mode 100644
index 000000000..f36bc3dd8
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/n8n_cli.py
@@ -0,0 +1,1793 @@
+"""cli-anything-n8n — CLI for n8n workflow automation.
+
+Based on n8n Public API v1.1.1 (n8n >= 1.0.0).
+Verified against n8n 2.43.0.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import shlex
+import sys
+import time
+from pathlib import Path
+from typing import Any
+from urllib.parse import urlparse
+
+import click
+import requests
+
+from cli_anything.n8n.core import (
+ credentials,
+ executions,
+ expressions,
+ nodes,
+ project,
+ scaffolds,
+ tags,
+ templates,
+ variables,
+ versions,
+ workflows,
+)
+from cli_anything.n8n.utils.repl_skin import error, output, print_banner, success, warn
+
+
+CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
+VERSION = "2.4.6"
+
+
+def _safe_filename(name: str) -> str:
+ """Sanitize a string for use as a filename."""
+ name = re.sub(r'[<>:"/\\|?*]', '', name)
+ name = re.sub(r'[\s/\\]+', '_', name)
+ return name[:60] or "workflow"
+
+
+# Fields to strip when sending workflow data to n8n API
+_INTERNAL_FIELDS = frozenset({"id", "createdAt", "updatedAt", "versionId", "shared"})
+
+
+def _conn(ctx: click.Context) -> dict[str, str]:
+ """Extract connection kwargs from Click context."""
+ return {"base_url": ctx.obj["base_url"], "api_key": ctx.obj["api_key"]}
+
+
+def _json_flag(ctx: click.Context) -> bool:
+ return ctx.obj.get("as_json", False)
+
+
+def _clean_for_api(data: dict[str, Any]) -> dict[str, Any]:
+ """Remove n8n internal fields before sending to API."""
+ return {k: v for k, v in data.items() if k not in _INTERNAL_FIELDS}
+
+
+def _auto_snapshot(workflow_id: str, conn: dict[str, str], trigger: str) -> None:
+ """Save a version snapshot before modifying a workflow."""
+ try:
+ wf_data = workflows.get_workflow(workflow_id, **conn)
+ ver = versions.save_snapshot(workflow_id, wf_data, trigger)
+ click.secho(f" (snapshot v{ver} saved)", fg="bright_black")
+ except (requests.exceptions.RequestException, OSError):
+ warn("Could not save snapshot before this change")
+
+
+def _load_json_arg(value: str) -> dict[str, Any]:
+ """Parse a JSON string or read from file if prefixed with @. Must return dict."""
+ if value.startswith("@"):
+ filepath = Path(value[1:]).resolve()
+ try:
+ with open(filepath) as f:
+ data = json.load(f)
+ except FileNotFoundError:
+ raise ValueError(f"File not found: {filepath}")
+ except json.JSONDecodeError as e:
+ raise ValueError(f"Invalid JSON in {filepath}: {e}")
+ else:
+ try:
+ data = json.loads(value)
+ except json.JSONDecodeError as e:
+ raise ValueError(f"Invalid JSON: {e}")
+ if not isinstance(data, dict):
+ raise ValueError("JSON must be an object, not array or primitive")
+ return data
+
+
+# ─── Root ───────────────────────────────────────────────────────────────────
+
[email protected](context_settings=CONTEXT_SETTINGS, invoke_without_command=True)
[email protected]("--url", default=None, envvar="N8N_BASE_URL", help="n8n instance URL")
[email protected]("--api-key", default=None, envvar="N8N_API_KEY", help="n8n API key")
[email protected]("--json", "as_json", is_flag=True, default=False, help="JSON output")
[email protected]_option(version=VERSION, prog_name="cli-anything-n8n")
+def cli(ctx: click.Context, url: str | None, api_key: str | None, as_json: bool) -> None:
+ """CLI harness for n8n workflow automation (API v1.1.1, n8n >= 1.0.0)."""
+ ctx.ensure_object(dict)
+ resolved_url, resolved_key = project.get_connection(url, api_key)
+ ctx.obj["base_url"] = resolved_url
+ ctx.obj["api_key"] = resolved_key
+ ctx.obj["as_json"] = as_json
+ if ctx.invoked_subcommand is None:
+ ctx.invoke(repl)
+
+
+# ─── REPL ───────────────────────────────────────────────────────────────────
+
[email protected]("repl", hidden=True)
+def repl(ctx: click.Context) -> None:
+ """Start interactive REPL."""
+ try:
+ from prompt_toolkit import PromptSession
+ from prompt_toolkit.completion import WordCompleter
+ from prompt_toolkit.history import InMemoryHistory
+ except ImportError:
+ click.echo("prompt-toolkit is required for REPL mode. Install: pip install prompt-toolkit")
+ sys.exit(1)
+
+ base_url = ctx.obj["base_url"]
+ print_banner(base_url or "(not configured)")
+
+ # Build completer from all CLI commands
+ words = ["help", "exit", "quit", "status"]
+ for name, cmd in cli.commands.items():
+ if getattr(cmd, "hidden", False):
+ continue
+ words.append(name)
+ if hasattr(cmd, "commands"):
+ for sub in cmd.commands:
+ words.append(f"{name} {sub}")
+ completer = WordCompleter(words, ignore_case=True)
+
+ session = PromptSession(history=InMemoryHistory(), completer=completer)
+ while True:
+ try:
+ line = session.prompt("n8n> ").strip()
+ except (EOFError, KeyboardInterrupt):
+ click.echo("\nBye!")
+ break
+ if not line:
+ continue
+ if line in ("exit", "quit", "q"):
+ click.echo("Bye!")
+ break
+ if line == "help":
+ click.echo(cli.get_help(ctx))
+ continue
+ try:
+ try:
+ args = shlex.split(line)
+ except ValueError:
+ args = line.split()
+ cli.main(args, standalone_mode=False, obj=ctx.obj)
+ except click.exceptions.UsageError as exc:
+ error(str(exc))
+ except SystemExit:
+ pass
+ except Exception as exc:
+ error(str(exc))
+
+
+# ─── Config ─────────────────────────────────────────────────────────────────
+
+def config_() -> None:
+ """Configuration management."""
+
+
+@config_.command("show")
+def config_show(ctx: click.Context) -> None:
+ """Show current configuration (API key is always masked)."""
+ cfg = project.load_config()
+ masked = {**cfg}
+ if masked.get("api_key"):
+ masked["api_key"] = "****configured****"
+ output(masked, _json_flag(ctx))
+
+
+@config_.command("set")
+def config_set(ctx: click.Context, key: str, value: str) -> None:
+ """Set a config value (base_url, api_key)."""
+ cfg = project.load_config()
+ if key not in ("base_url", "api_key"):
+ error(f"Unknown config key: {key}. Use: base_url, api_key")
+ return
+ if key == "base_url":
+ parsed = urlparse(value)
+ if not parsed.scheme or not parsed.netloc:
+ error(f"Invalid URL: {value} (must include http:// or https://)")
+ return
+ cfg[key] = value
+ path = project.save_config(cfg)
+ success(f"Saved {key} to {path}")
+
+
+@config_.command("test")
+def config_test(ctx: click.Context) -> None:
+ """Test connection to your n8n instance."""
+ conn = _conn(ctx)
+ if not conn["base_url"]:
+ error("No URL configured. Run: cli-anything-n8n config set base_url https://...")
+ return
+ if not conn["api_key"]:
+ error("No API key configured. Run: cli-anything-n8n config set api_key YOUR_KEY")
+ return
+ try:
+ workflows.list_workflows(**conn, limit=1)
+ success(f"Connected to {conn['base_url']}")
+ click.echo(f" API is responding.")
+ except requests.exceptions.ConnectionError:
+ error(f"Cannot connect to {conn['base_url']}")
+ except requests.exceptions.HTTPError as exc:
+ status_code = exc.response.status_code
+ if status_code == 401:
+ error("API key is invalid or expired.")
+ elif status_code == 403:
+ error("API key does not have permission.")
+ else:
+ error(f"API returned {status_code}")
+
+
+# ─── Shell Completions ─────────────────────────────────────────────────────
+
[email protected]("completions")
[email protected]("shell", type=click.Choice(["bash", "zsh", "fish"]))
+def install_completions(shell: str) -> None:
+ """Generate shell completion script (bash, zsh, fish)."""
+ import subprocess
+ env_var = "_CLI_ANYTHING_N8N_COMPLETE"
+ shell_map = {"bash": "bash_source", "zsh": "zsh_source", "fish": "fish_source"}
+ import os
+ result = subprocess.run(
+ [sys.executable, "-m", "cli_anything.n8n"],
+ capture_output=True, text=True, timeout=5,
+ env={**os.environ, env_var: shell_map[shell]},
+ )
+ if result.stdout:
+ click.echo(result.stdout)
+ click.echo(f"\n# To install, run:", err=True)
+ if shell == "bash":
+ click.echo(f'# cli-anything-n8n completions bash >> ~/.bashrc', err=True)
+ elif shell == "zsh":
+ click.echo(f'# cli-anything-n8n completions zsh >> ~/.zshrc', err=True)
+ elif shell == "fish":
+ click.echo(f'# cli-anything-n8n completions fish > ~/.config/fish/completions/cli-anything-n8n.fish', err=True)
+ else:
+ success(f"Shell completions for {shell} generated. Paste output into your shell config.")
+
+
+# ─── Workflows ──────────────────────────────────────────────────────────────
+
[email protected]("workflow")
+def workflow_() -> None:
+ """Workflow management."""
+
+
+@workflow_.command("list")
[email protected]("--active/--inactive", default=None, help="Filter by active status")
[email protected]("--tags", "tag_filter", default=None, help="Filter by tag names (comma-separated)")
[email protected]("--name", default=None, help="Filter by name (contains)")
[email protected]("--limit", default=50, type=int, help="Max results")
[email protected]("--cursor", default=None, help="Pagination cursor")
+def workflow_list(ctx: click.Context, active: bool | None, tag_filter: str | None, name: str | None, limit: int, cursor: str | None) -> None:
+ """List workflows."""
+ data = workflows.list_workflows(
+ **_conn(ctx), active=active, tags=tag_filter, name=name, limit=limit, cursor=cursor,
+ )
+ output(data, _json_flag(ctx))
+
+
+@workflow_.command("search")
[email protected]("--active/--inactive", default=None, help="Filter by active status")
+def workflow_search(ctx: click.Context, query: str, active: bool | None) -> None:
+ """Search workflows by name (case-insensitive)."""
+ data = workflows.list_workflows(**_conn(ctx), limit=200, active=active)
+ wf_list = data.get("data", []) if isinstance(data, dict) else data
+ query_lower = query.lower()
+ matches = [w for w in wf_list if query_lower in w.get("name", "").lower()]
+ if _json_flag(ctx):
+ output({"data": matches}, True)
+ elif not matches:
+ warn(f"No workflows matching '{query}'")
+ else:
+ click.secho(f" Found {len(matches)} workflow(s) matching '{query}':\n", fg="cyan")
+ for w in matches:
+ status_str = click.style("active", fg="green") if w.get("active") else click.style("inactive", fg="bright_black")
+ click.echo(f" {w.get('id', '?'):>16s} {status_str} {w.get('name', '?')}")
+
+
+@workflow_.command("get")
[email protected]("workflow_id")
+def workflow_get(ctx: click.Context, workflow_id: str) -> None:
+ """Get workflow details."""
+ data = workflows.get_workflow(workflow_id, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@workflow_.command("create")
[email protected]("json_data")
+def workflow_create(ctx: click.Context, json_data: str) -> None:
+ """Create a workflow from JSON (inline or @file.json). Workflows are created inactive."""
+ payload = _load_json_arg(json_data)
+ payload.pop("active", None) # Never auto-activate on create
+ data = workflows.create_workflow(payload, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@workflow_.command("update")
[email protected]("workflow_id")
[email protected]("json_data")
+def workflow_update(ctx: click.Context, workflow_id: str, json_data: str) -> None:
+ """Update a workflow. Does not change active status — use activate/deactivate."""
+ _auto_snapshot(workflow_id, _conn(ctx), "update")
+ payload = _load_json_arg(json_data)
+ payload.pop("active", None) # Don't change active status via update
+ data = workflows.update_workflow(workflow_id, payload, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@workflow_.command("delete")
[email protected]("workflow_id")
[email protected]_option(prompt="Are you sure you want to delete this workflow?")
+def workflow_delete(ctx: click.Context, workflow_id: str) -> None:
+ """Delete a workflow."""
+ workflows.delete_workflow(workflow_id, **_conn(ctx))
+ success(f"Workflow {workflow_id} deleted")
+
+
+@workflow_.command("activate")
[email protected]("workflow_id")
+def workflow_activate(ctx: click.Context, workflow_id: str) -> None:
+ """Activate a workflow."""
+ data = workflows.activate_workflow(workflow_id, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@workflow_.command("deactivate")
[email protected]("workflow_id")
+def workflow_deactivate(ctx: click.Context, workflow_id: str) -> None:
+ """Deactivate a workflow."""
+ data = workflows.deactivate_workflow(workflow_id, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@workflow_.command("tags")
[email protected]("workflow_id")
+def workflow_tags(ctx: click.Context, workflow_id: str) -> None:
+ """Get workflow tags."""
+ data = workflows.get_workflow_tags(workflow_id, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@workflow_.command("set-tags")
[email protected]("workflow_id")
[email protected]("json_data", metavar="TAG_IDS_JSON")
+def workflow_set_tags(ctx: click.Context, workflow_id: str, json_data: str) -> None:
+ """Set workflow tags (JSON array of {id} objects)."""
+ try:
+ tag_ids = json.loads(json_data)
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"Invalid JSON: {exc}") from exc
+ if not isinstance(tag_ids, list):
+ raise ValueError("JSON must be an array of {id} objects")
+ data = workflows.update_workflow_tags(workflow_id, tag_ids, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@workflow_.command("transfer")
[email protected]("workflow_id")
[email protected]("project_id")
+def workflow_transfer(ctx: click.Context, workflow_id: str, project_id: str) -> None:
+ """Transfer a workflow to another project."""
+ workflows.transfer_workflow(workflow_id, project_id, **_conn(ctx))
+ success(f"Workflow {workflow_id} transferred to project {project_id}")
+
+
+@workflow_.command("export")
[email protected]("workflow_id")
[email protected]("-o", "--output", "out_path", default=None, help="Output file (default: <name>.json)")
+def workflow_export(ctx: click.Context, workflow_id: str, out_path: str | None) -> None:
+ """Export a workflow to a JSON file."""
+ data = workflows.get_workflow(workflow_id, **_conn(ctx))
+ if not out_path:
+ name = _safe_filename(data.get("name", workflow_id))
+ out_path = f"{name}.json"
+ # Remove server-specific fields for portability
+ export_data = _clean_for_api(data)
+ out = Path(out_path)
+ if out.exists():
+ warn(f"File {out_path} already exists — overwriting")
+ out.write_text(json.dumps(export_data, indent=2, default=str))
+ success(f"Exported to {out_path}")
+
+
+@workflow_.command("import")
[email protected]("file_path", type=click.Path(exists=True))
[email protected]("--name", default=None, help="Override workflow name")
+def workflow_import(ctx: click.Context, file_path: str, name: str | None) -> None:
+ """Import a workflow from a JSON file."""
+ with open(file_path) as f:
+ data = json.load(f)
+ if not isinstance(data, dict):
+ error("Invalid workflow format: must be a JSON object, not array or string")
+ return
+ # Remove fields that would conflict on import
+ for field in ("id", "createdAt", "updatedAt", "versionId", "shared"):
+ data.pop(field, None)
+ data["active"] = False # Never auto-activate imported workflows
+ if name:
+ data["name"] = name
+ result = workflows.create_workflow(data, **_conn(ctx))
+ success(f"Imported as workflow {result.get('id', '?')} — {result.get('name', '?')}")
+ output(result, _json_flag(ctx))
+
+
+@workflow_.command("backup-all")
[email protected]("-d", "--dir", "out_dir", default="n8n-backup", help="Output directory (default: n8n-backup)")
[email protected]("--active-only", is_flag=True, default=False, help="Only backup active workflows")
+def workflow_backup_all(ctx: click.Context, out_dir: str, active_only: bool) -> None:
+ """Backup ALL workflows to a folder (one JSON per workflow)."""
+ conn = _conn(ctx)
+ # Paginate to get ALL workflows, not just first page
+ wf_list: list[dict] = []
+ cursor = None
+ seen_cursors: set[str] = set()
+ for _ in range(100): # Max 100 pages (10,000 workflows)
+ data = workflows.list_workflows(**conn, limit=100, cursor=cursor, active=True if active_only else None)
+ page = data.get("data", []) if isinstance(data, dict) else data
+ wf_list.extend(page)
+ cursor = data.get("nextCursor") if isinstance(data, dict) else None
+ if not cursor or not page or cursor in seen_cursors:
+ break
+ seen_cursors.add(cursor)
+
+ if not wf_list:
+ warn("No workflows found")
+ return
+
+ out_path = Path(out_dir)
+ out_path.mkdir(parents=True, exist_ok=True)
+
+ click.echo(f" Backing up {len(wf_list)} workflow(s) to {out_dir}/\n")
+ ok, fail = 0, 0
+ for w in wf_list:
+ wf_id = w.get("id", "unknown")
+ try:
+ full = workflows.get_workflow(wf_id, **conn)
+ export_data = _clean_for_api(full)
+ name_safe = _safe_filename(full.get("name", wf_id))
+ filename = f"{wf_id}_{name_safe}.json"
+ (out_path / filename).write_text(json.dumps(export_data, indent=2, default=str))
+ click.secho(f" {wf_id} {full.get('name', '?')}", fg="green")
+ ok += 1
+ except Exception as exc:
+ click.secho(f" {wf_id} FAILED — {exc}", fg="red")
+ fail += 1
+
+ # Write manifest
+ manifest = {"backup_date": time.strftime("%Y-%m-%dT%H:%M:%S"), "count": ok, "failed": fail, "workflows": [w.get("id") for w in wf_list]}
+ (out_path / "_manifest.json").write_text(json.dumps(manifest, indent=2))
+
+ click.echo()
+ success(f"Backed up {ok} workflows to {out_dir}/ ({fail} failed)")
+
+
+@workflow_.command("restore-all")
[email protected]("backup_dir", type=click.Path(exists=True))
[email protected]("--dry-run", is_flag=True, default=False, help="Show what would be imported without doing it")
+def workflow_restore_all(ctx: click.Context, backup_dir: str, dry_run: bool) -> None:
+ """Restore workflows from a backup folder."""
+ conn = _conn(ctx)
+ backup_path = Path(backup_dir)
+ backup_resolved = backup_path.resolve()
+ json_files = sorted(backup_path.glob("*.json"))
+ # Filter manifest and symlinks pointing outside backup dir
+ json_files = [f for f in json_files if f.name != "_manifest.json" and f.resolve().is_relative_to(backup_resolved)]
+
+ if not json_files:
+ warn(f"No JSON files found in {backup_dir}/")
+ return
+
+ click.echo(f" {'[DRY RUN] ' if dry_run else ''}Restoring {len(json_files)} workflow(s) from {backup_dir}/\n")
+ ok, fail = 0, 0
+ for f in json_files:
+ try:
+ data = json.loads(f.read_text())
+ if not isinstance(data, dict):
+ raise ValueError("Not a valid workflow JSON object")
+ name = data.get("name", f.stem)
+ if dry_run:
+ click.echo(f" Would import: {name}")
+ ok += 1
+ continue
+ for field in ("id", "createdAt", "updatedAt", "versionId", "shared"):
+ data.pop(field, None)
+ data["active"] = False # Never auto-activate restored workflows
+ result = workflows.create_workflow(data, **conn)
+ click.secho(f" {result.get('id', '?')} {name}", fg="green")
+ ok += 1
+ except Exception as exc:
+ click.secho(f" {f.name} FAILED — {exc}", fg="red")
+ fail += 1
+
+ click.echo()
+ if dry_run:
+ success(f"Would restore {ok} workflows ({fail} would fail)")
+ else:
+ success(f"Restored {ok} workflows ({fail} failed)")
+
+
+@workflow_.command("diff")
+def workflow_diff(ctx: click.Context, source: str, target: str) -> None:
+ """Compare two workflows. Use workflow IDs or @file.json paths.
+
+ Examples: diff ABC123 DEF456, diff ABC123 @local.json, diff @a.json @b.json
+ """
+ import difflib
+ conn = _conn(ctx)
+
+ def _load(ref: str) -> dict:
+ if ref.startswith("@"):
+ return _load_json_arg(ref)
+ return workflows.get_workflow(ref, **conn)
+
+ def _clean(data: dict) -> dict:
+ return _clean_for_api(data)
+
+ src = _clean(_load(source))
+ tgt = _clean(_load(target))
+
+ src_lines = json.dumps(src, indent=2, sort_keys=True, default=str).splitlines(keepends=True)
+ tgt_lines = json.dumps(tgt, indent=2, sort_keys=True, default=str).splitlines(keepends=True)
+
+ src_label = source if source.startswith("@") else f"workflow:{source}"
+ tgt_label = target if target.startswith("@") else f"workflow:{target}"
+
+ diff = list(difflib.unified_diff(src_lines, tgt_lines, fromfile=src_label, tofile=tgt_label, lineterm=""))
+
+ if not diff:
+ success("Workflows are identical")
+ return
+
+ for line in diff:
+ if line.startswith("+++") or line.startswith("---"):
+ click.secho(line, fg="cyan", bold=True)
+ elif line.startswith("+"):
+ click.secho(line, fg="green")
+ elif line.startswith("-"):
+ click.secho(line, fg="red")
+ elif line.startswith("@@"):
+ click.secho(line, fg="cyan")
+ else:
+ click.echo(line)
+
+
+@workflow_.command("bulk-activate")
[email protected]("--tag", default=None, help="Activate all workflows with this tag")
[email protected]("--search", default=None, help="Activate all workflows matching name")
+def workflow_bulk_activate(ctx: click.Context, tag: str | None, search: str | None) -> None:
+ """Activate multiple workflows by tag or name search."""
+ if not tag and not search:
+ error("Provide --tag or --search to select workflows")
+ return
+ conn = _conn(ctx)
+ data = workflows.list_workflows(**conn, tags=tag, limit=200)
+ wf_list = data.get("data", []) if isinstance(data, dict) else data
+ if search:
+ q = search.lower()
+ wf_list = [w for w in wf_list if q in w.get("name", "").lower()]
+ inactive = [w for w in wf_list if not w.get("active")]
+ if not inactive:
+ warn("No inactive workflows found matching criteria")
+ return
+ click.echo(f" Activating {len(inactive)} workflow(s)...")
+ ok, fail = 0, 0
+ for w in inactive:
+ try:
+ workflows.activate_workflow(w.get("id", ""), **conn)
+ click.secho(f" {w.get('id', '?')} {w.get('name', '?')}", fg="green")
+ ok += 1
+ except Exception as exc:
+ click.secho(f" {w.get('id', '?')} {w.get('name', '?')} — {exc}", fg="red")
+ fail += 1
+ success(f"Activated {ok}, failed {fail}")
+
+
+@workflow_.command("bulk-deactivate")
[email protected]("--tag", default=None, help="Deactivate all workflows with this tag")
[email protected]("--search", default=None, help="Deactivate all workflows matching name")
+def workflow_bulk_deactivate(ctx: click.Context, tag: str | None, search: str | None) -> None:
+ """Deactivate multiple workflows by tag or name search."""
+ if not tag and not search:
+ error("Provide --tag or --search to select workflows")
+ return
+ conn = _conn(ctx)
+ data = workflows.list_workflows(**conn, tags=tag, limit=200)
+ wf_list = data.get("data", []) if isinstance(data, dict) else data
+ if search:
+ q = search.lower()
+ wf_list = [w for w in wf_list if q in w.get("name", "").lower()]
+ active = [w for w in wf_list if w.get("active")]
+ if not active:
+ warn("No active workflows found matching criteria")
+ return
+ click.echo(f" Deactivating {len(active)} workflow(s)...")
+ ok, fail = 0, 0
+ for w in active:
+ try:
+ workflows.deactivate_workflow(w.get("id", ""), **conn)
+ click.secho(f" {w.get('id', '?')} {w.get('name', '?')}", fg="bright_black")
+ ok += 1
+ except Exception as exc:
+ click.secho(f" {w.get('id', '?')} {w.get('name', '?')} — {exc}", fg="red")
+ fail += 1
+ success(f"Deactivated {ok}, failed {fail}")
+
+
+# ─── Executions ─────────────────────────────────────────────────────────────
+
[email protected]("execution")
+def execution_() -> None:
+ """Execution management."""
+
+
+@execution_.command("list")
[email protected]("--status", type=click.Choice(["error", "success", "waiting", "running", "new"]), default=None)
[email protected]("--workflow-id", default=None, help="Filter by workflow ID")
[email protected]("--limit", default=20, type=int)
[email protected]("--cursor", default=None)
[email protected]("--include-data", is_flag=True, default=False, help="Include execution data")
+def execution_list(ctx: click.Context, status: str | None, workflow_id: str | None, limit: int, cursor: str | None, include_data: bool) -> None:
+ """List executions."""
+ data = executions.list_executions(
+ **_conn(ctx), status=status, workflow_id=workflow_id, limit=limit, cursor=cursor, include_data=include_data,
+ )
+ output(data, _json_flag(ctx))
+
+
+@execution_.command("get")
[email protected]("execution_id")
[email protected]("--no-data", is_flag=True, default=False, help="Exclude execution data")
+def execution_get(ctx: click.Context, execution_id: str, no_data: bool) -> None:
+ """Get execution details."""
+ data = executions.get_execution(execution_id, **_conn(ctx), include_data=not no_data)
+ output(data, _json_flag(ctx))
+
+
+@execution_.command("delete")
[email protected]("execution_id")
+def execution_delete(ctx: click.Context, execution_id: str) -> None:
+ """Delete an execution."""
+ executions.delete_execution(execution_id, **_conn(ctx))
+ success(f"Execution {execution_id} deleted")
+
+
+@execution_.command("retry")
[email protected]("execution_id")
+def execution_retry(ctx: click.Context, execution_id: str) -> None:
+ """Retry a failed execution."""
+ data = executions.retry_execution(execution_id, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@execution_.command("errors")
[email protected]("--workflow-id", default=None, help="Filter by workflow ID")
[email protected]("--limit", default=10, type=int, help="Number of errors to show")
[email protected]("--details", is_flag=True, default=False, help="Include error message details")
+def execution_errors(ctx: click.Context, workflow_id: str | None, limit: int, details: bool) -> None:
+ """Show recent failed executions (shortcut for list --status error)."""
+ conn = _conn(ctx)
+ data = executions.list_executions(**conn, status="error", workflow_id=workflow_id, limit=limit, include_data=details)
+ err_list = data.get("data", []) if isinstance(data, dict) else data
+
+ if _json_flag(ctx):
+ output(data, True)
+ return
+
+ if not err_list:
+ success("No errors found!")
+ return
+
+ click.secho(f"\n {len(err_list)} recent error(s):\n", fg="red", bold=True)
+ for e in err_list:
+ eid = e.get("id", "?")
+ wf_id = e.get("workflowId", "?")
+ started = str(e.get("startedAt", ""))[:19].replace("T", " ")
+ stopped = str(e.get("stoppedAt", ""))[:19].replace("T", " ")
+ click.echo(f" {click.style(eid, fg='red'):>12s} wf:{wf_id:<16s} {started} -> {stopped}")
+
+ if details and isinstance(e.get("data"), dict):
+ run_data = e["data"].get("resultData", {})
+ error_msg = run_data.get("error", {}).get("message", "")
+ if error_msg:
+ click.secho(f" {error_msg[:120]}", fg="bright_black")
+ click.echo()
+
+
+@execution_.command("watch")
[email protected]("--workflow-id", default=None, help="Filter by workflow ID")
[email protected]("--interval", default=5, type=int, help="Poll interval in seconds (default: 5)")
[email protected]("--limit", default=5, type=int, help="Number of executions to show")
+def execution_watch(ctx: click.Context, workflow_id: str | None, interval: int, limit: int) -> None:
+ """Watch executions in real-time (poll mode). Press Ctrl+C to stop."""
+ import shutil
+ if interval < 1:
+ error("--interval must be at least 1 second")
+ return
+ conn = _conn(ctx)
+ click.secho(f" Watching executions (every {interval}s). Ctrl+C to stop.\n", fg="cyan")
+ seen: set[str] = set()
+ try:
+ while True:
+ data = executions.list_executions(**conn, workflow_id=workflow_id, limit=limit)
+ rows = data.get("data", []) if isinstance(data, dict) else data
+ term_w = shutil.get_terminal_size().columns
+ click.echo(f"\033[2J\033[H", nl=False) # clear screen
+ click.secho(f" n8n executions — {time.strftime('%H:%M:%S')} (every {interval}s, Ctrl+C to stop)\n", fg="cyan")
+ if not rows:
+ click.secho(" No executions found.", fg="bright_black")
+ else:
+ for row in rows:
+ eid = str(row.get("id", ""))
+ status = row.get("status", "?")
+ wf_id = row.get("workflowId", "?")
+ started = str(row.get("startedAt", ""))[:19].replace("T", " ")
+ is_new = eid not in seen
+ seen.add(eid)
+ color = {"success": "green", "error": "red", "running": "yellow", "waiting": "cyan"}.get(status, "white")
+ marker = " *" if is_new else " "
+ line = f"{marker} {eid:>8s} {click.style(status.ljust(8), fg=color)} wf:{wf_id:<16s} {started}"
+ click.echo(line[:term_w])
+ time.sleep(interval)
+ except KeyboardInterrupt:
+ click.echo("\n Stopped.")
+
+
+# ─── Status Dashboard ──────────────────────────────────────────────────────
+
+def status_dashboard(ctx: click.Context) -> None:
+ """Show a quick overview of your n8n instance."""
+ conn = _conn(ctx)
+ as_json = _json_flag(ctx)
+
+ wf_data = workflows.list_workflows(**conn, limit=200)
+ wf_list = wf_data.get("data", []) if isinstance(wf_data, dict) else wf_data
+ active_wfs = [w for w in wf_list if w.get("active")]
+ inactive_wfs = [w for w in wf_list if not w.get("active")]
+
+ exec_data = executions.list_executions(**conn, limit=10)
+ exec_list = exec_data.get("data", []) if isinstance(exec_data, dict) else exec_data
+ errors = [e for e in exec_list if e.get("status") == "error"]
+
+ if as_json:
+ output({
+ "workflows": {"total": len(wf_list), "active": len(active_wfs), "inactive": len(inactive_wfs)},
+ "recent_executions": len(exec_list),
+ "recent_errors": len(errors),
+ "last_error": errors[0] if errors else None,
+ }, True)
+ return
+
+ click.echo()
+ click.secho(" n8n Status Dashboard", fg="cyan", bold=True)
+ click.secho(" " + "=" * 40, fg="cyan")
+ click.echo()
+
+ click.secho(" Workflows", fg="cyan", bold=True)
+ click.echo(f" Total: {len(wf_list)}")
+ click.secho(f" Active: {len(active_wfs)}", fg="green")
+ click.echo(f" Inactive: {len(inactive_wfs)}")
+ click.echo()
+
+ click.secho(" Recent Executions (last 10)", fg="cyan", bold=True)
+ if not exec_list:
+ click.secho(" No executions found.", fg="bright_black")
+ else:
+ for e in exec_list:
+ status = e.get("status", "?")
+ color = {"success": "green", "error": "red", "running": "yellow", "waiting": "cyan"}.get(status, "white")
+ started = str(e.get("startedAt", ""))[:19].replace("T", " ")
+ click.echo(f" {e.get('id', '?'):>8s} {click.style(status.ljust(8), fg=color)} wf:{e.get('workflowId', '?'):<16s} {started}")
+ click.echo()
+
+ if errors:
+ click.secho(f" Errors: {len(errors)} in last 10 executions", fg="red", bold=True)
+ last = errors[0]
+ click.echo(f" Last error: execution {last.get('id')} (wf:{last.get('workflowId')}) at {str(last.get('startedAt', ''))[:19]}")
+ else:
+ click.secho(" No errors in recent executions", fg="green")
+ click.echo()
+
+
+# ─── Credentials ────────────────────────────────────────────────────────────
+
[email protected]("credential")
+def credential_() -> None:
+ """Credential management (limited by n8n API — no list/update)."""
+
+
+@credential_.command("create")
[email protected]("json_data")
+def credential_create(ctx: click.Context, json_data: str) -> None:
+ """Create a credential from JSON."""
+ data = credentials.create_credential(_load_json_arg(json_data), **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@credential_.command("delete")
[email protected]("credential_id")
[email protected]_option(prompt="Are you sure you want to delete this credential?")
+def credential_delete(ctx: click.Context, credential_id: str) -> None:
+ """Delete a credential."""
+ credentials.delete_credential(credential_id, **_conn(ctx))
+ success(f"Credential {credential_id} deleted")
+
+
+@credential_.command("schema")
[email protected]("credential_type")
+def credential_schema(ctx: click.Context, credential_type: str) -> None:
+ """Get credential schema for a type."""
+ data = credentials.get_credential_schema(credential_type, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@credential_.command("transfer")
[email protected]("credential_id")
[email protected]("project_id")
+def credential_transfer(ctx: click.Context, credential_id: str, project_id: str) -> None:
+ """Transfer a credential to another project."""
+ credentials.transfer_credential(credential_id, project_id, **_conn(ctx))
+ success(f"Credential {credential_id} transferred to project {project_id}")
+
+
+# ─── Variables ──────────────────────────────────────────────────────────────
+
[email protected]("variable")
+def variable_() -> None:
+ """Variable management."""
+
+
+@variable_.command("list")
+def variable_list(ctx: click.Context) -> None:
+ """List all variables."""
+ data = variables.list_variables(**_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@variable_.command("create")
+def variable_create(ctx: click.Context, key: str, value: str) -> None:
+ """Create a variable."""
+ data = variables.create_variable(key, value, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@variable_.command("update")
[email protected]("variable_id")
+def variable_update(ctx: click.Context, variable_id: str, key: str, value: str) -> None:
+ """Update a variable."""
+ data = variables.update_variable(variable_id, key, value, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@variable_.command("delete")
[email protected]("variable_id")
+def variable_delete(ctx: click.Context, variable_id: str) -> None:
+ """Delete a variable."""
+ variables.delete_variable(variable_id, **_conn(ctx))
+ success(f"Variable {variable_id} deleted")
+
+
+# ─── Tags ───────────────────────────────────────────────────────────────────
+
+def tag_() -> None:
+ """Tag management."""
+
+
+@tag_.command("list")
[email protected]("--limit", default=50, type=int)
+def tag_list(ctx: click.Context, limit: int) -> None:
+ """List all tags."""
+ data = tags.list_tags(**_conn(ctx), limit=limit)
+ output(data, _json_flag(ctx))
+
+
+@tag_.command("get")
+def tag_get(ctx: click.Context, tag_id: str) -> None:
+ """Get tag details."""
+ data = tags.get_tag(tag_id, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@tag_.command("create")
+def tag_create(ctx: click.Context, name: str) -> None:
+ """Create a tag."""
+ data = tags.create_tag(name, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@tag_.command("update")
+def tag_update(ctx: click.Context, tag_id: str, name: str) -> None:
+ """Update a tag name."""
+ data = tags.update_tag(tag_id, name, **_conn(ctx))
+ output(data, _json_flag(ctx))
+
+
+@tag_.command("delete")
+def tag_delete(ctx: click.Context, tag_id: str) -> None:
+ """Delete a tag."""
+ tags.delete_tag(tag_id, **_conn(ctx))
+ success(f"Tag {tag_id} deleted")
+
+
+# ─── Templates (n8n.io) ─────────────────────────────────────────────────────
+
[email protected]("template")
+def template_() -> None:
+ """Browse and deploy templates from n8n.io (2,700+ templates)."""
+
+
+@template_.command("search")
[email protected]("--limit", default=10, type=int, help="Max results")
+def template_search(ctx: click.Context, query: str, limit: int) -> None:
+ """Search templates on n8n.io by keyword."""
+ data = templates.search_templates(query, limit=limit)
+ wfs = data.get("workflows", [])
+
+ if _json_flag(ctx):
+ output(data, True)
+ return
+
+ total = data.get("totalWorkflows", 0)
+ click.secho(f"\n {total} templates found for '{query}' (showing {len(wfs)}):\n", fg="cyan")
+ for w in wfs:
+ views = w.get("totalViews", 0)
+ click.echo(f" {click.style(str(w.get('id', '?')), fg='cyan'):>8s} {w.get('name', '?')[:60]}")
+ click.secho(f" {views:,} views by {w.get('user', {}).get('username', '?')}", fg="bright_black")
+ click.echo()
+
+
+@template_.command("get")
[email protected]("template_id", type=int)
+def template_get(ctx: click.Context, template_id: int) -> None:
+ """Get template details from n8n.io."""
+ data = templates.get_template(template_id)
+ wf = data.get("workflow", {})
+ if _json_flag(ctx):
+ output(data, True)
+ return
+ click.secho(f"\n Template #{template_id}: {wf.get('name', '?')}", fg="cyan", bold=True)
+ click.echo(f" Nodes: {len(wf.get('nodes', []))}")
+ click.echo(f" Views: {wf.get('totalViews', 0):,}")
+ desc = data.get("description", "")
+ if desc:
+ click.echo(f" Description: {desc[:200]}")
+ click.echo()
+
+
+@template_.command("deploy")
[email protected]("template_id", type=int)
[email protected]("--name", default=None, help="Override workflow name")
+def template_deploy(ctx: click.Context, template_id: int, name: str | None) -> None:
+ """Deploy a template from n8n.io directly to your n8n instance."""
+ conn = _conn(ctx)
+ click.echo(f" Fetching template #{template_id} from n8n.io...")
+ data = templates.get_template(template_id)
+ # n8n.io API nests workflow data under "workflow" key
+ wf_wrapper = data.get("workflow", {})
+ wf_data = wf_wrapper.get("workflow", wf_wrapper) if isinstance(wf_wrapper, dict) else {}
+
+ # Clean for import — never auto-activate
+ for field in ("id", "createdAt", "updatedAt", "versionId", "shared"):
+ wf_data.pop(field, None)
+ wf_data["active"] = False
+ if name:
+ wf_data["name"] = name
+ elif not wf_data.get("name"):
+ wf_data["name"] = f"Template #{template_id}"
+
+ result = workflows.create_workflow(wf_data, **conn)
+ success(f"Deployed as workflow {result.get('id', '?')} — {result.get('name', '?')}")
+ output(result, _json_flag(ctx))
+
+
+# ─── Workflow Validate ──────────────────────────────────────────────────────
+
+@workflow_.command("validate")
+def workflow_validate(ctx: click.Context, source: str) -> None:
+ """Validate a workflow structure. Use workflow ID or @file.json."""
+ conn = _conn(ctx)
+
+ if source.startswith("@"):
+ data = _load_json_arg(source)
+ else:
+ data = workflows.get_workflow(source, **conn)
+
+ issues: list[str] = []
+ warnings: list[str] = []
+
+ # Check basic structure
+ if not data.get("name"):
+ issues.append("Missing workflow name")
+ if not data.get("nodes"):
+ issues.append("No nodes defined")
+ if not isinstance(data.get("connections", {}), dict):
+ issues.append("Invalid connections format (must be object)")
+
+ nodes = data.get("nodes", [])
+ if not isinstance(nodes, list):
+ issues.append("Invalid nodes format (must be array)")
+ nodes = []
+ nodes = [n for n in nodes if isinstance(n, dict)]
+ node_names = {n.get("name") for n in nodes}
+
+ # Check each node
+ trigger_count = 0
+ for node in nodes:
+ if not node.get("type"):
+ issues.append(f"Node '{node.get('name', '?')}' has no type")
+ if not node.get("name"):
+ issues.append(f"Node of type '{node.get('type', '?')}' has no name")
+ node_type_lower = node.get("type", "").lower()
+ if "trigger" in node_type_lower or "webhook" in node_type_lower:
+ trigger_count += 1
+
+ if trigger_count == 0:
+ warnings.append("No trigger node found — workflow cannot be activated")
+ if trigger_count > 1:
+ warnings.append(f"Multiple trigger nodes ({trigger_count}) — only one should be active")
+
+ # Check connections reference existing nodes
+ for source_node, conns in data.get("connections", {}).items():
+ if source_node not in node_names:
+ issues.append(f"Connection from non-existent node: '{source_node}'")
+ if isinstance(conns, dict):
+ for conn_type, outputs in conns.items():
+ if isinstance(outputs, list):
+ for output_list in outputs:
+ if isinstance(output_list, list):
+ for target in output_list:
+ if not isinstance(target, dict):
+ continue
+ target_name = target.get("node", "")
+ if target_name and target_name not in node_names:
+ issues.append(f"Connection to non-existent node: '{target_name}'")
+
+ # Check for duplicate node names
+ seen_names: set[str] = set()
+ for node in nodes:
+ name = node.get("name", "")
+ if name in seen_names:
+ issues.append(f"Duplicate node name: '{name}'")
+ seen_names.add(name)
+
+ if _json_flag(ctx):
+ output({"valid": len(issues) == 0, "issues": issues, "warnings": warnings}, True)
+ return
+
+ if issues:
+ click.secho(f"\n INVALID — {len(issues)} issue(s):\n", fg="red", bold=True)
+ for i in issues:
+ click.secho(f" {i}", fg="red")
+ else:
+ click.secho(f"\n VALID", fg="green", bold=True)
+
+ if warnings:
+ click.secho(f"\n {len(warnings)} warning(s):", fg="yellow")
+ for w in warnings:
+ click.secho(f" {w}", fg="yellow")
+
+ if not issues and not warnings:
+ click.echo(f" {len(nodes)} nodes, {trigger_count} trigger(s)")
+ click.echo()
+
+
+# ─── Workflow Autofix ───────────────────────────────────────────────────────
+
+@workflow_.command("autofix")
[email protected]("--apply", is_flag=True, default=False, help="Apply fixes (default: preview only)")
[email protected]("--save", "save_path", default=None, help="Save fixed workflow to file instead of updating n8n")
+def workflow_autofix(ctx: click.Context, source: str, apply: bool, save_path: str | None) -> None:
+ """Auto-fix common workflow issues. Preview by default, --apply to save.
+
+ Fixes: expression format, webhook paths, broken connections, duplicate names,
+ connection types, unused error outputs.
+ """
+ from cli_anything.n8n.core.fixers import autofix
+
+ conn = _conn(ctx)
+ if source.startswith("@"):
+ wf_data = _load_json_arg(source)
+ wf_id = None
+ else:
+ wf_data = workflows.get_workflow(source, **conn)
+ wf_id = source
+
+ import copy
+ wf_copy = copy.deepcopy(wf_data)
+ fixed_wf, fixes = autofix(wf_copy, apply=True)
+
+ if _json_flag(ctx):
+ output({"fixes": [{"type": f.fix_type, "description": f.description, "confidence": f.confidence, "node": f.node_name} for f in fixes], "total": len(fixes), "applied": apply or bool(save_path)}, True)
+ return
+
+ if not fixes:
+ success("No issues found!")
+ return
+
+ click.secho(f"\n Found {len(fixes)} issue(s):\n", fg="yellow", bold=True)
+ for f in fixes:
+ color = {"HIGH": "red", "MEDIUM": "yellow", "LOW": "bright_black"}.get(f.confidence, "white")
+ node_str = f" [{f.node_name}]" if f.node_name else ""
+ click.echo(f" {click.style(f.confidence, fg=color):>8s} {f.fix_type:30s}{node_str}")
+ click.secho(f" {f.description}", fg="bright_black")
+
+ if save_path:
+ Path(save_path).write_text(json.dumps(fixed_wf, indent=2, default=str))
+ success(f"Fixed workflow saved to {save_path}")
+ elif apply and wf_id:
+ _auto_snapshot(wf_id, conn, "autofix")
+ update_data = _clean_for_api(fixed_wf)
+ workflows.update_workflow(wf_id, update_data, **conn)
+ success(f"Applied {len(fixes)} fix(es) to workflow {wf_id}")
+ elif apply and not wf_id:
+ error("Cannot apply fixes to a file source. Use --save instead.")
+ else:
+ warn("Preview only. Use --apply to fix in n8n, or --save to save to file.")
+ click.echo()
+
+
+# ─── Workflow Patch (incremental updates) ───────────────────────────────────
+
+@workflow_.command("patch")
[email protected]("workflow_id")
[email protected]("--rename", default=None, help="Rename the workflow")
[email protected]("--enable-node", default=None, help="Enable a disabled node by name")
[email protected]("--disable-node", default=None, help="Disable a node by name")
[email protected]("--remove-node", default=None, help="Remove a node by name (and its connections)")
[email protected]("--connect", nargs=2, default=None, help="Connect two nodes: --connect SOURCE TARGET")
[email protected]("--disconnect", nargs=2, default=None, help="Disconnect two nodes: --disconnect SOURCE TARGET")
+def workflow_patch(ctx: click.Context, workflow_id: str, rename: str | None, enable_node: str | None, disable_node: str | None, remove_node: str | None, connect: tuple[str, str] | None, disconnect: tuple[str, str] | None) -> None:
+ """Apply incremental changes to a workflow without replacing it entirely."""
+ conn = _conn(ctx)
+ wf = workflows.get_workflow(workflow_id, **conn)
+ nodes = wf.get("nodes", [])
+ if not isinstance(nodes, list):
+ nodes = []
+ connections = wf.get("connections", {})
+ if not isinstance(connections, dict):
+ connections = {}
+ changed = False
+
+ if rename:
+ wf["name"] = rename
+ changed = True
+ success(f"Renamed to '{rename}'")
+
+ if enable_node:
+ for n in nodes:
+ if isinstance(n, dict) and n.get("name") == enable_node:
+ n["disabled"] = False
+ changed = True
+ success(f"Enabled node '{enable_node}'")
+ break
+ else:
+ error(f"Node '{enable_node}' not found")
+ return
+
+ if disable_node:
+ for n in nodes:
+ if isinstance(n, dict) and n.get("name") == disable_node:
+ n["disabled"] = True
+ changed = True
+ success(f"Disabled node '{disable_node}'")
+ break
+ else:
+ error(f"Node '{disable_node}' not found")
+ return
+
+ if remove_node:
+ original_len = len(nodes)
+ wf["nodes"] = [n for n in nodes if isinstance(n, dict) and n.get("name") != remove_node]
+ if len(wf["nodes"]) == original_len:
+ error(f"Node '{remove_node}' not found")
+ return
+ # Clean connections
+ connections.pop(remove_node, None)
+ for src_conns in connections.values():
+ if isinstance(src_conns, dict):
+ for outputs in src_conns.values():
+ if isinstance(outputs, list):
+ for output_list in outputs:
+ if isinstance(output_list, list):
+ output_list[:] = [t for t in output_list if isinstance(t, dict) and t.get("node") != remove_node]
+ changed = True
+ success(f"Removed node '{remove_node}' and its connections")
+
+ if connect:
+ src, tgt = connect
+ node_names = {n.get("name") for n in wf.get("nodes", []) if isinstance(n, dict)}
+ if src not in node_names:
+ error(f"Source node '{src}' not found")
+ return
+ if tgt not in node_names:
+ error(f"Target node '{tgt}' not found")
+ return
+ src_conns = connections.setdefault(src, {})
+ main_outputs = src_conns.get("main")
+ if not isinstance(main_outputs, list):
+ main_outputs = [[]]
+ src_conns["main"] = main_outputs
+ elif not main_outputs or not isinstance(main_outputs[0], list):
+ main_outputs.insert(0, [])
+ main_outputs[0].append({"node": tgt, "type": "main", "index": 0})
+ changed = True
+ success(f"Connected '{src}' -> '{tgt}'")
+
+ if disconnect:
+ src, tgt = disconnect
+ if src in connections and isinstance(connections[src], dict):
+ for outputs in connections[src].values():
+ if isinstance(outputs, list):
+ for output_list in outputs:
+ if isinstance(output_list, list):
+ output_list[:] = [t for t in output_list if isinstance(t, dict) and t.get("node") != tgt]
+ changed = True
+ success(f"Disconnected '{src}' -> '{tgt}'")
+ else:
+ error(f"No connections from '{src}'")
+ return
+
+ if not changed:
+ error("No operations specified. Use --rename, --enable-node, --disable-node, --remove-node, --connect, or --disconnect")
+ return
+
+ _auto_snapshot(workflow_id, conn, "patch")
+ update_data = _clean_for_api(wf)
+ result = workflows.update_workflow(workflow_id, update_data, **conn)
+ output(result, _json_flag(ctx))
+
+
+# ─── Health Check ───────────────────────────────────────────────────────────
+
[email protected]("--diagnostic", is_flag=True, default=False, help="Show detailed diagnostic info")
+def health_check(ctx: click.Context, diagnostic: bool) -> None:
+ """Check n8n instance health and connectivity."""
+ conn = _conn(ctx)
+ base_url = conn["base_url"]
+
+ if not base_url:
+ error("No URL configured.")
+ return
+
+ results: dict[str, Any] = {"url": base_url, "status": "unknown"}
+
+ # Test connectivity and measure response time
+ start = time.time()
+ try:
+ wf_data = workflows.list_workflows(**conn, limit=1)
+ elapsed = round((time.time() - start) * 1000)
+ results["status"] = "connected"
+ results["response_ms"] = elapsed
+
+ wf_list = wf_data.get("data", []) if isinstance(wf_data, dict) else wf_data
+ results["has_workflows"] = len(wf_list) > 0
+ except requests.exceptions.ConnectionError:
+ results["status"] = "unreachable"
+ except requests.exceptions.HTTPError as exc:
+ results["status"] = f"error_{exc.response.status_code}"
+
+ # Try to get n8n version via healthz endpoint
+ try:
+ resp = requests.get(f"{base_url}/healthz", timeout=5)
+ if resp.ok:
+ health = resp.json() if resp.headers.get("content-type", "").startswith("application/json") else {}
+ results["n8n_status"] = health.get("status", "ok")
+ except (requests.exceptions.RequestException, ValueError):
+ pass # healthz is optional
+
+ if diagnostic:
+ import os
+ results["diagnostic"] = {
+ "base_url": base_url,
+ "api_key_set": bool(conn.get("api_key")),
+ "timeout": os.environ.get("N8N_TIMEOUT", "30"),
+ "python": sys.version.split()[0],
+ "cli_version": VERSION,
+ }
+
+ if _json_flag(ctx):
+ output(results, True)
+ return
+
+ click.echo()
+ click.secho(" n8n Health Check", fg="cyan", bold=True)
+ click.secho(" " + "=" * 40, fg="cyan")
+ click.echo()
+
+ click.echo(f" Instance: {base_url}")
+
+ if results["status"] == "connected":
+ click.secho(f" Status: Connected", fg="green")
+ click.echo(f" Response: {results.get('response_ms', '?')}ms")
+ elif results["status"] == "unreachable":
+ click.secho(f" Status: Unreachable", fg="red")
+ else:
+ click.secho(f" Status: {results['status']}", fg="red")
+
+ if diagnostic and "diagnostic" in results:
+ diag = results["diagnostic"]
+ click.echo()
+ click.secho(" Diagnostic", fg="cyan", bold=True)
+ click.echo(f" API Key: {'configured' if diag['api_key_set'] else 'NOT SET'}")
+ click.echo(f" Timeout: {diag['timeout']}s")
+ click.echo(f" Python: {diag['python']}")
+ click.echo(f" CLI: v{diag['cli_version']}")
+
+ click.echo()
+
+
+# ─── Workflow Versions ──────────────────────────────────────────────────────
+
+@workflow_.group("versions")
+def workflow_versions_() -> None:
+ """Version history and rollback (local snapshots)."""
+
+
+@workflow_versions_.command("list")
[email protected]("workflow_id")
[email protected]("--limit", default=20, type=int)
+def versions_list(ctx: click.Context, workflow_id: str, limit: int) -> None:
+ """List stored versions for a workflow."""
+ vers = versions.list_versions(workflow_id, limit=limit)
+ if _json_flag(ctx):
+ output(vers, True)
+ return
+ if not vers:
+ warn(f"No versions stored for workflow {workflow_id}")
+ click.echo(" Versions are saved automatically when you use: update, patch, autofix --apply")
+ return
+ click.secho(f"\n {len(vers)} version(s) for workflow {workflow_id}:\n", fg="cyan")
+ for v in vers:
+ click.echo(f" v{v['version_number']:>3d} {v['created_at']} {click.style(v['trigger'], fg='cyan'):>12s} {v['workflow_name']}")
+ click.echo()
+
+
+@workflow_versions_.command("rollback")
[email protected]("workflow_id")
[email protected]("--version", "ver_num", type=int, default=None, help="Version number to rollback to (default: previous)")
+def versions_rollback(ctx: click.Context, workflow_id: str, ver_num: int | None) -> None:
+ """Rollback a workflow to a previous version."""
+ conn = _conn(ctx)
+
+ if ver_num is None:
+ vers = versions.list_versions(workflow_id, limit=1)
+ if not vers:
+ error(f"No versions found for workflow {workflow_id}")
+ return
+ ver_num = vers[0].get("version_number")
+ if not ver_num:
+ error("Version data is corrupted")
+ return
+
+ snapshot = versions.get_snapshot(workflow_id, ver_num)
+ if not snapshot:
+ error(f"Version {ver_num} not found for workflow {workflow_id}")
+ return
+
+ # Save current state before rollback
+ _auto_snapshot(workflow_id, conn, "pre-rollback")
+
+ # Apply the rollback — deactivate first, then update
+ try:
+ workflows.deactivate_workflow(workflow_id, **conn)
+ except requests.exceptions.HTTPError:
+ pass # May already be inactive
+ update_data = _clean_for_api(snapshot)
+ update_data.pop("active", None)
+ workflows.update_workflow(workflow_id, update_data, **conn)
+ success(f"Rolled back workflow {workflow_id} to version {ver_num} (deactivated — use activate to enable)")
+
+
+@workflow_versions_.command("show")
[email protected]("workflow_id")
[email protected]("version_number", type=int)
+def versions_show(ctx: click.Context, workflow_id: str, version_number: int) -> None:
+ """Show a specific version's snapshot."""
+ snapshot = versions.get_snapshot(workflow_id, version_number)
+ if not snapshot:
+ error(f"Version {version_number} not found")
+ return
+ output(snapshot, _json_flag(ctx))
+
+
+@workflow_versions_.command("diff")
[email protected]("workflow_id")
[email protected]("version_a", type=int)
[email protected]("version_b", type=int)
+def versions_diff(ctx: click.Context, workflow_id: str, version_a: int, version_b: int) -> None:
+ """Compare two versions of a workflow."""
+ if version_a == version_b:
+ warn(f"Both versions are the same ({version_a}). Nothing to diff.")
+ return
+ import difflib
+ snap_a = versions.get_snapshot(workflow_id, version_a)
+ snap_b = versions.get_snapshot(workflow_id, version_b)
+ if not snap_a:
+ error(f"Version {version_a} not found")
+ return
+ if not snap_b:
+ error(f"Version {version_b} not found")
+ return
+
+ def _clean(d: dict) -> str:
+ clean = {k: v for k, v in d.items() if k not in ("id", "createdAt", "updatedAt", "versionId", "shared")}
+ return json.dumps(clean, indent=2, sort_keys=True, default=str)
+
+ lines_a = _clean(snap_a).splitlines(keepends=True)
+ lines_b = _clean(snap_b).splitlines(keepends=True)
+ diff = difflib.unified_diff(lines_a, lines_b, fromfile=f"v{version_a}", tofile=f"v{version_b}", lineterm="")
+
+ any_diff = False
+ for line in diff:
+ any_diff = True
+ if line.startswith("+++") or line.startswith("---"):
+ click.secho(line, fg="cyan", bold=True)
+ elif line.startswith("+"):
+ click.secho(line, fg="green")
+ elif line.startswith("-"):
+ click.secho(line, fg="red")
+ elif line.startswith("@@"):
+ click.secho(line, fg="cyan")
+ else:
+ click.echo(line)
+
+ if not any_diff:
+ success("Versions are identical")
+
+
+@workflow_versions_.command("prune")
[email protected]("workflow_id")
[email protected]("--keep", default=10, type=int, help="Number of recent versions to keep")
+def versions_prune(workflow_id: str, keep: int) -> None:
+ """Delete old versions, keeping the N most recent."""
+ deleted = versions.prune_versions(workflow_id, keep=keep)
+ success(f"Pruned {deleted} old version(s), kept {keep} most recent")
+
+
+@workflow_versions_.command("stats")
+def versions_stats(ctx: click.Context) -> None:
+ """Show version storage statistics."""
+ st = versions.stats()
+ if _json_flag(ctx):
+ output(st, True)
+ return
+ click.echo(f"\n Versions DB: {st['db_path']}")
+ click.echo(f" Workflows tracked: {st['workflows_tracked']}")
+ click.echo(f" Total versions: {st['total_versions']}")
+ size_kb = st['db_size_bytes'] / 1024
+ click.echo(f" DB size: {size_kb:.1f} KB")
+ click.echo()
+
+
+# ─── Workflow Test (webhook trigger) ────────────────────────────────────────
+
+@workflow_.command("test")
[email protected]("workflow_id")
[email protected]("--data", "test_data", default=None, help="JSON data to send (inline or @file.json)")
+def workflow_test(ctx: click.Context, workflow_id: str, test_data: str | None) -> None:
+ """Test a workflow by triggering its webhook (workflow must be active with a webhook trigger)."""
+ conn = _conn(ctx)
+ wf = workflows.get_workflow(workflow_id, **conn)
+
+ # Find webhook trigger node
+ webhook_node = None
+ for node in wf.get("nodes", []):
+ if not isinstance(node, dict):
+ continue
+ node_type = node.get("type", "").lower()
+ if "webhook" in node_type:
+ webhook_node = node
+ break
+
+ if not webhook_node:
+ error("No webhook trigger found in this workflow. Only webhook-triggered workflows can be tested via CLI.")
+ return
+
+ if not wf.get("active"):
+ error(f"Workflow is not active. Run: cli-anything-n8n workflow activate {workflow_id}")
+ return
+
+ # Build webhook URL (allow : for path params like /:id, strip only dangerous chars)
+ webhook_path = webhook_node.get("parameters", {}).get("path", "")
+ if not webhook_path:
+ webhook_id = webhook_node.get("webhookId", "")
+ webhook_path = webhook_id or workflow_id
+ webhook_path = re.sub(r'[^a-zA-Z0-9_\-/:.]', '', webhook_path).strip("/")
+ if any(seg in {".", ".."} for seg in webhook_path.split("/")):
+ error("Webhook path contains invalid dot segments")
+ return
+
+ base = conn["base_url"].rstrip("/")
+ webhook_url = f"{base}/webhook/{webhook_path}"
+
+ # Use the HTTP method configured on the webhook node (default POST)
+ http_method = webhook_node.get("parameters", {}).get("httpMethod", "POST").upper()
+ payload = _load_json_arg(test_data) if test_data else {}
+
+ click.echo(f" Triggering webhook ({http_method}): {webhook_url}")
+ from cli_anything.n8n.utils.n8n_backend import DEFAULT_TIMEOUT
+ resp = requests.request(http_method, webhook_url, json=payload if http_method in ("POST", "PUT", "PATCH") else None, params=payload if http_method == "GET" else None, timeout=DEFAULT_TIMEOUT)
+
+ if _json_flag(ctx):
+ try:
+ output(resp.json(), True)
+ except (ValueError, AttributeError):
+ output({"status": resp.status_code, "body": resp.text}, True)
+ return
+
+ if resp.ok:
+ success(f"Webhook responded {resp.status_code}")
+ try:
+ output(resp.json(), False)
+ except (ValueError, AttributeError):
+ click.echo(f" Response: {resp.text[:200]}")
+ else:
+ error(f"Webhook returned {resp.status_code}")
+
+
+# ─── Nodes (npm registry) ───────────────────────────────────────────────────
+
+def node_() -> None:
+ """Search and explore n8n community nodes (via npm)."""
+
+
+@node_.command("search")
[email protected]("--limit", default=15, type=int, help="Max results")
+def node_search(ctx: click.Context, query: str, limit: int) -> None:
+ """Search n8n community nodes on npm (26,000+ packages)."""
+ data = nodes.search_nodes(query, limit=limit)
+
+ if _json_flag(ctx):
+ output(data, True)
+ return
+
+ pkgs = data.get("packages", [])
+ if not pkgs:
+ warn(f"No node packages found for '{query}'")
+ return
+
+ click.secho(f"\n {data.get('total', '?'):,} packages found for '{query}' (showing {len(pkgs)}):\n", fg="cyan")
+ for p in pkgs:
+ click.echo(f" {click.style(p.get('name', '?'), fg='cyan')}")
+ click.secho(f" v{p.get('version', '?')} by {p.get('author', '?')} — {p.get('description', '')}", fg="bright_black")
+ click.echo(f"\n Use: cli-anything-n8n node info <package-name> for details")
+ click.echo()
+
+
+@node_.command("info")
[email protected]("package_name")
+def node_info(ctx: click.Context, package_name: str) -> None:
+ """Get detailed info about an n8n node package from npm."""
+ data = nodes.get_node_info(package_name)
+
+ if _json_flag(ctx):
+ output(data, True)
+ return
+
+ click.secho(f"\n {data.get('name', '?')} v{data.get('version', '?')}", fg="cyan", bold=True)
+ click.echo(f" {data.get('description', '')}")
+ click.echo(f" Author: {data.get('author', '?')}")
+ click.echo(f" License: {data.get('license', '?')}")
+ if data.get("homepage"):
+ click.echo(f" Homepage: {data.get('homepage', '')}")
+ click.echo(f" npm: {data.get('npm_url', '')}")
+
+ n8n_nodes = data.get("n8n_nodes", [])
+ if n8n_nodes and isinstance(n8n_nodes, list):
+ click.secho(f"\n Nodes provided ({len(n8n_nodes)}):", fg="cyan")
+ for n in n8n_nodes:
+ click.echo(f" - {n}")
+
+ n8n_creds = data.get("n8n_credentials", [])
+ if n8n_creds and isinstance(n8n_creds, list):
+ click.secho(f"\n Credentials:", fg="cyan")
+ for c in n8n_creds:
+ click.echo(f" - {c}")
+
+ click.secho(f"\n Install:", fg="green")
+ click.echo(f" {data.get('install_cmd', 'N/A')}")
+ click.echo()
+
+
+# ─── Scaffold ───────────────────────────────────────────────────────────────
+
+@workflow_.command("scaffold")
[email protected]("pattern", type=click.Choice(["webhook", "api", "database", "ai-agent", "scheduled"]))
[email protected]("--name", default=None, help="Custom workflow name")
[email protected]("--deploy", is_flag=True, default=False, help="Deploy directly to n8n")
[email protected]("-o", "--output", "out_path", default=None, help="Save to file")
+def workflow_scaffold(ctx: click.Context, pattern: str, name: str | None, deploy: bool, out_path: str | None) -> None:
+ """Generate a workflow from a proven pattern.
+
+ Patterns: webhook, api, database, ai-agent, scheduled.
+ """
+ wf = scaffolds.get_scaffold(pattern, name=name)
+
+ if _json_flag(ctx) and not deploy and not out_path:
+ output(wf, True)
+ return
+
+ if deploy:
+ result = workflows.create_workflow(wf, **_conn(ctx))
+ success(f"Deployed '{wf['name']}' as workflow {result.get('id', '?')}")
+ output(result, _json_flag(ctx))
+ elif out_path:
+ Path(out_path).write_text(json.dumps(wf, indent=2, default=str))
+ success(f"Saved scaffold to {out_path}")
+ else:
+ click.secho(f"\n Pattern: {pattern}", fg="cyan", bold=True)
+ click.echo(f" Name: {wf.get('name', '?')}")
+ click.echo(f" Nodes: {len(wf.get('nodes', []))}")
+ for n in wf.get("nodes", []):
+ if not isinstance(n, dict):
+ continue
+ click.echo(f" - {n.get('name', '?')} ({n.get('type', '?')})")
+ click.echo(f"\n Use --deploy to create in n8n, --output to save to file, or --json to see full JSON")
+ click.echo()
+
+
+@workflow_.command("patterns")
+def workflow_patterns(ctx: click.Context) -> None:
+ """List available scaffold patterns."""
+ patterns = scaffolds.list_patterns()
+ if _json_flag(ctx):
+ output(patterns, True)
+ return
+ click.secho("\n Available workflow patterns:\n", fg="cyan", bold=True)
+ for p in patterns:
+ click.echo(f" {click.style(p.get('name', '?'), fg='cyan'):>20s} {p.get('description', '')}")
+ click.echo(f"\n Usage: cli-anything-n8n workflow scaffold <pattern> [--deploy]")
+ click.echo()
+
+
+# ─── Expression Validator ───────────────────────────────────────────────────
+
[email protected]("expression")
+def expression_validate(ctx: click.Context, expr: str) -> None:
+ """Validate an n8n expression (e.g., '={{$json.name}}')."""
+ result = expressions.validate_expression(expr)
+
+ if _json_flag(ctx):
+ output({"valid": result.valid, "expression": result.expression, "issues": result.issues, "warnings": result.warnings}, True)
+ return
+
+ if result.valid and not result.warnings:
+ success(f"Expression is valid: {expr}")
+ return
+
+ if result.issues:
+ click.secho(f"\n INVALID expression:\n", fg="red", bold=True)
+ for issue in result.issues:
+ click.secho(f" {issue}", fg="red")
+
+ if result.warnings:
+ click.secho(f"\n Warnings:", fg="yellow")
+ for w in result.warnings:
+ click.secho(f" {w}", fg="yellow")
+
+ if result.valid:
+ success("Expression is syntactically valid (with warnings)")
+ click.echo()
+
+
+# ─── Entry point ────────────────────────────────────────────────────────────
+
+def main() -> None:
+ try:
+ cli(obj={})
+ except requests.exceptions.HTTPError as exc:
+ status = exc.response.status_code
+ try:
+ body = exc.response.json()
+ msg = str(body.get("message", "Request failed"))[:200]
+ except (ValueError, AttributeError):
+ msg = "Request failed"
+ error(f"{status} — {msg}")
+ sys.exit(1)
+ except requests.exceptions.ConnectionError:
+ error("Cannot connect to n8n. Check your URL and network.")
+ sys.exit(1)
+ except ValueError as exc:
+ error(str(exc))
+ sys.exit(1)
+ except OSError as exc:
+ error(f"File error: {exc}")
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/n8n/agent-harness/cli_anything/n8n/skills/SKILL.md b/n8n/agent-harness/cli_anything/n8n/skills/SKILL.md
new file mode 100644
index 000000000..998956575
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/skills/SKILL.md
@@ -0,0 +1,50 @@
+---
+name: cli-anything-n8n
+description: >-
+ Command-line interface for n8n workflow automation platform.
+ Manages workflows, executions, credentials, variables, and tags.
+ Based on n8n Public API v1.1.1 (n8n >= 1.0.0).
+---
+
+# cli-anything-n8n
+
+CLI harness for n8n workflow automation — built with the CLI-Anything pattern.
+Verified against n8n OpenAPI spec v1.1.1.
+
+## Installation
+
+```bash
+pip install cli-anything-n8n
+```
+
+## Configuration
+
+```bash
+cli-anything-n8n config set base_url https://your-n8n-instance.com
+cli-anything-n8n config set api_key your-api-key
+
+# Or environment variables
+export N8N_BASE_URL=https://your-n8n-instance.com
+export N8N_API_KEY=your-api-key
+export N8N_TIMEOUT=60 # optional, default 30s
+```
+
+## Command Groups
+
+| Group | Commands |
+|-------|----------|
+| workflow | list, get, create, update, delete, activate, deactivate, tags, set-tags, transfer |
+| execution | list, get, delete, retry |
+| credential | create, delete, schema, transfer |
+| variable | list, create, update, delete |
+| tag | list, get, create, update, delete |
+| config | show, set |
+
+## For AI Agents
+
+- Always use `--json` flag for structured output
+- Use `@file.json` to pass complex JSON from files
+- Check return codes: 0 = success, non-zero = error
+- All IDs are strings, not integers
+- API key is always masked in `config show` output
+- Not available in public API: data tables, credential listing, execution stop
diff --git a/n8n/agent-harness/cli_anything/n8n/tests/TEST.md b/n8n/agent-harness/cli_anything/n8n/tests/TEST.md
new file mode 100644
index 000000000..2a53ff332
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/tests/TEST.md
@@ -0,0 +1,29 @@
+# Testing cli-anything-n8n
+
+## Unit tests (no n8n required)
+
+```bash
+cd agent-harness
+pip install -e .
+pytest cli_anything/n8n/tests/test_core.py -v
+```
+
+## E2E tests (n8n instance required)
+
+```bash
+export N8N_BASE_URL=https://your-n8n-instance.com
+export N8N_API_KEY=your-api-key
+pytest cli_anything/n8n/tests/test_full_e2e.py -v -m e2e
+```
+
+## Run all tests
+
+```bash
+pytest cli_anything/n8n/tests/ -v
+```
+
+## Skip E2E
+
+```bash
+pytest cli_anything/n8n/tests/ -v -m "not e2e"
+```
diff --git a/n8n/agent-harness/cli_anything/n8n/tests/__init__.py b/n8n/agent-harness/cli_anything/n8n/tests/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/n8n/agent-harness/cli_anything/n8n/tests/test_core.py b/n8n/agent-harness/cli_anything/n8n/tests/test_core.py
new file mode 100644
index 000000000..ee6cbb8dc
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/tests/test_core.py
@@ -0,0 +1,499 @@
+"""Unit tests — all HTTP calls mocked."""
+
+from __future__ import annotations
+
+import json
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from cli_anything.n8n.core import (
+ credentials,
+ executions,
+ project,
+ tags,
+ variables,
+ workflows,
+)
+from cli_anything.n8n.utils import n8n_backend
+
+
+# ─── Helpers ────────────────────────────────────────────────────────────────
+
+def mock_response(status_code: int = 200, json_data: dict | list | None = None) -> MagicMock:
+ resp = MagicMock()
+ resp.status_code = status_code
+ resp.json.return_value = json_data or {}
+ resp.text = json.dumps(json_data or {})
+ resp.raise_for_status = MagicMock()
+ return resp
+
+
+BASE = "https://n8n.example.com"
+KEY = "test-api-key-1234"
+
+
+# ─── Backend ────────────────────────────────────────────────────────────────
+
+class TestBackend:
+ def test_url_construction(self):
+ url = n8n_backend._url(BASE, "/workflows")
+ assert url == f"{BASE}/api/v1/workflows"
+
+ def test_url_with_full_api_path(self):
+ url = n8n_backend._url(BASE, "/api/v1/workflows")
+ assert url == f"{BASE}/api/v1/workflows"
+
+ @patch.dict("os.environ", {"N8N_BASE_URL": ""}, clear=False)
+ def test_url_missing_base(self):
+ with pytest.raises(ValueError, match="base URL not configured"):
+ n8n_backend._url("", "/workflows")
+
+ def test_headers_with_key(self):
+ h = n8n_backend._headers("mykey")
+ assert h["X-N8N-API-KEY"] == "mykey"
+ assert h["Content-Type"] == "application/json"
+
+ def test_headers_no_key(self):
+ with patch.dict("os.environ", {}, clear=True):
+ h = n8n_backend._headers("")
+ assert "X-N8N-API-KEY" not in h
+
+ @patch("cli_anything.n8n.utils.n8n_backend.requests.request")
+ def test_api_get(self, mock_req):
+ mock_req.return_value = mock_response(200, {"data": []})
+ result = n8n_backend.api_get("/workflows", base_url=BASE, api_key=KEY)
+ assert result == {"data": []}
+ args, kwargs = mock_req.call_args
+ assert args[0] == "GET"
+
+ @patch("cli_anything.n8n.utils.n8n_backend.requests.request")
+ def test_api_post(self, mock_req):
+ mock_req.return_value = mock_response(200, {"id": "1"})
+ result = n8n_backend.api_post("/workflows", {"name": "test"}, base_url=BASE, api_key=KEY)
+ assert result == {"id": "1"}
+
+ @patch("cli_anything.n8n.utils.n8n_backend.requests.request")
+ def test_api_delete_204(self, mock_req):
+ mock_req.return_value = mock_response(204)
+ result = n8n_backend.api_delete("/workflows/1", base_url=BASE, api_key=KEY)
+ assert result == {}
+
+ @patch("cli_anything.n8n.utils.n8n_backend.requests.request")
+ def test_custom_timeout(self, mock_req):
+ mock_req.return_value = mock_response(200, {})
+ n8n_backend.api_request("GET", "/test", base_url=BASE, api_key=KEY, timeout=120)
+ _, kwargs = mock_req.call_args
+ assert kwargs["timeout"] == 120
+
+
+# ─── Workflows ──────────────────────────────────────────────────────────────
+
+class TestWorkflows:
+ @patch("cli_anything.n8n.core.workflows.api_get")
+ def test_list_workflows(self, mock_get):
+ mock_get.return_value = {"data": [{"id": "1", "name": "Test"}]}
+ result = workflows.list_workflows(base_url=BASE, api_key=KEY)
+ assert result["data"][0]["name"] == "Test"
+
+ @patch("cli_anything.n8n.core.workflows.api_get")
+ def test_list_workflows_with_filters(self, mock_get):
+ mock_get.return_value = {"data": []}
+ workflows.list_workflows(base_url=BASE, api_key=KEY, active=True, name="foo")
+ _, kwargs = mock_get.call_args
+ assert kwargs["params"]["active"] == "true"
+ assert kwargs["params"]["name"] == "foo"
+
+ @patch("cli_anything.n8n.core.workflows.api_get")
+ def test_get_workflow(self, mock_get):
+ mock_get.return_value = {"id": "1", "name": "Test"}
+ result = workflows.get_workflow("1", base_url=BASE, api_key=KEY)
+ assert result["id"] == "1"
+
+ @patch("cli_anything.n8n.core.workflows.api_post")
+ def test_create_workflow(self, mock_post):
+ mock_post.return_value = {"id": "2"}
+ result = workflows.create_workflow({"name": "New"}, base_url=BASE, api_key=KEY)
+ assert result["id"] == "2"
+
+ @patch("cli_anything.n8n.core.workflows.api_delete")
+ def test_delete_workflow(self, mock_del):
+ mock_del.return_value = {}
+ workflows.delete_workflow("1", base_url=BASE, api_key=KEY)
+ mock_del.assert_called_once()
+
+ @patch("cli_anything.n8n.core.workflows.api_post")
+ def test_activate_workflow(self, mock_post):
+ mock_post.return_value = {"active": True}
+ result = workflows.activate_workflow("1", base_url=BASE, api_key=KEY)
+ assert result["active"] is True
+
+ @patch("cli_anything.n8n.core.workflows.api_put")
+ def test_transfer_workflow(self, mock_put):
+ mock_put.return_value = {}
+ workflows.transfer_workflow("1", "proj-1", base_url=BASE, api_key=KEY)
+ mock_put.assert_called_once()
+
+ @patch("cli_anything.n8n.core.workflows.api_put")
+ def test_update_workflow_tags(self, mock_put):
+ mock_put.return_value = [{"id": "t1"}]
+ result = workflows.update_workflow_tags("1", [{"id": "t1"}], base_url=BASE, api_key=KEY)
+ assert result == [{"id": "t1"}]
+
+
+# ─── Executions ─────────────────────────────────────────────────────────────
+
+class TestExecutions:
+ @patch("cli_anything.n8n.core.executions.api_get")
+ def test_list_executions(self, mock_get):
+ mock_get.return_value = {"data": [{"id": "10", "status": "success"}]}
+ result = executions.list_executions(base_url=BASE, api_key=KEY, status="success")
+ assert result["data"][0]["status"] == "success"
+
+ @patch("cli_anything.n8n.core.executions.api_post")
+ def test_retry_execution(self, mock_post):
+ mock_post.return_value = {"id": "11"}
+ result = executions.retry_execution("10", base_url=BASE, api_key=KEY)
+ assert result["id"] == "11"
+
+ @patch("cli_anything.n8n.core.executions.api_delete")
+ def test_delete_execution(self, mock_del):
+ mock_del.return_value = {}
+ executions.delete_execution("10", base_url=BASE, api_key=KEY)
+ mock_del.assert_called_once()
+
+
+# ─── Credentials ────────────────────────────────────────────────────────────
+
+class TestCredentials:
+ @patch("cli_anything.n8n.core.credentials.api_post")
+ def test_create_credential(self, mock_post):
+ mock_post.return_value = {"id": "c1"}
+ result = credentials.create_credential({"name": "test", "type": "httpBasicAuth", "data": {}}, base_url=BASE, api_key=KEY)
+ assert result["id"] == "c1"
+
+ @patch("cli_anything.n8n.core.credentials.api_get")
+ def test_get_schema(self, mock_get):
+ mock_get.return_value = {"properties": {}}
+ result = credentials.get_credential_schema("telegramApi", base_url=BASE, api_key=KEY)
+ assert "properties" in result
+
+ @patch("cli_anything.n8n.core.credentials.api_delete")
+ def test_delete_credential(self, mock_del):
+ mock_del.return_value = {}
+ credentials.delete_credential("c1", base_url=BASE, api_key=KEY)
+ mock_del.assert_called_once()
+
+ @patch("cli_anything.n8n.core.credentials.api_put")
+ def test_transfer_credential(self, mock_put):
+ mock_put.return_value = {}
+ credentials.transfer_credential("c1", "proj-1", base_url=BASE, api_key=KEY)
+ mock_put.assert_called_once()
+
+
+# ─── Variables ──────────────────────────────────────────────────────────────
+
+class TestVariables:
+ @patch("cli_anything.n8n.core.variables.api_get")
+ def test_list_variables(self, mock_get):
+ mock_get.return_value = [{"id": "1", "key": "FOO", "value": "bar"}]
+ result = variables.list_variables(base_url=BASE, api_key=KEY)
+ assert result[0]["key"] == "FOO"
+
+ @patch("cli_anything.n8n.core.variables.api_post")
+ def test_create_variable(self, mock_post):
+ mock_post.return_value = {"id": "2", "key": "BAZ", "value": "qux"}
+ result = variables.create_variable("BAZ", "qux", base_url=BASE, api_key=KEY)
+ assert result["key"] == "BAZ"
+
+
+# ─── Tags ───────────────────────────────────────────────────────────────────
+
+class TestTags:
+ @patch("cli_anything.n8n.core.tags.api_get")
+ def test_list_tags(self, mock_get):
+ mock_get.return_value = {"data": [{"id": "1", "name": "prod"}]}
+ result = tags.list_tags(base_url=BASE, api_key=KEY)
+ assert result["data"][0]["name"] == "prod"
+
+ @patch("cli_anything.n8n.core.tags.api_post")
+ def test_create_tag(self, mock_post):
+ mock_post.return_value = {"id": "2", "name": "dev"}
+ result = tags.create_tag("dev", base_url=BASE, api_key=KEY)
+ assert result["name"] == "dev"
+
+
+# ─── Project config ─────────────────────────────────────────────────────────
+
+class TestProject:
+ @patch.dict("os.environ", {"N8N_BASE_URL": "https://env.example.com", "N8N_API_KEY": "env-key"})
+ def test_load_config_env_override(self):
+ cfg = project.load_config()
+ assert cfg["base_url"] == "https://env.example.com"
+ assert cfg["api_key"] == "env-key"
+
+ def test_get_connection_explicit_args(self):
+ url, key = project.get_connection("https://arg.com", "arg-key")
+ assert url == "https://arg.com"
+ assert key == "arg-key"
+
+
+# ─── JSON arg parsing ──────────────────────────────────────────────────────
+
+class TestLoadJsonArg:
+ def test_parse_inline_json(self):
+ from cli_anything.n8n.n8n_cli import _load_json_arg
+ result = _load_json_arg('{"name": "test"}')
+ assert result == {"name": "test"}
+
+ def test_invalid_json_raises(self):
+ from cli_anything.n8n.n8n_cli import _load_json_arg
+ with pytest.raises(ValueError, match="Invalid JSON"):
+ _load_json_arg("not json")
+
+ def test_file_not_found_raises(self):
+ from cli_anything.n8n.n8n_cli import _load_json_arg
+ with pytest.raises(ValueError, match="File not found"):
+ _load_json_arg("@/nonexistent/file.json")
+
+ def test_load_from_file(self, tmp_path):
+ from cli_anything.n8n.n8n_cli import _load_json_arg
+ f = tmp_path / "test.json"
+ f.write_text('{"name": "from_file"}')
+ result = _load_json_arg(f"@{f}")
+ assert result == {"name": "from_file"}
+
+
+# ─── CLI commands (subprocess) ──────────────────────────────────────────────
+
+class TestCLICommands:
+ def test_export_import_roundtrip(self, tmp_path):
+ """Test that export strips server fields using the REAL _clean_for_api."""
+ from cli_anything.n8n.n8n_cli import _clean_for_api, _load_json_arg
+ # Simulate export data (what get_workflow returns)
+ server_data = {
+ "id": "abc123",
+ "name": "Test WF",
+ "nodes": [{"type": "n8n-nodes-base.manualTrigger"}],
+ "connections": {},
+ "settings": {},
+ "createdAt": "2026-01-01",
+ "updatedAt": "2026-01-02",
+ "versionId": "v1",
+ "shared": [{"role": "owner"}],
+ }
+ # Use the REAL function, not a reimplementation
+ export_data = _clean_for_api(server_data)
+ assert "id" not in export_data
+ assert "createdAt" not in export_data
+ assert "name" in export_data
+ assert "nodes" in export_data
+
+ # Write and read back
+ out = tmp_path / "export.json"
+ out.write_text(json.dumps(export_data, indent=2))
+ loaded = _load_json_arg(f"@{out}")
+ assert loaded["name"] == "Test WF"
+ assert "id" not in loaded
+
+
+class TestVersions:
+ def test_save_and_list(self, tmp_path, monkeypatch):
+ from cli_anything.n8n.core import versions as ver
+ monkeypatch.setattr(ver, "DB_DIR", tmp_path)
+ monkeypatch.setattr(ver, "DB_PATH", tmp_path / "versions.db")
+
+ wf = {"name": "Test WF", "nodes": [], "connections": {}}
+ v1 = ver.save_snapshot("wf1", wf, "update")
+ assert v1 == 1
+ v2 = ver.save_snapshot("wf1", {**wf, "name": "Updated"}, "patch")
+ assert v2 == 2
+
+ vers = ver.list_versions("wf1")
+ assert len(vers) == 2
+ assert vers[0]["version_number"] == 2
+
+ def test_get_snapshot(self, tmp_path, monkeypatch):
+ from cli_anything.n8n.core import versions as ver
+ monkeypatch.setattr(ver, "DB_DIR", tmp_path)
+ monkeypatch.setattr(ver, "DB_PATH", tmp_path / "versions.db")
+
+ wf = {"name": "Original", "nodes": [{"name": "A"}]}
+ ver.save_snapshot("wf1", wf, "update")
+ snapshot = ver.get_snapshot("wf1", 1)
+ assert snapshot["name"] == "Original"
+ assert snapshot["nodes"][0]["name"] == "A"
+
+ def test_prune(self, tmp_path, monkeypatch):
+ from cli_anything.n8n.core import versions as ver
+ monkeypatch.setattr(ver, "DB_DIR", tmp_path)
+ monkeypatch.setattr(ver, "DB_PATH", tmp_path / "versions.db")
+
+ for i in range(5):
+ ver.save_snapshot("wf1", {"name": f"v{i}"}, "test")
+ deleted = ver.prune_versions("wf1", keep=2)
+ assert deleted == 3
+ remaining = ver.list_versions("wf1")
+ assert len(remaining) == 2
+
+ def test_stats(self, tmp_path, monkeypatch):
+ from cli_anything.n8n.core import versions as ver
+ monkeypatch.setattr(ver, "DB_DIR", tmp_path)
+ monkeypatch.setattr(ver, "DB_PATH", tmp_path / "versions.db")
+
+ ver.save_snapshot("wf1", {"name": "A"}, "test")
+ ver.save_snapshot("wf2", {"name": "B"}, "test")
+ st = ver.stats()
+ assert st["total_versions"] == 2
+ assert st["workflows_tracked"] == 2
+
+
+class TestFixers:
+ def test_expression_format(self):
+ from cli_anything.n8n.core.fixers import autofix
+ wf = {"name": "Test", "nodes": [{"name": "Node1", "type": "n8n-nodes-base.set", "parameters": {"value": "{{$json.name}}"}}], "connections": {}}
+ _, fixes = autofix(wf, apply=False)
+ assert any(f.fix_type == "expression-format" for f in fixes)
+
+ def test_expression_format_apply(self):
+ from cli_anything.n8n.core.fixers import autofix
+ wf = {"name": "Test", "nodes": [{"name": "Node1", "type": "n8n-nodes-base.set", "parameters": {"value": "{{$json.name}}"}}], "connections": {}}
+ fixed, fixes = autofix(wf, apply=True)
+ assert fixed["nodes"][0]["parameters"]["value"] == "={{$json.name}}"
+
+ def test_webhook_missing_path(self):
+ from cli_anything.n8n.core.fixers import autofix
+ wf = {"name": "Test", "nodes": [{"name": "Webhook", "type": "n8n-nodes-base.webhook", "parameters": {}}], "connections": {}}
+ _, fixes = autofix(wf, apply=False)
+ assert any(f.fix_type == "webhook-missing-path" for f in fixes)
+
+ def test_orphan_connection(self):
+ from cli_anything.n8n.core.fixers import autofix
+ wf = {"name": "Test", "nodes": [{"name": "A", "type": "test"}], "connections": {"NonExistent": {"main": [[{"node": "A", "type": "main", "index": 0}]]}}}
+ fixed, fixes = autofix(wf, apply=True)
+ assert "NonExistent" not in fixed["connections"]
+
+ def test_no_issues(self):
+ from cli_anything.n8n.core.fixers import autofix
+ wf = {"name": "Test", "nodes": [{"name": "A", "type": "n8n-nodes-base.manualTrigger", "parameters": {}}], "connections": {}}
+ _, fixes = autofix(wf, apply=False)
+ assert len(fixes) == 0
+
+ def test_null_nodes_no_crash(self):
+ """Bug fix: autofix must not crash when nodes or connections are None."""
+ from cli_anything.n8n.core.fixers import autofix
+ wf = {"name": "Test", "nodes": None, "connections": None}
+ _, fixes = autofix(wf, apply=False)
+ assert isinstance(fixes, list)
+
+ def test_expression_in_list_apply(self):
+ """Bug fix: _set_nested must handle bracket notation for list items."""
+ from cli_anything.n8n.core.fixers import autofix
+ wf = {
+ "name": "Test",
+ "nodes": [{"name": "Set", "type": "n8n-nodes-base.set", "parameters": {
+ "assignments": [{"name": "x", "value": "{{$json.y}}"}]
+ }}],
+ "connections": {},
+ }
+ fixed, fixes = autofix(wf, apply=True)
+ # The fix should update the value inside the list, not create a corrupted key
+ assert "assignments[0]" not in fixed["nodes"][0]["parameters"]
+ assert fixed["nodes"][0]["parameters"]["assignments"][0]["value"] == "={{$json.y}}"
+
+
+class TestNodes:
+ @patch("cli_anything.n8n.core.nodes.requests.get")
+ def test_search_nodes(self, mock_get):
+ from cli_anything.n8n.core import nodes as nd
+ mock_resp = MagicMock()
+ mock_resp.json.return_value = {"total": 100, "objects": [{"package": {"name": "n8n-nodes-test", "version": "1.0.0", "description": "Test", "publisher": {"username": "dev"}}}]}
+ mock_resp.raise_for_status = MagicMock()
+ mock_get.return_value = mock_resp
+ result = nd.search_nodes("test")
+ assert result["total"] == 100
+
+ @patch("cli_anything.n8n.core.nodes.requests.get")
+ def test_get_node_info(self, mock_get):
+ from cli_anything.n8n.core import nodes as nd
+ mock_resp = MagicMock()
+ mock_resp.json.return_value = {"name": "n8n-nodes-test", "description": "Test pkg", "dist-tags": {"latest": "1.0.0"}, "versions": {"1.0.0": {"license": "MIT", "n8n": {"nodes": [{"type": "testNode"}], "credentials": []}, "keywords": []}}, "author": {"name": "dev"}}
+ mock_resp.raise_for_status = MagicMock()
+ mock_get.return_value = mock_resp
+ result = nd.get_node_info("n8n-nodes-test")
+ assert result["name"] == "n8n-nodes-test"
+ assert len(result["n8n_nodes"]) == 1
+
+
+class TestScaffolds:
+ def test_list_patterns(self):
+ from cli_anything.n8n.core.scaffolds import list_patterns
+ patterns = list_patterns()
+ assert len(patterns) == 5
+ names = {p["name"] for p in patterns}
+ assert "webhook" in names
+ assert "ai-agent" in names
+
+ def test_get_scaffold(self):
+ from cli_anything.n8n.core.scaffolds import get_scaffold
+ wf = get_scaffold("webhook")
+ assert wf["name"] == "Webhook Processing"
+ assert len(wf["nodes"]) > 0
+ assert "connections" in wf
+
+ def test_get_scaffold_custom_name(self):
+ from cli_anything.n8n.core.scaffolds import get_scaffold
+ wf = get_scaffold("api", name="My API Flow")
+ assert wf["name"] == "My API Flow"
+
+ def test_get_scaffold_invalid(self):
+ from cli_anything.n8n.core.scaffolds import get_scaffold
+ with pytest.raises(ValueError, match="Unknown pattern"):
+ get_scaffold("nonexistent")
+
+
+class TestExpressions:
+ def test_valid_expression(self):
+ from cli_anything.n8n.core.expressions import validate_expression
+ result = validate_expression("={{$json.name}}")
+ assert result.valid
+ assert len(result.issues) == 0
+
+ def test_mismatched_braces(self):
+ from cli_anything.n8n.core.expressions import validate_expression
+ result = validate_expression("={{$json.name}")
+ assert not result.valid
+ assert any("Mismatched" in i for i in result.issues)
+
+ def test_missing_equals_prefix(self):
+ from cli_anything.n8n.core.expressions import validate_expression
+ result = validate_expression("{{$json.name}}")
+ assert result.valid # valid but with warning
+ assert any("prefix" in w for w in result.warnings)
+
+ def test_json_bracket_without_quotes(self):
+ from cli_anything.n8n.core.expressions import validate_expression
+ result = validate_expression("={{$json[key]}}")
+ assert any("quotes" in i for i in result.issues)
+
+
+class TestTemplates:
+ @patch("cli_anything.n8n.core.templates.requests.get")
+ def test_search_templates(self, mock_get):
+ from cli_anything.n8n.core import templates as tmpl
+ mock_resp = MagicMock()
+ mock_resp.json.return_value = {"totalWorkflows": 5, "workflows": [{"id": 1, "name": "Test"}]}
+ mock_resp.raise_for_status = MagicMock()
+ mock_get.return_value = mock_resp
+ result = tmpl.search_templates("telegram")
+ assert result["totalWorkflows"] == 5
+
+ @patch("cli_anything.n8n.core.templates.requests.get")
+ def test_get_template(self, mock_get):
+ from cli_anything.n8n.core import templates as tmpl
+ mock_resp = MagicMock()
+ mock_resp.json.return_value = {"workflow": {"name": "My Template", "nodes": []}}
+ mock_resp.raise_for_status = MagicMock()
+ mock_get.return_value = mock_resp
+ result = tmpl.get_template(123)
+ assert result["workflow"]["name"] == "My Template"
diff --git a/n8n/agent-harness/cli_anything/n8n/tests/test_full_e2e.py b/n8n/agent-harness/cli_anything/n8n/tests/test_full_e2e.py
new file mode 100644
index 000000000..2a1a91a95
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/tests/test_full_e2e.py
@@ -0,0 +1,346 @@
+"""E2E tests — require a running n8n instance.
+
+Set N8N_BASE_URL and N8N_API_KEY env vars to run these tests.
+Verified against n8n 2.43.0 (API v1.1.1).
+Skip with: pytest -m "not e2e"
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+import uuid
+
+import pytest
+import requests as req
+
+from cli_anything.n8n.core import credentials, tags, variables, workflows
+
+
+pytestmark = pytest.mark.e2e
+
+N8N_URL = os.environ.get("N8N_BASE_URL", "")
+N8N_KEY = os.environ.get("N8N_API_KEY", "")
+
+
+def _skip_if_no_n8n():
+ if not N8N_URL or not N8N_KEY:
+ pytest.skip("N8N_BASE_URL and N8N_API_KEY required for E2E tests")
+
+
+def _resolve_cli() -> list[str]:
+ import shutil
+ if shutil.which("cli-anything-n8n"):
+ return ["cli-anything-n8n"]
+ return [sys.executable, "-m", "cli_anything.n8n"]
+
+
+# ─── Subprocess tests (no n8n needed) ──────────────────────────────────────
+
+class TestCLISubprocess:
+ def test_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "n8n workflow automation" in result.stdout
+
+ def test_version(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "--version"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "2.4.6" in result.stdout
+
+ def test_workflow_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "list" in result.stdout
+ assert "set-tags" in result.stdout
+ assert "transfer" in result.stdout
+ assert "export" in result.stdout
+ assert "import" in result.stdout
+
+ def test_status_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "status", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "overview" in result.stdout.lower()
+
+ def test_execution_watch_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "execution", "watch", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "interval" in result.stdout
+
+ def test_config_test_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "config", "test", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "connection" in result.stdout.lower()
+
+ def test_workflow_search_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "search", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "QUERY" in result.stdout
+
+ def test_workflow_bulk_activate_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "bulk-activate", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "--tag" in result.stdout
+ assert "--search" in result.stdout
+
+ def test_workflow_backup_all_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "backup-all", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "--dir" in result.stdout
+
+ def test_workflow_restore_all_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "restore-all", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "--dry-run" in result.stdout
+
+ def test_workflow_diff_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "diff", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "SOURCE" in result.stdout
+
+ def test_execution_errors_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "execution", "errors", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "--details" in result.stdout
+
+ def test_template_search_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "template", "search", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "QUERY" in result.stdout
+
+ def test_template_deploy_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "template", "deploy", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "TEMPLATE_ID" in result.stdout
+
+ def test_workflow_validate_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "validate", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "SOURCE" in result.stdout
+
+ def test_workflow_test_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "test", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "WORKFLOW_ID" in result.stdout
+
+ def test_workflow_autofix_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "autofix", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "--apply" in result.stdout
+
+ def test_workflow_patch_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "patch", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "--rename" in result.stdout
+ assert "--enable-node" in result.stdout
+ assert "--remove-node" in result.stdout
+ assert "--connect" in result.stdout
+
+ def test_health_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "health", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "--diagnostic" in result.stdout
+
+ def test_workflow_versions_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "versions", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "rollback" in result.stdout
+ assert "prune" in result.stdout
+ assert "stats" in result.stdout
+
+ def test_workflow_scaffold_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "scaffold", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "webhook" in result.stdout
+ assert "ai-agent" in result.stdout
+
+ def test_workflow_patterns(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "workflow", "patterns"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "webhook" in result.stdout
+ assert "database" in result.stdout
+
+ def test_expression_validate_valid(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "expression", "={{$json.name}}"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "valid" in result.stdout.lower()
+
+ def test_expression_validate_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "expression", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+
+ def test_node_search_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "node", "search", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "QUERY" in result.stdout
+
+ def test_node_info_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "node", "info", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "PACKAGE_NAME" in result.stdout
+
+ def test_completions_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "completions", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "bash" in result.stdout
+
+ def test_credential_help(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "credential", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+ assert "create" in result.stdout
+ assert "schema" in result.stdout
+ assert "transfer" in result.stdout
+ # "list" command should not appear as a subcommand
+ lines = [line.strip() for line in result.stdout.splitlines()]
+ subcommands = [line for line in lines if line and not line.startswith("Usage") and not line.startswith("-") and not line.startswith("Options") and not line.startswith("Credential")]
+ assert not any(line.startswith("list") for line in subcommands)
+
+ def test_config_show_json(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "--json", "config", "show"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode == 0
+
+ def test_no_table_command(self):
+ result = subprocess.run(
+ [*_resolve_cli(), "table", "--help"], capture_output=True, text=True, timeout=10,
+ )
+ assert result.returncode != 0 # table command removed
+
+
+# ─── E2E tests (n8n required) ──────────────────────────────────────────────
+
+class TestWorkflowsE2E:
+ def test_list_workflows(self):
+ _skip_if_no_n8n()
+ result = workflows.list_workflows(base_url=N8N_URL, api_key=N8N_KEY, limit=5)
+ assert "data" in result
+
+ def test_workflow_crud(self):
+ _skip_if_no_n8n()
+ wf = workflows.create_workflow(
+ {"name": "CLI-Anything Test WF", "nodes": [], "connections": {}, "settings": {}},
+ base_url=N8N_URL, api_key=N8N_KEY,
+ )
+ wf_id = wf["id"]
+
+ try:
+ detail = workflows.get_workflow(wf_id, base_url=N8N_URL, api_key=N8N_KEY)
+ assert detail["name"] == "CLI-Anything Test WF"
+
+ updated = workflows.update_workflow(
+ wf_id,
+ {"name": "CLI-Anything Test WF Updated", "nodes": [], "connections": {}, "settings": {}},
+ base_url=N8N_URL, api_key=N8N_KEY,
+ )
+ assert updated["name"] == "CLI-Anything Test WF Updated"
+ finally:
+ workflows.delete_workflow(wf_id, base_url=N8N_URL, api_key=N8N_KEY)
+
+ try:
+ workflows.get_workflow(wf_id, base_url=N8N_URL, api_key=N8N_KEY)
+ assert False, "Workflow should have been deleted"
+ except req.exceptions.HTTPError as e:
+ assert e.response.status_code == 404
+
+
+class TestCredentialsE2E:
+ def test_get_schema(self):
+ _skip_if_no_n8n()
+ result = credentials.get_credential_schema("httpBasicAuth", base_url=N8N_URL, api_key=N8N_KEY)
+ assert isinstance(result, (dict, list))
+
+
+class TestVariablesE2E:
+ def test_list_variables(self):
+ _skip_if_no_n8n()
+ try:
+ result = variables.list_variables(base_url=N8N_URL, api_key=N8N_KEY)
+ assert isinstance(result, (list, dict))
+ except req.exceptions.HTTPError as e:
+ if e.response.status_code == 403:
+ pytest.skip("Variables API requires Enterprise license")
+ raise
+
+
+class TestTagsE2E:
+ def test_list_tags(self):
+ _skip_if_no_n8n()
+ result = tags.list_tags(base_url=N8N_URL, api_key=N8N_KEY)
+ assert isinstance(result, (list, dict))
+
+ def test_tag_lifecycle(self):
+ _skip_if_no_n8n()
+ unique_name = f"CLITEST{uuid.uuid4().hex[:8].upper()}"
+
+ tag = tags.create_tag(unique_name, base_url=N8N_URL, api_key=N8N_KEY)
+ tag_id = tag["id"]
+
+ try:
+ all_tags = tags.list_tags(base_url=N8N_URL, api_key=N8N_KEY)
+ data = all_tags.get("data", all_tags) if isinstance(all_tags, dict) else all_tags
+ names = [t["name"] for t in data if isinstance(t, dict)]
+ assert unique_name in names
+
+ updated_name = f"{unique_name}UPD"
+ updated = tags.update_tag(tag_id, updated_name, base_url=N8N_URL, api_key=N8N_KEY)
+ assert updated["name"] == updated_name
+ finally:
+ tags.delete_tag(tag_id, base_url=N8N_URL, api_key=N8N_KEY)
diff --git a/n8n/agent-harness/cli_anything/n8n/utils/__init__.py b/n8n/agent-harness/cli_anything/n8n/utils/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/n8n/agent-harness/cli_anything/n8n/utils/n8n_backend.py b/n8n/agent-harness/cli_anything/n8n/utils/n8n_backend.py
new file mode 100644
index 000000000..c68b2827c
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/utils/n8n_backend.py
@@ -0,0 +1,101 @@
+"""n8n REST API client — single module that handles all HTTP communication."""
+
+from __future__ import annotations
+
+import json
+import os
+from typing import Any
+
+import requests
+
+
+try:
+ DEFAULT_TIMEOUT = int(os.environ.get("N8N_TIMEOUT", "30"))
+except (TypeError, ValueError):
+ DEFAULT_TIMEOUT = 30
+
+# n8n Public API version supported
+MIN_N8N_VERSION = "1.0.0"
+API_VERSION = "v1"
+
+
+def _get_base_url() -> str:
+ return os.environ.get("N8N_BASE_URL", "").rstrip("/")
+
+
+def _get_api_key() -> str:
+ return os.environ.get("N8N_API_KEY", "")
+
+
+def _headers(api_key: str | None = None) -> dict[str, str]:
+ key = api_key or _get_api_key()
+ h: dict[str, str] = {"Content-Type": "application/json"}
+ if key:
+ h["X-N8N-API-KEY"] = key
+ return h
+
+
+def _url(base_url: str | None, path: str) -> str:
+ base = (base_url or _get_base_url()).rstrip("/")
+ if not base:
+ raise ValueError(
+ "n8n base URL not configured. Set N8N_BASE_URL env var or pass --url."
+ )
+ api_prefix = f"/api/{API_VERSION}"
+ if path.startswith("/api/"):
+ return f"{base}{path}"
+ return f"{base}{api_prefix}{path}"
+
+
+def _handle_response(resp: requests.Response) -> Any:
+ if resp.status_code == 204:
+ return {}
+ try:
+ return resp.json()
+ except (json.JSONDecodeError, ValueError):
+ return {"raw": resp.text}
+
+
+def api_request(
+ method: str,
+ endpoint: str,
+ *,
+ base_url: str | None = None,
+ api_key: str | None = None,
+ params: dict[str, Any] | None = None,
+ json_data: Any | None = None,
+ timeout: int | None = None,
+) -> Any:
+ """Execute an HTTP request against the n8n API."""
+ url = _url(base_url, endpoint)
+ headers = _headers(api_key)
+ resp = requests.request(
+ method,
+ url,
+ headers=headers,
+ params=params,
+ json=json_data,
+ timeout=timeout or DEFAULT_TIMEOUT,
+ )
+ resp.raise_for_status()
+ return _handle_response(resp)
+
+
+def api_get(endpoint: str, *, base_url: str | None = None, api_key: str | None = None, params: dict[str, Any] | None = None) -> Any:
+ return api_request("GET", endpoint, base_url=base_url, api_key=api_key, params=params)
+
+
+def api_post(endpoint: str, data: Any | None = None, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_request("POST", endpoint, base_url=base_url, api_key=api_key, json_data=data)
+
+
+def api_put(endpoint: str, data: Any | None = None, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_request("PUT", endpoint, base_url=base_url, api_key=api_key, json_data=data)
+
+
+def api_patch(endpoint: str, data: Any | None = None, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_request("PATCH", endpoint, base_url=base_url, api_key=api_key, json_data=data)
+
+
+def api_delete(endpoint: str, *, base_url: str | None = None, api_key: str | None = None) -> Any:
+ return api_request("DELETE", endpoint, base_url=base_url, api_key=api_key)
diff --git a/n8n/agent-harness/cli_anything/n8n/utils/repl_skin.py b/n8n/agent-harness/cli_anything/n8n/utils/repl_skin.py
new file mode 100644
index 000000000..c9419593e
--- /dev/null
+++ b/n8n/agent-harness/cli_anything/n8n/utils/repl_skin.py
@@ -0,0 +1,591 @@
+"""cli-anything REPL Skin — Unified terminal interface for all CLI harnesses.
+
+Copy this file into your CLI package at:
+ cli_anything/<software>/utils/repl_skin.py
+
+Usage:
+ from cli_anything.<software>.utils.repl_skin import ReplSkin
+
+ skin = ReplSkin("shotcut", version="1.0.0")
+ skin.print_banner() # auto-detects skills/SKILL.md inside the package
+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)
+ skin.success("Project saved")
+ skin.error("File not found")
+ skin.warning("Unsaved changes")
+ skin.info("Processing 24 clips...")
+ skin.status("Track 1", "3 clips, 00:02:30")
+ skin.table(headers, rows)
+ skin.print_goodbye()
+"""
+
+import os
+import sys
+
+# ── ANSI color codes (no external deps for core styling) ──────────────
+
+_RESET = "\033[0m"
+_BOLD = "\033[1m"
+_DIM = "\033[2m"
+_ITALIC = "\033[3m"
+_UNDERLINE = "\033[4m"
+
+# Brand colors
+_CYAN = "\033[38;5;80m" # cli-anything brand cyan
+_CYAN_BG = "\033[48;5;80m"
+_WHITE = "\033[97m"
+_GRAY = "\033[38;5;245m"
+_DARK_GRAY = "\033[38;5;240m"
+_LIGHT_GRAY = "\033[38;5;250m"
+
+# Software accent colors — each software gets a unique accent
+_ACCENT_COLORS = {
+ "gimp": "\033[38;5;214m", # warm orange
+ "blender": "\033[38;5;208m", # deep orange
+ "inkscape": "\033[38;5;39m", # bright blue
+ "audacity": "\033[38;5;33m", # navy blue
+ "libreoffice": "\033[38;5;40m", # green
+ "obs_studio": "\033[38;5;55m", # purple
+ "kdenlive": "\033[38;5;69m", # slate blue
+ "shotcut": "\033[38;5;35m", # teal green
+ "anygen": "\033[38;5;141m", # soft violet
+ "novita": "\033[38;5;81m", # vivid blue (for Novita AI)
+ "rms": "\033[38;5;27m", # Teltonika blue
+}
+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue
+
+# Status colors
+_GREEN = "\033[38;5;78m"
+_YELLOW = "\033[38;5;220m"
+_RED = "\033[38;5;196m"
+_BLUE = "\033[38;5;75m"
+_MAGENTA = "\033[38;5;176m"
+
+# ── Brand icon ────────────────────────────────────────────────────────
+
+# The cli-anything icon: a small colored diamond/chevron mark
+_ICON = f"{_CYAN}{_BOLD}◆{_RESET}"
+_ICON_SMALL = f"{_CYAN}▸{_RESET}"
+
+# ── Box drawing characters ────────────────────────────────────────────
+
+_H_LINE = "─"
+_V_LINE = "│"
+_TL = "╭"
+_TR = "╮"
+_BL = "╰"
+_BR = "╯"
+_T_DOWN = "┬"
+_T_UP = "┴"
+_T_RIGHT = "├"
+_T_LEFT = "┤"
+_CROSS = "┼"
+
+
+def _strip_ansi(text: str) -> str:
+ """Remove ANSI escape codes for length calculation."""
+ import re
+ return re.sub(r"\033\[[^m]*m", "", text)
+
+
+def _visible_len(text: str) -> int:
+ """Get visible length of text (excluding ANSI codes)."""
+ return len(_strip_ansi(text))
+
+
+class ReplSkin:
+ """Unified REPL skin for cli-anything CLIs.
+
+ Provides consistent branding, prompts, and message formatting
+ across all CLI harnesses built with the cli-anything methodology.
+ """
+
+ def __init__(self, software: str, version: str = "1.0.0",
+ history_file: str | None = None, skill_path: str | None = None):
+ """Initialize the REPL skin.
+
+ Args:
+ software: Software name (e.g., "gimp", "shotcut", "blender").
+ version: CLI version string.
+ history_file: Path for persistent command history.
+ Defaults to ~/.cli-anything-<software>/history
+ skill_path: Path to the SKILL.md file for agent discovery.
+ Auto-detected from the package's skills/ directory if not provided.
+ Displayed in banner for AI agents to know where to read skill info.
+ """
+ self.software = software.lower().replace("-", "_")
+ self.display_name = software.replace("_", " ").title()
+ self.version = version
+
+ # Auto-detect skill path from package layout:
+ # cli_anything/<software>/utils/repl_skin.py (this file)
+ # cli_anything/<software>/skills/SKILL.md (target)
+ if skill_path is None:
+ from pathlib import Path
+ _auto = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"
+ if _auto.is_file():
+ skill_path = str(_auto)
+ self.skill_path = skill_path
+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)
+
+ # History file
+ if history_file is None:
+ from pathlib import Path
+ hist_dir = Path.home() / f".cli-anything-{self.software}"
+ hist_dir.mkdir(parents=True, exist_ok=True)
+ self.history_file = str(hist_dir / "history")
+ else:
+ self.history_file = history_file
+
+ # Detect terminal capabilities
+ self._color = self._detect_color_support()
+
+ def _detect_color_support(self) -> bool:
+ """Check if terminal supports color."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):
+ return False
+ if not hasattr(sys.stdout, "isatty"):
+ return False
+ return sys.stdout.isatty()
+
+ def _c(self, code: str, text: str) -> str:
+ """Apply color code if colors are supported."""
+ if not self._color:
+ return text
+ return f"{code}{text}{_RESET}"
+
+ # ── Banner ────────────────────────────────────────────────────────
+
+ def print_banner(self):
+ """Print the startup banner with branding."""
+ inner = 54
+
+ def _box_line(content: str) -> str:
+ """Wrap content in box drawing, padding to inner width."""
+ pad = inner - _visible_len(content)
+ vl = self._c(_DARK_GRAY, _V_LINE)
+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"
+
+ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")
+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")
+
+ # Title: ◆ cli-anything · Shotcut
+ icon = self._c(_CYAN + _BOLD, "◆")
+ brand = self._c(_CYAN + _BOLD, "cli-anything")
+ dot = self._c(_DARK_GRAY, "·")
+ name = self._c(self.accent + _BOLD, self.display_name)
+ title = f" {icon} {brand} {dot} {name}"
+
+ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"
+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"
+ empty = ""
+
+ # Skill path for agent discovery
+ skill_line = None
+ if self.skill_path:
+ skill_icon = self._c(_MAGENTA, "◇")
+ skill_label = self._c(_DARK_GRAY, " Skill:")
+ skill_path_display = self._c(_LIGHT_GRAY, self.skill_path)
+ skill_line = f" {skill_icon} {skill_label} {skill_path_display}"
+
+ print(top)
+ print(_box_line(title))
+ print(_box_line(ver))
+ if skill_line:
+ print(_box_line(skill_line))
+ print(_box_line(empty))
+ print(_box_line(tip))
+ print(bot)
+ print()
+
+ # ── Prompt ────────────────────────────────────────────────────────
+
+ def prompt(self, project_name: str = "", modified: bool = False,
+ context: str = "") -> str:
+ """Build a styled prompt string for prompt_toolkit or input().
+
+ Args:
+ project_name: Current project name (empty if none open).
+ modified: Whether the project has unsaved changes.
+ context: Optional extra context to show in prompt.
+
+ Returns:
+ Formatted prompt string.
+ """
+ parts = []
+
+ # Icon
+ if self._color:
+ parts.append(f"{_CYAN}◆{_RESET} ")
+ else:
+ parts.append("> ")
+
+ # Software name
+ parts.append(self._c(self.accent + _BOLD, self.software))
+
+ # Project context
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ parts.append(f" {self._c(_DARK_GRAY, '[')}")
+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))
+ parts.append(self._c(_DARK_GRAY, ']'))
+
+ parts.append(self._c(_GRAY, " ❯ "))
+
+ return "".join(parts)
+
+ def prompt_tokens(self, project_name: str = "", modified: bool = False,
+ context: str = ""):
+ """Build prompt_toolkit formatted text tokens for the prompt.
+
+ Use with prompt_toolkit's FormattedText for proper ANSI handling.
+
+ Returns:
+ list of (style, text) tuples for prompt_toolkit.
+ """
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+ tokens = []
+
+ tokens.append(("class:icon", "◆ "))
+ tokens.append(("class:software", self.software))
+
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ tokens.append(("class:bracket", " ["))
+ tokens.append(("class:context", f"{ctx}{mod}"))
+ tokens.append(("class:bracket", "]"))
+
+ tokens.append(("class:arrow", " ❯ "))
+
+ return tokens
+
+ def get_prompt_style(self):
+ """Get a prompt_toolkit Style object matching the skin.
+
+ Returns:
+ prompt_toolkit.styles.Style
+ """
+ try:
+ from prompt_toolkit.styles import Style
+ except ImportError:
+ return None
+
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+
+ return Style.from_dict({
+ "icon": "#5fdfdf bold", # cyan brand color
+ "software": f"{accent_hex} bold",
+ "bracket": "#585858",
+ "context": "#bcbcbc",
+ "arrow": "#808080",
+ # Completion menu
+ "completion-menu.completion": "bg:#303030 #bcbcbc",
+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",
+ "completion-menu.meta.completion": "bg:#303030 #808080",
+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",
+ # Auto-suggest
+ "auto-suggest": "#585858",
+ # Bottom toolbar
+ "bottom-toolbar": "bg:#1c1c1c #808080",
+ "bottom-toolbar.text": "#808080",
+ })
+
+ # ── Messages ──────────────────────────────────────────────────────
+
+ def success(self, message: str):
+ """Print a success message with green checkmark."""
+ icon = self._c(_GREEN + _BOLD, "✓")
+ print(f" {icon} {self._c(_GREEN, message)}")
+
+ def error(self, message: str):
+ """Print an error message with red cross."""
+ icon = self._c(_RED + _BOLD, "✗")
+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)
+
+ def warning(self, message: str):
+ """Print a warning message with yellow triangle."""
+ icon = self._c(_YELLOW + _BOLD, "⚠")
+ print(f" {icon} {self._c(_YELLOW, message)}")
+
+ def info(self, message: str):
+ """Print an info message with blue dot."""
+ icon = self._c(_BLUE, "●")
+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")
+
+ def hint(self, message: str):
+ """Print a subtle hint message."""
+ print(f" {self._c(_DARK_GRAY, message)}")
+
+ def section(self, title: str):
+ """Print a section header."""
+ print()
+ print(f" {self._c(self.accent + _BOLD, title)}")
+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")
+
+ # ── Status display ────────────────────────────────────────────────
+
+ def status(self, label: str, value: str):
+ """Print a key-value status line."""
+ lbl = self._c(_GRAY, f" {label}:")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def status_block(self, items: dict[str, str], title: str = ""):
+ """Print a block of status key-value pairs.
+
+ Args:
+ items: Dict of label -> value pairs.
+ title: Optional title for the block.
+ """
+ if title:
+ self.section(title)
+
+ max_key = max(len(k) for k in items) if items else 0
+ for label, value in items.items():
+ lbl = self._c(_GRAY, f" {label:<{max_key}}")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def progress(self, current: int, total: int, label: str = ""):
+ """Print a simple progress indicator.
+
+ Args:
+ current: Current step number.
+ total: Total number of steps.
+ label: Optional label for the progress.
+ """
+ pct = int(current / total * 100) if total > 0 else 0
+ bar_width = 20
+ filled = int(bar_width * current / total) if total > 0 else 0
+ bar = "█" * filled + "░" * (bar_width - filled)
+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"
+ if label:
+ text += f" {self._c(_LIGHT_GRAY, label)}"
+ print(text)
+
+ # ── Table display ─────────────────────────────────────────────────
+
+ def table(self, headers: list[str], rows: list[list[str]],
+ max_col_width: int = 40):
+ """Print a formatted table with box-drawing characters.
+
+ Args:
+ headers: Column header strings.
+ rows: List of rows, each a list of cell strings.
+ max_col_width: Maximum column width before truncation.
+ """
+ if not headers:
+ return
+
+ # Calculate column widths
+ col_widths = [min(len(h), max_col_width) for h in headers]
+ for row in rows:
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ col_widths[i] = min(
+ max(col_widths[i], len(str(cell))), max_col_width
+ )
+
+ def pad(text: str, width: int) -> str:
+ t = str(text)[:width]
+ return t + " " * (width - len(t))
+
+ # Header
+ header_cells = [
+ self._c(_CYAN + _BOLD, pad(h, col_widths[i]))
+ for i, h in enumerate(headers)
+ ]
+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ header_line = f" {sep.join(header_cells)}"
+ print(header_line)
+
+ # Separator
+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]
+ sep_line = self._c(_DARK_GRAY, f" {'───'.join([_H_LINE * w for w in col_widths])}")
+ print(sep_line)
+
+ # Rows
+ for row in rows:
+ cells = []
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))
+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ print(f" {row_sep.join(cells)}")
+
+ # ── Help display ──────────────────────────────────────────────────
+
+ def help(self, commands: dict[str, str]):
+ """Print a formatted help listing.
+
+ Args:
+ commands: Dict of command -> description pairs.
+ """
+ self.section("Commands")
+ max_cmd = max(len(c) for c in commands) if commands else 0
+ for cmd, desc in commands.items():
+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")
+ desc_styled = self._c(_GRAY, f" {desc}")
+ print(f"{cmd_styled}{desc_styled}")
+ print()
+
+ # ── Goodbye ───────────────────────────────────────────────────────
+
+ def print_goodbye(self):
+ """Print a styled goodbye message."""
+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")
+
+ # ── Prompt toolkit session factory ────────────────────────────────
+
+ def create_prompt_session(self):
+ """Create a prompt_toolkit PromptSession with skin styling.
+
+ Returns:
+ A configured PromptSession, or None if prompt_toolkit unavailable.
+ """
+ try:
+ from prompt_toolkit import PromptSession
+ from prompt_toolkit.history import FileHistory
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
+ from prompt_toolkit.formatted_text import FormattedText
+
+ style = self.get_prompt_style()
+
+ session = PromptSession(
+ history=FileHistory(self.history_file),
+ auto_suggest=AutoSuggestFromHistory(),
+ style=style,
+ enable_history_search=True,
+ )
+ return session
+ except ImportError:
+ return None
+
+ def get_input(self, pt_session, project_name: str = "",
+ modified: bool = False, context: str = "") -> str:
+ """Get input from user using prompt_toolkit or fallback.
+
+ Args:
+ pt_session: A prompt_toolkit PromptSession (or None).
+ project_name: Current project name.
+ modified: Whether project has unsaved changes.
+ context: Optional context string.
+
+ Returns:
+ User input string (stripped).
+ """
+ if pt_session is not None:
+ from prompt_toolkit.formatted_text import FormattedText
+ tokens = self.prompt_tokens(project_name, modified, context)
+ return pt_session.prompt(FormattedText(tokens)).strip()
+ else:
+ raw_prompt = self.prompt(project_name, modified, context)
+ return input(raw_prompt).strip()
+
+ # ── Toolbar builder ───────────────────────────────────────────────
+
+ def bottom_toolbar(self, items: dict[str, str]):
+ """Create a bottom toolbar callback for prompt_toolkit.
+
+ Args:
+ items: Dict of label -> value pairs to show in toolbar.
+
+ Returns:
+ A callable that returns FormattedText for the toolbar.
+ """
+ def toolbar():
+ from prompt_toolkit.formatted_text import FormattedText
+ parts = []
+ for i, (k, v) in enumerate(items.items()):
+ if i > 0:
+ parts.append(("class:bottom-toolbar.text", " │ "))
+ parts.append(("class:bottom-toolbar.text", f" {k}: "))
+ parts.append(("class:bottom-toolbar", v))
+ return FormattedText(parts)
+ return toolbar
+
+
+# ── ANSI 256-color to hex mapping (for prompt_toolkit styles) ─────────
+
+_ANSI_256_TO_HEX = {
+ "\033[38;5;33m": "#0087ff", # audacity navy blue
+ "\033[38;5;35m": "#00af5f", # shotcut teal
+ "\033[38;5;39m": "#00afff", # inkscape bright blue
+ "\033[38;5;40m": "#00d700", # libreoffice green
+ "\033[38;5;55m": "#5f00af", # obs purple
+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue
+ "\033[38;5;75m": "#5fafff", # default sky blue
+ "\033[38;5;80m": "#5fd7d7", # brand cyan
+ "\033[38;5;208m": "#ff8700", # blender deep orange
+ "\033[38;5;214m": "#ffaf00", # gimp warm orange
+}
+
+
+# ─── Module-level wrappers ─────────────────────────────────────────────────
+# n8n harness imports these as module functions. Lazy-init to avoid
+# import-time filesystem side effects.
+
+import json as _json
+import click as _click
+
+_skin = None
+
+
+def _get_skin() -> ReplSkin:
+ global _skin
+ if _skin is None:
+ _skin = ReplSkin("n8n")
+ return _skin
+
+
+def output(data, as_json: bool = False) -> None:
+ """Display data as JSON or formatted table/dict."""
+ if as_json:
+ _click.echo(_json.dumps(data, indent=2, default=str))
+ return
+ skin = _get_skin()
+ if isinstance(data, dict):
+ if "data" in data and isinstance(data["data"], list):
+ rows = data["data"]
+ if rows and isinstance(rows[0], dict):
+ headers = list(rows[0].keys())[:8]
+ table_rows = [[str(r.get(h, ""))[:30] for h in headers] for r in rows]
+ skin.table(headers, table_rows)
+ else:
+ _click.echo(_json.dumps(data, indent=2, default=str))
+ if data.get("nextCursor"):
+ skin.hint(f"Next cursor: {data['nextCursor']}")
+ else:
+ for k, v in data.items():
+ skin.status(str(k), str(v)[:80])
+ elif isinstance(data, list):
+ if data and isinstance(data[0], dict):
+ headers = list(data[0].keys())[:8]
+ table_rows = [[str(r.get(h, ""))[:30] for h in headers] for r in data]
+ skin.table(headers, table_rows)
+ else:
+ _click.echo(_json.dumps(data, indent=2, default=str))
+ else:
+ _click.echo(str(data))
+
+
+def error(msg: str) -> None:
+ _get_skin().error(msg)
+
+
+def success(msg: str) -> None:
+ _get_skin().success(msg)
+
+
+def warn(msg: str) -> None:
+ _get_skin().warning(msg)
+
+
+def print_banner(url: str = "") -> None:
+ skin = _get_skin()
+ skin.print_banner()
+ if url:
+ skin.info(f"URL: {url}")
diff --git a/n8n/agent-harness/setup.py b/n8n/agent-harness/setup.py
new file mode 100644
index 000000000..5b49056ed
--- /dev/null
+++ b/n8n/agent-harness/setup.py
@@ -0,0 +1,17 @@
+#!/usr/bin/env python3
+from setuptools import setup, find_namespace_packages
+with open("cli_anything/n8n/README.md", "r", encoding="utf-8") as fh:
+ long_description = fh.read()
+setup(
+ name="cli-anything-n8n", version="2.4.5",
+ author="Juan Jose Sanchez Bernal", author_email="[email protected]",
+ description="CLI harness for n8n workflow automation — 55+ commands. Requires: N8N_BASE_URL, N8N_API_KEY",
+ long_description=long_description, long_description_content_type="text/markdown",
+ url="https://github.com/HKUDS/CLI-Anything",
+ packages=find_namespace_packages(include=["cli_anything.*"]),
+ python_requires=">=3.10",
+ install_requires=["click>=8.0.0", "requests>=2.28.0", "prompt-toolkit>=3.0.0"],
+ entry_points={"console_scripts": ["cli-anything-n8n=cli_anything.n8n.n8n_cli:main"]},
+ package_data={"cli_anything.n8n": ["skills/*.md", "README.md"]},
+ include_package_data=True, zip_safe=False,
+)
diff --git a/registry.json b/registry.json
index deb1fab1e..2513a8f49 100644
--- a/registry.json
+++ b/registry.json
@@ -522,6 +522,20 @@
"category": "ai",
"contributor": "Akabane71",
"contributor_url": "https://github.com/Akabane71"
+ },
+ {
+ "name": "n8n",
+ "display_name": "n8n",
+ "version": "2.4.7",
+ "description": "Workflow automation via n8n REST API — 55+ commands",
+ "requires": "n8n >= 1.0.0",
+ "homepage": "https://n8n.io",
+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=n8n/agent-harness",
+ "entry_point": "cli-anything-n8n",
+ "skill_md": "n8n/agent-harness/cli_anything/n8n/skills/SKILL.md",
+ "category": "automation",
+ "contributor": "webcomunicasolutions",
+ "contributor_url": "https://github.com/webcomunicasolutions"
}
]
}