npm package: @flowdot.ai/cli
Description: Official CLI for FlowDot - Execute workflows, send messages to the agent, and manage your account from the command line
Author: FlowDot
Latest version: 1.0.0

# FlowDot CLI

**The official command-line interface for FlowDot** - an AI workflow automation platform.

FlowDot CLI enables you to run AI agents, execute recipes (multi-step AI workflows), browse and manage models, and interact with the FlowDot platform directly from your terminal.

## Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Authentication](#authentication)
- [Security Model](#security-model)
- [Prompt Injection](#prompt-injection)
- [Commands Overview](#commands-overview)
- [Shell Escape Commands](#shell-escape-commands)
- [Agent Mode](#agent-mode)
- [Chat Persistence](#chat-persistence)
- [Recipes System](#recipes-system)
- [Workflows](#workflows)
- [Tasks and Planning](#tasks-and-planning)
- [Model System](#model-system)
- [MCP Integration](#mcp-integration)
- [COMMS Relay System](#comms-relay-system)
- [Loops System](#loops-system)
- [Public Toolkits](#public-toolkits)
- [Testing](#testing)
- [Configuration](#configuration)
- [Architecture](#architecture)
- [Development](#development)

---

## Installation

### Requirements

- **Node.js** >= 20.0.0
- **npm** >= 9.0.0

### Install from npm

```bash
npm install -g @flowdot.ai/cli
```

### Install from source

```bash
git clone https://github.com/flowdot-llc/flowdot-cli.git
cd flowdot-cli
npm install
npm run build
npm link
```

### Verify Installation

```bash
flowdot --version
```

---

## Quick Start

```bash
# 1. Authenticate with FlowDot
flowdot auth login

# 2. Run an agent with a task
flowdot "Explain what this project does"

# 3. Start interactive chat
flowdot chat

# 4. Browse available models
flowdot models

# 5. List and run recipes
flowdot recipes list
flowdot recipes run my-recipe
```

---

## Authentication

FlowDot CLI uses **browser-based OAuth 2.0** for secure authentication.

### Login

```bash
flowdot auth login
```

This will:
1. Open your default browser to the FlowDot login page
2. Poll for authentication completion (up to 10 minutes)
3. Store the token securely using your OS credential manager

### Check Status

```bash
flowdot auth status
```

### Logout

```bash
flowdot auth logout
```

### Token Storage

Tokens are stored securely via **keytar** (OS credential manager):
- **macOS**: Keychain
- **Windows**: Credential Vault
- **Linux**: Secret Service API / libsecret

## Security Model

FlowDot CLI follows a **zero-trust** model for local actions and remote resources.

That means:

- External content is treated as untrusted data, even when it comes from an allowed domain
- MCP metadata, toolkit metadata, recipe content, COMMS content, and `@file` prompt attachments are not trusted as instructions
- High-impact actions such as shell execution, file writes, and remote control flows require explicit authorization
- Production API and Hub endpoints must use HTTPS; plaintext HTTP is only allowed for loopback/local development endpoints such as `http://127.0.0.1:8000`

Important trust boundaries in this CLI include:

- local files and workspaces
- shell commands
- web pages and search-result content
- MCP servers and toolkit tools
- COMMS relay and daemon messages
- model-visible prompt content

## Prompt Injection

Prompt injection is the AI-native version of implicit trust. In FlowDot CLI, the following should always be treated as hostile or potentially hostile data:

- web pages and search results
- comments, documentation, and copied text
- MCP tool descriptions and outputs
- toolkit descriptions and outputs
- recipe content from remote sources
- local file contents included with `@file`
- COMMS messages from remote channels

Practical guidance:

- Do not assume an approved domain implies trusted content
- Do not treat tool descriptions or page text as policy
- Review any consequential action carefully if it follows external research or remote content
- Prefer explicit local approval for commands or file changes that were proposed after browsing, MCP usage, toolkit usage, or COMMS interaction

---

## Commands Overview

```
flowdot [prompt...]                    Run agent with a prompt (default command)
flowdot chat                           Interactive chat mode
flowdot --resume <chat-id>             Resume a previous chat session
flowdot agent <request>                Run agent with options
flowdot ask <request>                  Alias for agent

flowdot chats list                     List recent chat sessions
flowdot chats show <id>                Show chat details and preview
flowdot chats delete <id>              Delete a specific chat
flowdot chats clear                    Clear all saved chats

flowdot auth login                     Authenticate with FlowDot
flowdot auth logout                    Clear stored credentials
flowdot auth status                    Check authentication status

flowdot config get                     View current configuration
flowdot config set-model <tier>        Set default model tier
flowdot config set-url <url>           Set API server URL
flowdot config models                  View model tier mappings
flowdot config set-tier <tier> <model> Set specific tier mapping
flowdot config clear-tier <tier>       Reset tier to default
flowdot config permissions             View saved permissions
flowdot config clear-permissions       Clear all saved permissions

flowdot models                         Interactive model browser
flowdot models --search <query>        Search for models
flowdot models --list                  List all available models

flowdot recipes list                   List linked recipes
flowdot recipes browse                 Browse community recipes
flowdot recipes run <alias|hash>       Execute a recipe
flowdot recipes link <hash> <alias>    Create a CLI alias for a recipe
flowdot recipes unlink <alias>         Remove a recipe alias
flowdot recipes show <hash>            View recipe details
flowdot recipes export <hash>          Export recipe definition
```

---

## Shell Escape Commands

During interactive chat mode, you can execute shell commands directly by prefixing them with `!`. This provides quick access to your terminal without leaving the chat session.

### Usage

```bash
# In flowdot chat mode:
> !ls                    # List files in current directory
> !cd ..                 # Change to parent directory
> !git status            # Check git status
> !npm install           # Run npm install
> !pwd                   # Print working directory
```

### How It Works

- Commands prefixed with `!` are passed directly to your system shell
- Output is displayed inline in the chat
- The working directory context is preserved between commands
- No AI processing occurs—the command runs exactly as typed

### Examples

```bash
$ flowdot chat
> !ls -la
total 24
drwxr-xr-x  5 user  staff   160 Mar 20 10:00 .
drwxr-xr-x 10 user  staff   320 Mar 20 09:00 ..
-rw-r--r--  1 user  staff  1234 Mar 20 10:00 package.json
-rw-r--r--  1 user  staff   567 Mar 20 10:00 tsconfig.json

> !git branch
* main
  feature/new-feature

> Now explain what this project does
# AI responds normally to non-! prefixed messages
```

### Notes

- Shell escape commands bypass the permission system since you are explicitly requesting execution
- Use standard shell syntax for your platform (bash on macOS/Linux, cmd/PowerShell on Windows)
- Piping and redirection work as expected: `!ls | grep .ts`
- For complex commands, consider using quotes: `!echo "Hello World"`

---

## Agent Mode

The agent is FlowDot CLI's primary mode for executing complex tasks. It automatically plans, executes, and synthesizes results.

### Basic Usage

```bash
# Default: runs agent mode
flowdot "Review my React component and suggest optimizations"

# Explicit agent command
flowdot agent "Find all TODO comments in this project"
```

### Agent Options

```bash
flowdot agent "your request" \
  --model <tier>              # Model tier: simple, capable, complex
  --max-iterations <num>      # Max planning iterations (default: 3)
  --timeout <ms>              # Timeout in milliseconds (default: 600000)
  --no-loop-detection         # Disable infinite loop detection
  --no-recovery               # Disable error recovery mode
  --no-parallel               # Force sequential task execution
  --no-replan                 # Disable replanning on failure
  --continue-on-error         # Continue execution after task errors
  --no-code-analysis          # Disable code reading/analysis
  --no-web-search             # Disable web search capability
```

### What the Agent Can Do

- **Code Analysis**: Read, search, and analyze code files
- **File Operations**: Create and edit files (with permission)
- **Command Execution**: Run shell commands (with permission)
- **Web Search**: Search the web for information
- **Workflow Execution**: Run FlowDot workflows
- **Multi-Step Planning**: Break complex tasks into steps

### Example Session

```bash
$ flowdot "Explain the authentication flow in this codebase"

┌─ FlowDot Agent
│ Request: Explain the authentication flow in this codebase
└─

✔ Created plan with 3 tasks
  1. Search for authentication-related files
  2. Read key authentication files
  3. Analyze and synthesize findings

⠋ Executing tasks...
✔ Task 1: Found 5 auth-related files
✔ Task 2: Read auth.ts, middleware.ts, login.ts
✔ Task 3: Analysis complete

┌─ Response
│ The authentication flow works as follows:
│ 1. User initiates login via /auth/login endpoint...
│ [detailed explanation]
└─
```

---

## Chat Persistence

FlowDot CLI automatically saves your conversations for later review and resumption.

### Storage Location

Chat history is stored per-project in the `.flowdot/` directory:

```
<cwd>/.flowdot/
├── chats/
│   ├── index.json           # Chat index for listing
│   └── {chat-id}.json       # Individual chat files
└── logs/
    ├── {session-id}.log     # Session-specific debug logs
    └── latest.txt           # Points to current session log
```

### Resume Previous Chats

```bash
# Resume a previous chat by ID
flowdot --resume <chat-id>

# Example
flowdot --resume 32621990
```

When resuming, the conversation context is restored and you can continue where you left off.

### Chat Management Commands

```bash
# List recent chats
flowdot chats list
# Output:
# ID        UPDATED              MSGS  TITLE
# 32621990  a few seconds ago    2     Explain the authentication flow...
# a1b2c3d4  1 day ago            5     Fix the bug in login component

# Show chat details and preview
flowdot chats show <id>

# Delete a specific chat
flowdot chats delete <id>

# Clear all chats (with confirmation)
flowdot chats clear
```

### Session Logs

Each CLI session creates a unique log file for debugging:

```bash
# Session logs are automatically created at:
# .flowdot/logs/{session-id}.log

# The latest.txt file points to the current session
# .flowdot/logs/latest.txt
```

Log entries include timestamps, levels, and categories for easy debugging.

---

## Recipes System

Recipes are **reusable AI workflows** - multi-step programs that combine LLM reasoning with code execution, tool usage, and control flow.

### Core Concepts

**Recipes consist of:**
- **Steps**: Individual execution units (agent, loop, parallel, gate, branch, invoke)
- **Stores**: Data containers that persist across steps
- **Inputs/Outputs**: Recipe parameters and return values

### Step Types

| Type | Description |
|------|-------------|
| `agent` | LLM agent with tools and prompts |
| `loop` | Iterate over arrays (serial or parallel) |
| `parallel` | Run multiple steps concurrently |
| `gate` | Approval checkpoint or condition |
| `branch` | Conditional routing to different steps |
| `invoke` | Call another recipe as a subroutine |

### Recipe Commands

```bash
# List your linked recipes
flowdot recipes list
flowdot recipes ls        # Short form

# List recipes you own
flowdot recipes my

# Browse community recipes
flowdot recipes browse
flowdot recipes browse --search "code review"

# View recipe details
flowdot recipes show <hash>

# Execute a recipe
flowdot recipes run <alias>
flowdot recipes run <hash>

# Execute with input
flowdot recipes run my-recipe -i '{"input": "value"}'

# Execute with model override
flowdot recipes run my-recipe --model complex

# Dry run (validate without executing)
flowdot recipes run my-recipe --dry-run

# Link a recipe to a CLI alias
flowdot recipes link abc123 my-alias

# Unlink an alias
flowdot recipes unlink my-alias

# Export recipe definition
flowdot recipes export abc123 > recipe.yaml
```

### Recipe Shortcuts

Once linked, recipes can be run as top-level commands:

```bash
# If "code-reviewer" is linked as an alias:
flowdot code-reviewer "review my authentication code"

# Equivalent to:
flowdot recipes run code-reviewer "review my authentication code"
```

### Recipe Input

Pass structured input to recipes:

```bash
# JSON input
flowdot recipes run analyzer -i '{"files": ["src/app.ts"], "depth": "detailed"}'

# Simple string input (becomes inputs.request)
flowdot recipes run summarizer "Summarize the main features"
```

### Template Variables

Recipes use template interpolation with `{{variable}}` syntax:

```
{{inputs.request}}              # CLI task argument
{{stores.plan.tasks}}           # Store values
{{stores.corpus.files[0]}}      # Array access
{{loop.item}}                   # Current loop item
{{loop.index}}                  # Loop iteration number
```

### Approval Gates

Recipes can include approval gates that pause for user confirmation:

```bash
$ flowdot recipes run deploy-checker

✔ Step 1: Analyze changes
✔ Step 2: Check dependencies

┌─ Approval Required
│ The following changes will be deployed:
│ - Modified: src/api/users.ts
│ - Added: src/api/auth.ts
│
│ Proceed with deployment check? (y/n)
└─
> y

✔ Step 3: Validate deployment
✔ Recipe complete
```

### Rich User Input (Gate Steps)

Gate steps support rich user input collection with custom buttons and text fields:

```yaml
- id: ask-questions
  type: gate
  config:
    requires_approval: true
    approval_prompt: "Please answer the following questions:\n{{stores.questions}}"
    input_options:
      button_mode: custom
      buttons:
        - { label: "Submit Answers", value: "submit", isApproval: true, style: "primary" }
        - { label: "Skip Questions", value: "skip", isApproval: true, style: "secondary" }
      allow_comment: true
      comment_required: true
      comment_placeholder: "Type your answers here..."
    input_output_store: user_answers
  next: process-answers
```

**Input Options Configuration:**

| Option | Type | Description |
|--------|------|-------------|
| `button_mode` | `"preset"` \| `"custom"` | Use preset buttons or define custom ones |
| `preset` | `string` | Preset name: `"approve_deny"`, `"yes_no"`, `"continue_cancel"` |
| `buttons` | `array` | Custom button definitions with label, value, isApproval, style |
| `allow_comment` | `boolean` | Show text input field |
| `comment_required` | `boolean` | Require text input before submission |
| `comment_placeholder` | `string` | Placeholder text for input field |

**Response Format:**

User responses are stored in the configured `input_output_store`:

```json
{
  "action": "submit",
  "comment": "User's text input here",
  "timestamp": "2026-03-02T12:00:00Z",
  "timedOut": false
}
```

**Example: Dynamic Questions**

```bash
$ flowdot story-outliner "a mystery story set in space"

✔ Analyze Concept (19s)

┌─ Clarification Questions
│ 1. What tone do you envision - noir, cozy, or hard sci-fi?
│ 2. Should the detective be human or AI?
│ 3. What's the central mystery - murder, theft, or conspiracy?
│
│ [1] Submit Answers  [2] Skip Questions
└─
> 1

Enter your answers: Dark noir tone, human detective, conspiracy involving AI...

✔ Ask Clarification Questions (25s)
✔ Generate Outline (150s)
✔ Recipe complete
```

### Recipe Definition Structure

```yaml
name: code-reviewer
description: Reviews code and provides feedback
entry_step: analyze

stores:
  - key: corpus
    type: any
    is_input: false
  - key: findings
    type: any
    is_output: true

steps:
  - id: analyze
    type: agent
    config:
      user_prompt: "Analyze the following code: {{inputs.request}}"
      tools: ["read", "search", "analyze"]
      output_store: { store: "findings" }
    next: review

  - id: review
    type: agent
    config:
      user_prompt: "Review findings and provide recommendations: {{stores.findings}}"
      model_tier: complex
```

### Recipe Architecture Patterns

**Orchestrator + Workers** (most common):
```
1. Orchestrator → Analyzes request, generates sub-tasks
2. Worker Loop  → Runs agent for each sub-task
3. Synthesizer  → Combines results into final answer
```

**Sequential Pipeline:**
```
Parser → Validator → Transformer → Formatter
```

**Parallel Fan-Out:**
```
         ┌→ Task A ─┐
Request ─┼→ Task B ─┼→ Aggregator
         └→ Task C ─┘
```

### Designing for Small Models

Small models need **prescriptive prompt lecturing**. Tell them exactly what to do:

**Bad:**
```
Search for files related to the request.
```

**Good:**
```
### Step 1: Search for Related Files
Use the 'search' tool with keywords. Examples:
- For "how does authentication work" → search: auth, login, token
- For "how does routing work" → search: router, route, endpoint

Run at least 3 different searches with different keywords.
```

### Prompt Lecturing Principles

| Principle | Example |
|-----------|---------|
| Give concrete examples | Show exact search patterns |
| Quantify requirements | "Run at least 3 searches" |
| Provide fallback paths | "If no results, try broader terms" |
| Specify output format | "Return ONLY valid JSON array" |
| Prevent common failures | "DO NOT make up file paths" |

### Recipe Debugging

Enable debug logging:
```bash
DEBUG=RECIPE flowdot recipes run my-recipe --input '{"request":"test"}'
```

Executions saved to `.flowdot/executions/{recipe-name}/{execution-id}/`.

---

## Workflows

FlowDot CLI integrates with FlowDot's visual workflow system, allowing you to discover and execute workflows from the command line.

### Workflow Discovery

The agent automatically discovers available workflows when planning tasks:

```bash
$ flowdot "Run my data processing workflow"

✔ Found 3 workflows
  - data-processor (D7FQqcJK3P)
  - file-converter (A3BcDeFgHi)
  - report-generator (X9YzAbCdEf)
```

### Workflow Execution

Workflows can be executed as part of agent plans or recipe steps:

```bash
# Agent will use workflow if appropriate
flowdot "Process the uploaded CSV and generate a report"

# In recipes, workflows appear as agent tools
# or can be invoked via the invoke step type
```

### Workflow vs Recipe

| Feature | Workflow | Recipe |
|---------|----------|--------|
| Creation | Visual editor on flowdot.ai | Code/API definition |
| Steps | Node-based graph | Sequential/parallel steps |
| Use Case | Data transformation, API chains | Agent orchestration |
| Execution | Via API | Via CLI or API |

---

## Tasks and Planning

When you give the agent a complex request, it breaks it down into executable tasks.

### Planning Process

```
User Request
    ↓
Input Classification
    ├─ Conversation → Direct response
    ├─ Recipe Match → Execute recipe
    └─ Complex Task → Plan & Execute
                          ↓
                    Task Planning
                          ↓
                    Task Execution (parallel when possible)
                          ↓
                    Completion Evaluation
                          ↓
                    Result Synthesis
```

### Task Types

| Type | Description |
|------|-------------|
| `code` | Code analysis, file operations, search |
| `workflow` | Execute FlowDot workflow |
| `llm` | LLM reasoning task |
| `check_status` | Verify previous task completion |

### Code Actions

The `code` task type supports these actions:

| Action | Description |
|--------|-------------|
| `search` | Search codebase for patterns |
| `read` | Read file contents |
| `analyze` | Analyze code structure |
| `find-definition` | Find symbol definitions |
| `edit-file` | Modify file content |
| `create-file` | Create new file |
| `execute-command` | Run shell command |
| `web-search` | Search the web |

### Parallel Execution

Tasks without dependencies execute in parallel:

```bash
$ flowdot "Search for auth code and check package.json dependencies"

✔ Created plan with 2 tasks
┌─ Executing in parallel
│ ⠋ Task 1: Searching auth files...
│ ⠋ Task 2: Reading package.json...
└─
✔ Both tasks completed (1.2s)
```

### Dependency Handling

Tasks can reference results from previous tasks:

```
Task 0: Read configuration file
Task 1: Analyze config (depends on Task 0 output)
Task 2: Search related files (independent)

Execution order:
- Task 0 and Task 2 run in parallel
- Task 1 runs after Task 0 completes
```

### Loop Detection

The agent detects infinite loops and stops:

```
⚠ Loop detected: Same action repeated 3 times
⚠ Breaking out of potential infinite loop
```

Disable with `--no-loop-detection` if needed.

### Recovery Mode

On errors, the agent attempts recovery:

```
✖ Task failed: File not found
↻ Attempting recovery...
✔ Found alternative file path
```

Disable with `--no-recovery` if needed.

---

## Model System

FlowDot uses a **three-tier model system** that abstracts away specific models, letting you choose by capability level.

### Model Tiers

| Tier | Purpose | Example Models |
|------|---------|----------------|
| `simple` | Fast, cost-effective | gpt-4o-mini, claude-haiku |
| `capable` | Balanced performance | gpt-4o, claude-sonnet |
| `complex` | Maximum capability | o1, claude-opus |

### Setting Default Tier

```bash
# Set default model tier
flowdot config set-model capable

# Override per-command
flowdot agent "complex task" --model complex
```

### Model Browser

Browse and search all available models:

```bash
# Interactive browser
flowdot models

# Search models
flowdot models --search "claude"

# List all models
flowdot models --list
```

The browser shows:
- Provider hierarchy (including nested providers)
- Model capabilities (vision, tools, etc.)
- Context length
- Pricing (input/output per million tokens)

### Tier Mapping

Map tiers to specific models:

```bash
# View current mappings
flowdot config models

# Set tier to specific model
flowdot config set-tier complex anthropic/claude-opus-4

# Reset tier to server default
flowdot config clear-tier complex
```

### Provider Path Format

Models are identified by provider paths:

```
provider/model                           # Direct provider
flowdot/redpill/anthropic/claude-sonnet # Nested provider (aggregator)
openrouter/anthropic/claude-opus        # Via OpenRouter
```

### Provider Types

| Type | Description | Example |
|------|-------------|---------|
| Direct | Direct API access | `openai/gpt-4o` |
| Aggregator | Routes to underlying providers | `flowdot/...` |
| Nested | Provider within aggregator | `flowdot/redpill/anthropic/...` |

### Model Discovery

The CLI fetches available models from the FlowDot API:

```typescript
// Models are cached for 5-10 minutes
// Includes pricing, capabilities, and availability
```

---

## MCP Integration

FlowDot CLI is designed for **Model Context Protocol (MCP)** compatibility.

### MCP Security Notes

- MCP server metadata is treated as untrusted input to the model, not as authority
- Wildcard MCP access should be granted sparingly
- Tool output from an MCP server should be treated as data that may still require local approval before any command execution or file mutation
- Running an MCP server you trust is not the same as trusting every string it returns

### Current MCP Support

- **Tool Registry**: Catalog of 100+ tools with installation methods
- **Tool Invocation**: Execute tools within agent steps
- **Tool Discovery**: Automatic tool capability detection

### MCP Server (Separate Package)

The FlowDot MCP Server is available as a separate package:

```bash
# Install and run
npx @flowdot.ai/mcp-server

# Configure in Claude Desktop, Cursor, etc.
```

**Location**: `E:\FlowdotPlatform\mcp-server`
**npm**: https://www.npmjs.com/package/@flowdot.ai/mcp-server

### Future: Automatic MCP Integration

**Planned Feature**: The FlowDot CLI will automatically leverage MCP tools, enabling any capability available through FlowDot's MCP server to be used directly in CLI sessions.

This means:
- All MCP tools available to Claude will be available to `flowdot agent`
- Recipe steps can invoke any MCP tool
- Model selection determines which AI drives the tools

Example (future):
```bash
# CLI automatically uses MCP tools when appropriate
flowdot "Create a new workflow that processes CSV files"
# → Uses MCP's workflow creation tools

flowdot "List my recent workflow executions"
# → Uses MCP's execution history tools
```

### Tool Registry

Available tools are catalogued in the tool registry:

```typescript
// Example registry entries
{
  'jest': { npm: 'jest', pip: null },
  'webpack': { npm: 'webpack-cli' },
  'prettier': { npm: 'prettier' },
  // ... 100+ tools
}
```

### MCP Configuration

Create `.mcp.json` in your working directory to configure MCP servers:

```json
{
  "mcpServers": {
    "server-name": {
      "command": "node",
      "args": ["path/to/server.js"],
      "env": {
        "API_KEY": "${MY_API_KEY}"
      }
    }
  }
}
```

Environment variables use `${VAR}` syntax for expansion.

### MCP Slash Commands

```
/mcp                      Show status overview
/mcp servers              List configured servers
/mcp start <name|all>     Start server(s)
/mcp stop <name|all>      Stop server(s)
/mcp restart <name>       Restart a server
/mcp tools [server]       List available tools
/mcp reload               Reload .mcp.json configuration
```

### MCP Tool Naming

MCP tools follow the convention:
```
mcp__<server-name>__<tool-name>
```

Examples:
- `mcp__flowdot__list_workflows`
- `mcp__youtube__get_channel`
- `mcp__news__get_market_news`

### MCP Permission System

All MCP tool calls require permission approval with wildcard support:

| Pattern | Matches |
|---------|---------|
| `mcp__flowdot__list_workflows` | Exact tool |
| `mcp__flowdot__*` | All tools from server |
| `mcp__*` | All MCP tools |

### MCP in Recipes

MCP tools work in recipe agent steps with wildcard support:

```yaml
steps:
  - id: fetch-data
    type: agent
    config:
      tools:
        - search                              # Built-in
        - mcp__flowdot__list_workflows        # Specific MCP tool
        - mcp__youtube__*                     # All YouTube tools
      user_prompt: |
        List available workflows...
```

---

## COMMS Relay System

COMMS enables **bidirectional communication** between FlowDot CLI and external messaging platforms. Receive notifications, approve recipe gate steps, and send commands to running agents—all through Telegram, Discord, or other channels.

### Key Principle

The CLI **never exposes ports**. All communication flows outbound through the FlowDot Hub using HTTP polling for real-time message delivery.

### COMMS Security Notes

- Use HTTPS for Hub connections outside local development
- Inbound COMMS content should be treated as untrusted until verified and approved
- Remote relay access does not bypass local approval for sensitive actions
- Signed inbound frame verification can be enforced by configuring `FLOWDOT_HUB_PUBLIC_KEY`

For local signed COMMS development:

```bash
node -e "const { generateKeyPairSync } = require('node:crypto'); const { privateKey } = generateKeyPairSync('ed25519'); const jwk = privateKey.export({ format: 'jwk' }); console.log('FLOWDOT_HUB_PRIVATE_KEY=' + Buffer.from(jwk.d, 'base64url').toString('base64')); console.log('FLOWDOT_HUB_PUBLIC_KEY=' + Buffer.from(jwk.x, 'base64url').toString('base64'));"
```

- Set `FLOWDOT_HUB_PRIVATE_KEY` in the Hub environment
- Set `FLOWDOT_HUB_PUBLIC_KEY` in the CLI environment
- The CLI accepts either a raw 32-byte Ed25519 public key (`base64`) or an SPKI DER public key (`base64`)

### Architecture

```
┌─────────────┐    HTTPS     ┌─────────────┐   Webhook    ┌─────────────┐
│   FlowDot   │◄────────────►│   FlowDot   │◄────────────►│  Telegram   │
│     CLI     │   Polling    │     Hub     │              │  Discord    │
└─────────────┘              └─────────────┘              └─────────────┘
      │                            │
      │ Signs requests             │ Routes messages
      │ with Ed25519               │ to/from channels
      ▼                            ▼
   ~/.flowdot/               PostgreSQL DB
   device-identity.json      (channels, messages)
```

### Supported Channels

| Channel | Status | Features |
|---------|--------|----------|
| **Telegram** | ✅ Ready | Buttons, text, approval prompts |
| **Discord** | ✅ Ready | Embeds, buttons, slash commands |
| **Email** | 🔜 Planned | SMTP or provider API |
| **SMS** | 🔜 Planned | Twilio integration |

### Message Types

| Type | Direction | Description |
|------|-----------|-------------|
| `notification` | CLI → User | Simple alerts with optional buttons |
| `approval_request` | CLI → User | Gate step requiring user decision |
| `approval_response` | User → CLI | Button click result |
| `agent_command` | User → CLI | Text command to running agent |

### Relay Mode (`/relay`)

The `/relay` command enables bidirectional communication during interactive sessions:

```bash
# In interactive CLI (flowdot chat)
/relay telegram     # Enable bidirectional relay to Telegram
/relay list         # Show available channels
/relay status       # Show current relay status
/relay off          # Disable relay
```

**Capabilities:**

| Direction | Description |
|-----------|-------------|
| 📤 Outbound | All CLI output mirrored to COMMS channel |
| 📥 Inbound | Commands from COMMS channel execute locally |

When relay is active, you can walk away from your computer, continue working via Telegram/Discord, and return to see all conversation history in the CLI.

### Example Session

```bash
$ flowdot chat
> /relay telegram
✅ Relay enabled: Telegram (My Bot)
   📤 Outbound: CLI → Telegram
   📥 Inbound: Telegram → CLI

# Now messages work both ways:
# - Type in CLI → appears in Telegram
# - Send in Telegram → executes in CLI
```

### Device Authentication

The CLI uses **Ed25519** keypairs for secure device authentication:

The legacy layout example below is historical. The current implementation detail immediately after the example is authoritative.

```
~/.flowdot/
├── device-identity.json  # Public device metadata only
├── config.json           # Hub URL, API keys
├── device-key.enc        # Encrypted private key fallback
└── channels.json         # Cached channel list
```

- Keypair generated automatically on first run
- Public key registered with Hub
- Private key signs outbound COMMS requests
- Device appears in user's account at `/settings/devices`

Current implementation detail:

- Public device metadata is stored in `device-identity.json`
- Private keys are stored in the OS credential manager when available
- If OS keychain storage is unavailable, the private key falls back to encrypted local storage (`device-key.enc`)

### Two Execution Modes

When you send a message via Telegram/Discord:

**Mode 1: Local CLI Daemon** (when CLI is running with relay)
- Commands routed to your local machine
- Can execute local recipes with file access
- Can use local MCP tools
- Real-time bidirectional communication

**Mode 2: Hub Agent** (when no CLI is connected)
- Commands processed server-side
- Can invoke toolkit tools and workflows
- Can perform research/web searches
- Responds back through the same channel

### Permission Prompts via COMMS

When a recipe or agent needs permission, the prompt appears in both CLI and your COMMS channel:

```
CLI:
┌─ Permission Request
│ Execute command: npm install
│ [Y] Yes, this time  [S] Yes, for session  [A] Yes, forever
│ [N] No, not now     [B] No, banned
└─

Telegram:
┌─ Permission Request
│ Execute command: npm install
│ [Yes, this time] [Yes, for session] [Yes, forever]
│ [No, not now] [No, banned]
└─
```

Approve from either location—the other will update automatically.

### Setup

1. **Configure channel** at https://flowdot.ai/settings/comms
2. **Start interactive CLI**: `flowdot chat`
3. **Enable relay**: `/relay telegram` (or discord)
4. **Test**: Send a message from your phone

For detailed implementation documentation, see `COMMS.md` in this repository.

---

## Loops System

The `loop` command transforms FlowDot CLI into an **asynchronous autonomous agent** capable of running recurring tasks without constant human supervision.

### Core Concept

```bash
flowdot loop 5m "check the build status and notify me on failures"
```

This schedules a prompt to execute every 5 minutes autonomously.

### Use Cases

```bash
# CI/CD Monitoring
flowdot loop 10m "check the deploy status on Vercel and alert me if it failed"

# Task Management
flowdot loop 30m "check Notion for new tasks assigned to me"

# Code Quality
flowdot loop 4h "count TODO comments in src/ and warn if over 50"

# System Health
flowdot loop 5m "ping our health endpoints and report any failures"
```

### Interval Formats

| Format | Example | Description |
|--------|---------|-------------|
| Minutes | `5m`, `30m` | Every N minutes |
| Hours | `1h`, `4h`, `24h` | Every N hours |
| Days | `1d`, `3d` | Every N days |
| Cron | `"0 9 * * *"` | Advanced scheduling |

### Loop Command Options

```bash
flowdot loop <interval> "<prompt>" [options]

Options:
  --name <name>           Name for the loop (for management)
  --max-runs <n>          Maximum number of executions
  --expires <duration>    Auto-expire after duration (default: 3d)
  --model <tier>          Model tier: simple, capable, complex
  --on-error <action>     Error handling: continue, pause, stop
  --notify <method>       Notification: none, terminal, webhook
  --quiet                 Suppress output between runs
  --dry-run               Show schedule without starting
```

### Loop Management Commands

```bash
flowdot loops list              # List all active loops
flowdot loops show <id|name>    # View loop details
flowdot loops pause <id|name>   # Pause a loop
flowdot loops resume <id|name>  # Resume a paused loop
flowdot loops stop <id|name>    # Stop and remove a loop
flowdot loops history <id|name> # View run history
flowdot loops run <id|name>     # Trigger immediate run
```

### Daemon Architecture

Loops run via a background daemon process:

```bash
flowdot daemon start    # Start the daemon
flowdot daemon stop     # Stop the daemon
flowdot daemon status   # Check daemon status
```

The daemon survives terminal close and manages all loop scheduling.

### Safety & Limits

| Safeguard | Default |
|-----------|---------|
| Auto-expiration | 3 days |
| Min interval | 1 minute |
| Max concurrent loops | 10 |
| Error threshold (auto-pause) | 5 consecutive |
| Max run duration | 30 minutes |

---

## Public Toolkits

FlowDot CLI can invoke **public toolkits** hosted on the FlowDot server. Toolkits are collections of pre-built tools that integrate with external services.

### Discovering Toolkits

Toolkits available on FlowDot can be discovered via the web interface or MCP tools:

```bash
# Via MCP (if connected)
mcp__flowdot__list_agent_toolkits
mcp__flowdot__search_agent_toolkits --query "youtube"
```

### Using Toolkits in Recipes

Recipes can invoke installed toolkit tools:

```yaml
steps:
  - id: fetch-video
    type: agent
    config:
      tools:
        - mcp__flowdot__mcp__flowdot__invoke_toolkit_tool
      user_prompt: |
        Use the YouTube toolkit to get video analytics...
```

### Toolkit Categories

| Category | Examples |
|----------|----------|
| `api-integration` | YouTube, Slack, GitHub |
| `data-processing` | CSV, JSON transformation |
| `automation` | Scheduling, notifications |
| `analytics` | Trading, market data |

---

## Testing

FlowDot is an **interactive CLI application**. You cannot test it with regular Bash commands. Use the MCP interactive-cli tools.

### Quick Test (Recommended)

Use `run_test_sequence` for one-shot testing:

```
mcp__interactive-cli__run_test_sequence(
  command: "npx flowdot",
  cwd: "E:/FlowdotPlatform/tests",
  input_message: "What is 2 + 2?",
  ready_idle_ms: 3000,
  response_idle_ms: 5000,
  timeout_ms: 60000,
  close_after: true
)
```

Returns structured results:
```json
{
  "success": true,
  "startup_output": "<compressed welcome screen>",
  "response_output": "<compressed agent response>",
  "total_elapsed_ms": 15863
}
```

### Manual Testing Workflow

```
1. mcp__interactive-cli__start_session(command: "npx flowdot", cwd: "/path")
2. mcp__interactive-cli__wait_for_idle(session_id, idle_ms: 2000)
3. mcp__interactive-cli__send_input(session_id, input: "message", press_enter: true)
4. mcp__interactive-cli__wait_for_idle(session_id, idle_ms: 3000, timeout_ms: 60000)
5. mcp__interactive-cli__close_session(session_id)
```

### Wait Functions

| Function | Use Case |
|----------|----------|
| `wait_for_idle(idle_ms)` | Wait until output stabilizes |
| `wait_for_pattern(preset)` | Wait for prompt, error, completion |
| `get_screen_snapshot()` | Quick status check |

### Animation Compression

Output is automatically compressed:

| Token | Meaning |
|-------|---------|
| `<SPIN:N>` | N spinner frames collapsed |
| `<REDRAW>` | Screen redraw collapsed |
| `<CLEAR>` | Screen clear |

### Checking Logs and Chats

Test data is stored in `.flowdot/`:

```
.flowdot/
├── chats/
│   ├── index.json           # Chat index
│   └── {chat-id}.json       # Individual chats
├── logs/
│   ├── {session-id}.log     # Debug logs
│   └── latest.txt           # Current session
└── permissions.json         # Saved permissions
```

Verify with CLI commands:
```bash
flowdot chats list
flowdot chats show <id>
```

---

## Configuration

### Configuration File

Configuration is stored in a platform-specific location:

| Platform | Location |
|----------|----------|
| macOS | `~/Library/Application Support/flowdot-cli/config.json` |
| Linux | `~/.config/flowdot-cli/config.json` |
| Windows | `%APPDATA%\flowdot-cli\config.json` |

### View Configuration

```bash
flowdot config get
```

Output:
```
┌─ FlowDot CLI Configuration
│ API URL:     https://flowdot.ai
│ Model:       capable
│ Linked Recipes: 3
└─
```

### Configuration Options

| Key | Description | Default |
|-----|-------------|---------|
| `apiUrl` | FlowDot API server URL | `https://flowdot.ai` |
| `model` | Default model tier | `capable` |

### Transport Rules

- Use `https://` for all non-loopback FlowDot API or Hub endpoints
- `http://127.0.0.1:8000` is allowed for local development only
- Non-loopback plaintext HTTP endpoints are rejected by the CLI

### Set Configuration

```bash
# Set API URL (for local development only)
flowdot config set-url http://127.0.0.1:8000

# Set API URL for production or remote self-hosted deployments
flowdot config set-url https://flowdot.example.com

# Set default model tier
flowdot config set-model complex
```

### Permissions

The CLI prompts for permission before sensitive operations with a 5-option response system:

**Permission Categories:**
- `command-execute` - Running shell commands
- `file-read` - Reading file contents
- `file-write` - Writing/updating files
- `file-create` - Creating new files
- `recipe-invoke` - Invoking/executing recipes
- `workflow-invoke` - Invoking workflows
- `web-search` - Searching the web
- `research` - General research/analysis

**Permission Options:**
| Option | Key | Behavior |
|--------|-----|----------|
| Yes - Right now | `y` | Allow this single operation |
| Yes - For session | `s` | Allow for rest of session (cleared on restart) |
| Yes - Forever | `a` | Allow always (persisted to file) |
| No - Not now | `n` | Deny this single operation |
| No - Banned | `b` | Always deny (persisted to file) |

**Storage:** Permissions are stored in a `.flowdot/` folder in the working directory:
```
<cwd>/.flowdot/
├── permissions.json     # Forever allow/ban
└── session.json         # Session-scoped permissions
```

**CLI Commands:**
```bash
# View all saved permissions
flowdot permissions

# Clear permissions
flowdot permissions clear              # Clear all
flowdot permissions clear --session    # Clear session only
flowdot permissions clear --persisted  # Clear forever/banned only
flowdot permissions clear --category command-execute  # Clear specific category

# Add permissions manually
flowdot permissions allow command-execute "npm install"
flowdot permissions ban command-execute "rm -rf"
flowdot permissions remove command-execute "npm install"

# List all permission categories
flowdot permissions categories
```

### Recipe Links

Recipe aliases are stored in configuration:

```bash
# View linked recipes
flowdot recipes list

# Link a recipe
flowdot recipes link abc123 my-alias

# Unlink
flowdot recipes unlink my-alias
```

### Cache Management

Settings and models are cached to reduce API calls:
- **Cache TTL**: 5 minutes
- **Automatic refresh**: On expiry
- **Manual clear**: Restart CLI

---

## Architecture

### Package Structure

```
flowdot-cli/
├── packages/
│   ├── cli/              # CLI commands and interface
│   │   └── src/
│   │       ├── index.ts  # Main entry point
│   │       └── commands/ # Command implementations
│   ├── core/             # Business logic
│   │   └── src/
│   │       ├── agent/    # Agent execution engine
│   │       ├── recipe/   # Recipe runtime
│   │       ├── services/ # API, config, etc.
│   │       └── utils/    # Utilities
│   ├── shared/           # Shared types and utilities
│   └── ui/               # Terminal UI components
```

### Key Components

| Component | Location | Purpose |
|-----------|----------|---------|
| Agent Engine | `core/src/agent/engine.ts` | Task planning and execution |
| Recipe Runtime | `core/src/recipe/RecipeRuntime.ts` | Recipe execution |
| API Client | `core/src/services/api.ts` | HTTP client with auth |
| Config Service | `core/src/services/config.ts` | Configuration persistence |
| Settings Service | `core/src/services/settings.ts` | Model tier resolution |

### Data Flow

```
User Input
    ↓
CLI (index.ts)
    ├─→ Recipe Alias? → RecipeRuntime
    ├─→ Simple Chat? → Direct LLM response
    └─→ Complex Task? → Agent Engine
                            ↓
                      Task Planning
                            ↓
                      Task Execution
                            ↓
                      Result Synthesis
                            ↓
                      Terminal Output
```

---

## Development

### Prerequisites

- Node.js >= 20.0.0
- npm >= 9.0.0

### Setup

```bash
# Clone repository
git clone https://github.com/flowdot-llc/flowdot-cli.git
cd flowdot-cli

# Install dependencies
npm install

# Build all packages
npm run build

# Link for local development
npm link
```

### Build Commands

```bash
# Build all packages
npm run build

# Build specific package
npm run build --workspace=@flowdot/cli
npm run build --workspace=@flowdot/core

# Watch mode
npm run dev
```

### Testing

```bash
# Run all tests
npm test

# Run specific package tests
npm test --workspace=@flowdot/cli
```

### Local Development

For local development against the FlowDot platform:

```bash
# Point to local loopback server for development only
flowdot config set-url http://127.0.0.1:8000

# Authenticate
flowdot auth login
```

### Debugging

Enable debug logging:

```bash
DEBUG=flowdot:* flowdot "your request"
```

Log files are written to `.flowdot/logs/` in the current directory.

---

## Troubleshooting

### Authentication Issues

```bash
# Check auth status
flowdot auth status

# Re-authenticate
flowdot auth logout
flowdot auth login
```

### API Connection Issues

```bash
# Check configured URL
flowdot config get

# Reset to default
flowdot config set-url https://flowdot.ai
```

### Permission Denied

```bash
# Clear saved permissions
flowdot config clear-permissions
```

### Recipe Not Found

```bash
# List linked recipes
flowdot recipes list

# Re-link if needed
flowdot recipes link <hash> <alias>
```

---

## Support

- **Documentation**: https://docs.flowdot.ai
- **Issues**: https://github.com/flowdot-llc/flowdot-cli/issues
- **Discord**: https://discord.gg/flowdot

---

## License

MIT License - see [LICENSE](LICENSE) for details.

---

Built with ❤️ by [FlowDot](https://flowdot.ai)