npm package: @kadi.build/cli
Description: A CLI for interacting with the Knowledge and Ability Deployment Interface (KADI), an agent management system for managing installation of agents and abilities in distributed environments.
Author: Corey Clark
Latest version: 0.0.1-alpha.12

# KADI CLI – Knowledge & Ability Deployment Interface

## Table of Contents

- [KADI CLI – Knowledge \& Ability Deployment Interface](#kadi-cli--knowledge--ability-deployment-interface)
  - [Table of Contents](#table-of-contents)
  - [What is KADI?](#what-is-kadi)
  - [Key Concepts](#key-concepts)
    - [Agents](#agents)
    - [Abilities](#abilities)
    - [CLI Plugins](#cli-plugins)
  - [Getting Started](#getting-started)
    - [Prerequisites](#prerequisites)
    - [Installation](#installation)
    - [Uninstallation](#uninstallation)
    - [Create Your First Agent](#create-your-first-agent)
    - [For Contributors \& Maintainers](#for-contributors--maintainers)
      - [Quick install (Linux \& macOS)](#quick-install-linux--macos)
      - [Quick install (Windows)](#quick-install-windows)
  - [`agent.json` – the manifest](#agentjson--the-manifest)
    - [Lifecycle Scripts](#lifecycle-scripts)
      - [Script Execution Order](#script-execution-order)
      - [Required vs Optional Scripts](#required-vs-optional-scripts)
      - [Best Practices](#best-practices)
  - [The Plugin Architecture](#the-plugin-architecture)
    - [How command resolution works](#how-command-resolution-works)
    - [Build your first plugin](#build-your-first-plugin)
  - [Plugin Atlas](#plugin-atlas)
    - [Core Development Plugins](#core-development-plugins)
      - [kadi-install](#kadi-install)
      - [kadi-init](#kadi-init)
      - [kadi-update](#kadi-update)
    - [Runtime \& Execution Plugins](#runtime--execution-plugins)
      - [kadi-run](#kadi-run)
    - [Build \& Deployment Plugins](#build--deployment-plugins)
      - [kadi-build](#kadi-build)
      - [kadi-deploy](#kadi-deploy)
    - [Infrastructure Plugins](#infrastructure-plugins)
      - [kadi-broker](#kadi-broker)
  - [Roadmap](#roadmap)
  - [Contributing](#contributing)

---

## What is KADI?

**KADI (Knowledge & Ability Deployment Interface)** is a modular tool-chain for building, packaging, and running _software agents_.  
It ships as a **very small CLI** that speaks just one language:

```bash
kadi <command> [...options]
```

…but it becomes powerful by **loading every command from a plugin at run-time**.  
Each plugin is a normal Node.js module living inside the `abilities/` folder (for now).

## Key Concepts

### Agents

A **KADI agent** is a _self-contained directory_ that implements some behavior – AI assistant, micro-service, data pipeline, you name it.  
The only contract is the presence of an `agent.json` manifest at the root.

### Abilities

An **ability** is to an agent what a package is to an operating system: a self-contained, reusable piece of functionality.  
Each ability is stored under `abilities/<name>/<version>/` and ships **its own `agent.json` manifest**.

Typical use cases:

- Provide a domain-specific _tool_ the KADI broker can invoke (e.g. text-to-speech, PDF parsing).
- Bundle data or models an agent can access locally.
- Extend the CLI itself (see next section).

Example – adding outbound phone calls to an agent:

```bash
# inside your agent folder
kadi install phone
```

The `phone` ability (and its dependencies) are downloaded, placed under `abilities/phone/<version>/`, and immediately available for use.

### CLI Plugins

A **CLI plugin** stands in the same relationship to the **KADI binary** as an ability does to an agent: it augments behaviour without altering the host code-base.  
To be recognized, a plugin **must** export a default JavaScript function with the signature:

```ts
import { IKadiContext } from 'kadi'; // types only
export default function myPlugin(ctx: IKadiContext) {
  /* … */
}
```

CLI plugins **only affect the global CLI**. Placing them in an agent directory has no effect – they must be installed via the command below so the CLI can locate them:

```bash
# install a plugin and its dependencies
kadi install <plugin-name>
```

Manual copying or `npm install` is _not_ supported. The CLI resolves versions, installs to its own `abilities/` tree, and updates the root `agent.json` automatically.

At start-up the KADI binary inspects the first positional argument (`install`, `run`, `deploy`, …) and _lazy-loads_ the matching plugin.
If the plugin registers a Commander command of the same name the user never notices the indirection.

---

## Getting Started

### Prerequisites

- Node.js 18 or newer
- podman

### Installation

The recommended way to install KADI is via npm:

```bash
# Install globally (Node ≥ 18)
npm install -g @kadi.build/cli
```

### Uninstallation

To remove KADI from your system:

```bash
# Uninstall the CLI
npm uninstall -g @kadi.build/cli
```

### Create Your First Agent

Now create your first agent in a new directory:

```bash
# 1. Bootstrap a new agent
kadi init  # Creates a new agent with interactive setup

# 2. Install the abilities declared in agent.json
kadi install

# 3. Start the agent
kadi run        # executes the "start" lifecycle script
```

### For Contributors & Maintainers

If you're working on the KADI CLI itself or need the development environment, you can use the experimental installers:

#### Quick install (Linux & macOS)

```bash
# download the installer
curl -o install_kadi.sh http://kadi.build/uploads/install_kadi_linux.sh

# make it executable and run it
chmod +x install_kadi.sh
./install_kadi_exp.sh
```

The script drops the `kadi` binary on your **PATH** and optionally starts a local `kadi-server` for offline experimentation.

#### Quick install (Windows)

```powershell
# download the installer
Invoke-WebRequest -Uri https://agents.hewmen.ai/uploads/install_kadi_win.ps1 -OutFile install_kadi_win.ps1

# run it
.\install_kadi_win.ps1
```

If PowerShell blocks the script, either run it as _Administrator_ or temporarily allow local scripts:

```powershell
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned
```

> **Tip:** Both installers configure the CLI _and_ a local `kadi-server` for offline testing.

---

## `agent.json` – the manifest

`agent.json` plays the same role `package.json` plays in npm: **single source of truth**.  
Below is the _current_ canonical example – copy & modify.

```json
{
  "name": "agentA",
  "version": "1.0.0",
  "license": "MIT",
  "description": "Mock KADI Agent A demonstrating tool registration and cross-agent invocation.",
  "repo": "",
  "lib": "",
  "brokers": {
    "local": "ws://127.0.0.1:8080",
    "remote": "ws://146.190.121.213:8080"
  },
  "abilities": {},
  "scripts": {
    "preflight": "",
    "setup": "npm install",
    "start": "node agentA.js",
    "stop": ""
  },
  "deploy": {
    "services": {
      "agenta": {
        "image": "kassibert/agent-a:build-4",
        "ports": ["8080:8080"],
        "stdin_open": true,
        "tty": true,
        "networks": ["net"]
      }
    },
    "networks": { "net": {} }
  }
}
```

### Lifecycle Scripts

KADI agents use lifecycle scripts to define their behavior at different stages of their existence.

#### Script Execution Order

When you run `kadi run`, the following scripts execute in sequence:

1. **`preflight`** (optional) - Runs before anything else
2. **`setup`** (required) - Install dependencies, create configs, initialize data
3. **`start`** (required) - Launch the agent's main process
4. **`stop`** (optional) - Gracefully shut down, close connections, clean up

Additional scripts like `restart`, `healthcheck`, `bundle`, etc. can be added as needed.

#### Required vs Optional Scripts

| Script      | Required | Purpose                                                               | When Executed       |
| ----------- | -------- | --------------------------------------------------------------------- | ------------------- |
| `preflight` | no       | Validate environment, download assets – **runs before anything else** | `kadi run` (first)  |
| `setup`     | **yes**  | Install dependencies, create configs, initialize data                 | `kadi run` (second) |
| `start`     | **yes**  | Launch the agent's main process                                       | `kadi run` (third)  |
| `stop`      | no       | Gracefully shut down, close connections, clean up                     | `kadi stop`         |

`setup` and `start` are **hard requirements** – KADI will refuse to deploy an agent without them.

#### Best Practices

- **Don't exit with non-zero codes unless you really mean it** - If the failure is minor or only prevents optional features, print a warning and exit successfully
- **Use `setup` for one-time initialization** - Install dependencies, create configuration files, download models
- **Use `start` for the main process** - Launch your agent's primary service, web server, or background process
- **Use `stop` for graceful shutdown** - Close database connections, save state, terminate child processes
- **Use `preflight` for validation** - Check environment variables, verify external services are available
- **Don't prefix commands with "sudo"** - If root permissions are required, let the user run the command with sudo

---

## The Plugin Architecture

### How command resolution works

1. User types `kadi <command>` (e.g. `kadi deploy`).
2. The CLI looks into its own `agent.json.cliPlugins` map **first** – this allows explicit overrides.
3. If nothing matches it falls back to `abilities/<command>/<latest>/index.js`.
4. The file is imported as an ES module and its _default export_ is executed with the shared context.

See [`src/index.ts`](./src/index.ts) for the ~60-line implementation.

### Build your first plugin

1. Create the folder structure:

```bash
mkdir -p abilities/hello/0.0.1
```

2. Add `abilities/hello/0.0.1/index.js`:

```js
export default function hello(ctx) {
  ctx.commander
    .command('hello')
    .description('Prints a greeting')
    .action(() => {
      ctx.logger.log('👋  Hello from my first KADI plugin!');
    });
}
```

3. Register it in your root `agent.json` so KADI can map the `hello` command:

```json
{
  "cliPlugins": {
    "hello": "abilities/hello/0.0.1"
  }
}
```

4. Run it:

```bash
kadi hello
```

No additional SDKs or build steps are required; providing an ES module that matches the signature is sufficient.

---

## Plugin Atlas

KADI's power comes from its plugin ecosystem. Each plugin extends the CLI with specific functionality, from development tools to deployment automation. Here's a comprehensive guide to all official plugins:

### Core Development Plugins

#### kadi-install

**Purpose**: The foundation of KADI's dependency management system. Installs abilities and their nested dependencies, resolving version conflicts and updating `agent.json` automatically.

**Basic Usage**:

```bash
# Install a single ability
kadi install logging

# Install specific version
kadi install monitoring@0.0.7

# Install multiple abilities
kadi install logging monitoring@0.0.7 analytics

# Install all abilities declared in agent.json
kadi install

# Install CLI dependencies (from KADI CLI's agent.json)
kadi install --cli
```

**Repository**: [kadi-install](https://gitlab.com/humin-game-lab/kadi/kadi-install)

---

#### kadi-init

**Purpose**: Interactive project scaffolding that creates new KADI agents, CLI plugins, and abilities with proper structure and templates.

**Basic Usage**:

```bash
# Start interactive project creation
kadi init

# Creates a new agent with proper structure:
# - agent.json manifest
# - Language-specific dependencies
# - Main entry point with "Hello World" example
# - README with next steps
```

**Example Output**:

```
🚀 Welcome to KADI Init!
Let's create a new KADI project together.

? What are you building? › Agent - A standalone KADI agent
? What is the name of your project? › my-awesome-agent
? What programming language do you want to use? › JavaScript (Node.js)
? Describe your project: › A smart AI assistant for task management

📋 Project Summary:
Type: agent
Name: my-awesome-agent
Language: JavaScript
Description: A smart AI assistant for task management

? Create the project with these settings? › Yes

Creating your KADI project...
✔ Project created successfully!

🎉 Your KADI project is ready!
```

**Repository**: [kadi-init](https://gitlab.com/humin-game-lab/kadi/kadi-init)

---

#### kadi-update

**Purpose**: Keeps your KADI projects up-to-date by checking the registry for newer versions of installed abilities and updating them automatically.

**Basic Usage**:

```bash
# Update all abilities in current project
kadi update

# Update the CLI itself
kadi update --cli

# Update specific abilities
kadi update logging monitoring@0.0.7

# Update specific CLI abilities
kadi update --cli kadi-install kadi-run@1.2.0
```

**Repository**: [kadi-update](https://gitlab.com/humin-game-lab/kadi/kadi-update)

---

### Runtime & Execution Plugins

#### kadi-run

**Purpose**: The **script execution engine** for the KADI ecosystem. It provides a unified interface to run commands defined in `agent.json` files, whether they're at the project level or within specific abilities.

**Basic Usage**:

```bash
# Run the default 'start' script from your project
kadi run

# Run a custom script defined in your project
kadi run test

# Run a well-known script (start, init, setup)
kadi run setup

# Run a script from a specific ability
kadi run build --ability my-ui

# Run a script with explicit ability specification
kadi run -a data-processor migrate
```

**Advanced Usage**:

```bash
# Development workflow
kadi run init      # Initialize project dependencies
kadi run dev       # Start development server
kadi run test      # Run tests
kadi run build     # Build for production

# Ability management
kadi run setup --ability ui-component    # Run setup from ui-component ability
kadi run build --ability api-client      # Run build from api-client ability
kadi run test --ability data-processor   # Run tests from data-processor ability

# Custom scripts
kadi run deploy    # Run deployment script
kadi run migrate --ability data-processor  # Execute database migrations
kadi run docs      # Generate documentation
```

**Repository**: [kadi-run](https://gitlab.com/humin-game-lab/kadi/kadi-run)

---

### Build & Deployment Plugins

#### kadi-build

**Purpose**: Containerizes KADI agents into reproducible Docker images using a curated `Dockerfile.KADI` template.

**Basic Usage**:

```bash
# Build with default settings
kadi build

# Custom image tag
kadi build --tag registry.example.com/agents/my-agent:1.2.0

# Cross-compile for Linux/AMD64
kadi build --platform linux

# Preview changes without building
kadi build --dry-run
```

**Repository**: [kadi-build](https://gitlab.com/humin-game-lab/kadi/kadi-build)

---

#### kadi-deploy

**Purpose**: **Deployment engine** that takes a single `agent.json` and **deploys** to various platforms, generating the necessary artifacts and executing the deployment process.

**Basic Usage**:

```bash
# Deploy locally with Podman Compose (auto-starts VM if needed)
kadi deploy --target local

# Deploy to Akash mainnet (handles wallet connection, bidding, manifest upload)
kadi deploy --target akash --network mainnet

# Preview deployment without making changes
kadi deploy --dry-run

# Non-interactive deployment (assumes "yes" for all prompts)
kadi deploy --target akash --network mainnet --yes
```

**Advanced Usage**:

```bash
# Deploy to specific project directory
kadi deploy --target local --project /path/to/agent

# Deploy to Akash testnet
kadi deploy --target akash --network testnet

# Local development workflow
kadi deploy --dry-run              # Preview compose without changes
kadi deploy --target local         # Build images and run stack locally
kadi deploy --target akash         # Deploy to Akash Network
```

**Repository**: [kadi-deploy](https://gitlab.com/humin-game-lab/kadi/kadi-deploy)

---

### Infrastructure Plugins

#### kadi-broker

**Purpose**: WebSocket & RabbitMQ message router for cross-agent communication, implementing the KADI protocol for tool discovery and invocation.

**Basic Usage**:

```bash
# Start the broker server
npm start

# Run example agents
npm run agent:a
npm run agent:b
npm run agent:c

# Monitor with observer
npm run observer
```

**Repository**: [kadi-broker](https://gitlab.com/humin-game-lab/kadi/kadi-broker)

---

## Roadmap

TODO

---

## Contributing

TODO

For larger ideas open an issue first so we can discuss direction.