# AUI Agent Builder CLI

[![npm version](https://img.shields.io/npm/v/aui-agent-builder.svg)](https://www.npmjs.com/package/aui-agent-builder)
[![npm downloads](https://img.shields.io/npm/dw/aui-agent-builder.svg)](https://www.npmjs.com/package/aui-agent-builder)
[![node](https://img.shields.io/node/v/aui-agent-builder.svg)](https://nodejs.org)

Build, version, and deploy AI agents from your terminal. Import agent configurations as local JSON files, edit them in your editor with full schema autocomplete, validate changes, push to the backend, and manage versions — all from the command line.

---

## Features

- **Code-first agent development** — Edit agent configurations as JSON files in your editor with schema-driven autocomplete
- **Version management** — Create drafts, publish, activate, and archive agent versions with full lifecycle control
- **Smart diff & validation** — See exactly what changed, validate against domain schemas before pushing
- **Knowledge base management** — Upload documents and URLs, export/import KB configurations
- **Scope-level control** — Import and push at network, account, organization, or category scope
- **IDE integration** — Auto-generated schemas, Cursor rules, Claude skills, and OpenCode skills for AI-assisted editing
- **CI/CD ready** — Every command has a non-interactive mode with flags for automation
- **Web playground** — Built-in chat UI for testing agents locally

---

## Table of Contents

- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Concepts](#core-concepts)
- [Commands Reference](#commands-reference)
- [Workflows](#workflows)
- [Project Structure](#project-structure)
- [Configuration File Reference](#configuration-file-reference)
- [Version Management](#version-management)
- [Knowledge Bases](#knowledge-bases)
- [CI/CD & Automation](#cicd--automation)
- [Configuration](#configuration)
- [Troubleshooting](#troubleshooting)
- [Local Development](#local-development)

---

## Installation

```bash
npm install -g aui-agent-builder
```

Requires **Node.js 18+**.

Verify installation:

```bash
aui -v
```

---

## Quick Start

```bash
# 1. Authenticate
aui login

# 2. Import an existing agent (or create one with: aui agents --create)
aui import-agent

# 3. Edit .aui.json files in your editor (schema autocomplete works out of the box)

# 4. See what changed
aui diff

# 5. Validate
aui validate

# 6. Push changes
aui push

# 7. Publish and go live
aui version publish
aui version activate
```

---

## Core Concepts

### Hierarchy

```
Organization
└── Account (Project)
    └── Agent (Network)
        └── Version (v1.0, v1.1, v2.0, ...)
```

| Concept | Description |
|---------|-------------|
| **Organization** | Top-level workspace, tied to your login credentials |
| **Account** | A project within the organization |
| **Agent** | An AI agent (also called a "network") within a project |
| **Version** | An immutable snapshot of the agent's full configuration |

### Agent Configuration

Each agent is composed of seven configuration types:

| Config | File | Purpose |
|--------|------|---------|
| **General Settings** | `agent.aui.json` | Name, objective, persona, tone, guardrails |
| **Parameters** | `parameters.aui.json` | Data the agent collects from users and outputs |
| **Entities** | `entities.aui.json` | Groups of related parameters |
| **Integrations** | `integrations.aui.json` | API, RAG, and MCP connections |
| **Tools** | `tools/*.aui.json` | Agent capabilities (one file per tool) |
| **Rules** | `rules.aui.json` | Global behavioral rules |
| **Widgets** | `widgets.aui.json` | Card templates for rich UI responses |

### Version Lifecycle

```
draft ──→ published ──→ active
                    └──→ archived
```

| State | Editable | Can Activate | Description |
|-------|----------|-------------|-------------|
| **Draft** | Yes | No | Work in progress. Receives pushes |
| **Published** | No | Yes | Locked permanently. Ready to go live |
| **Active** | No | — | The live production configuration |
| **Archived** | No | No | Retired. Can still be viewed and cloned |

---

## Commands Reference

### Discovering commands

```bash
aui --help                  # Human-readable command overview
aui <command> --help        # Options for any command (e.g. aui integration test --help)
aui --help --json           # Full command tree as a JSON envelope (for tooling / coding agents)
aui <command> --help --json # JSON help scoped to a single command/subcommand
```

`aui --help --json` emits `{ "success": true, "data": { name, version, command } }`,
where `command` recursively lists every subcommand with its `description`,
`arguments`, and `options` (each option carries `flags`, `description`,
`default`, and `takesRequiredValue` / `takesOptionalValue`).

### Authentication

```bash
aui login                        # Open browser for authentication
aui login --environment staging  # Login to a specific environment
aui login --token <jwt>          # Login with a JWT token (for CI/CD)
aui logout                       # Clear session and credentials
```

### Agent Management

```bash
aui agents                       # Interactive menu: list, create, switch, import, delete
aui agents --list                # List all agents in the current account
aui agents --create              # Create, then auto-import into ./<agent-name> and drop you in
aui agents --switch              # Switch the active agent in your session
aui agents --delete              # Interactive: org → account → agent → choose scope (whole / one version / all versions)
```

**`aui agents --create` is end-to-end.** It creates the agent + its first
version, **auto-imports the editable draft into a new `./<agent-name>` folder**
(use `--dir <path>` to override), and **drops you into that folder via an
interactive subshell** so you can start editing immediately — run `exit` to
return. The creation **mode follows your environment**: `staging` / `custom` →
bundle mode, `production` / `eu-production` → records mode. Override with
`--bundle-mode` / `--records-mode`.

In **bundle mode**, the Apollo endpoint provisions everything server-side
(network → agent → version → publish → activate) **and creates a draft for
editing**; the CLI imports **that draft** (resolved via `GET .../versions`),
not the published active version — you can only `aui push` into a draft. It
never creates a draft itself (falls back to the active version only if none is
found). In **records mode**, the create flow snapshots a v1.0 draft and imports
it. **Non-interactive creation is create-only:** `--json`, piped output, CI,
and the agent-builder-bff sandbox skip BOTH the auto-import and the subshell and
behave like a plain create (set `AUI_AUTO_IMPORT=1` to force the import in
automation; `AUI_AUTO_IMPORT=0` to disable it in a terminal). A child process
can't change the parent shell's cwd, which is why the interactive case opens a
nested shell.

**Non-interactive creation:**

```bash
# Minimal — still prompts for org/account
aui agents --create --name "My Agent"

# Fully non-interactive
aui agents --create --name "My Agent" --account-id <id>

# With a specific category (e.g. Amazon, Google Flights)
aui agents --create --name "My Agent" --account-id <id> --category Amazon

# Import the new agent into a specific folder instead of ./<agent-name>
aui agents --create --name "My Agent" --account-id <id> --dir ./my-agent

# Force a creation mode regardless of environment
aui agents --create --name "My Agent" --account-id <id> --records-mode
aui agents --create --name "My Agent" --account-id <id> --bundle-mode

# One-step: create + version + publish + activate
aui agents --create --name "My Agent" --account-id <id> --full
```

**Interactive flow:**

`aui agents --delete` walks you through the same picker the create / import flows use:

1. Select organization
2. Select account
3. Select agent (with the active version surfaced inline)
4. Choose what to delete:
   - **Delete entire agent** — single API call, removes ALL versions. Confirmed by typing the agent name.
   - **Delete a specific version** — pick from the version list. Yes/no confirm.
   - **Delete all versions** — loops per-version DELETEs, keeps the agent shell. The currently active version is attempted last and may be rejected by the backend.

**Non-interactive deletion (irreversible — requires `--yes` to skip confirmation):**

```bash
# Delete an entire agent (and ALL of its versions) by network ID — single API call
aui agents --delete --network-id <network-id> --yes

# Loop per-version DELETE for an agent (keeps the agent shell, removes every version)
aui agents --delete --agent-id <agent-id> --all-versions --yes

# Delete a specific version of the current agent
aui agents --delete --version <version-id> --yes

# Delete a specific version of a specific agent (fully explicit)
aui agents --delete --agent-id <agent-id> --version <version-id> --yes

# JSON output (for CI/CD; --yes is mandatory for actual delete)
aui agents --delete --network-id <network-id> --yes --json
```

> **Notes**
> - `--delete --network-id <id>` is a single `DELETE /v1/agents/network/{network_id}` — removes the agent record AND every version in one call.
> - `--delete --agent-id <id> --all-versions` loops per-version `DELETE /v1/agents/{agent_id}/versions/{version_id}` calls — useful when you want to clear history but keep the agent shell. The active version is attempted last; the backend may reject it.
> - Deleting a single version is also rejected by the backend if it is currently *active* — activate a different version first, or delete the entire agent instead.
> - If you delete the agent or version that's currently selected in your session, the CLI clears the session pointer and tells you to switch.
> - All DELETE calls are captured by `aui curl` for inspection / replay.

### Import & Pull

```bash
aui import-agent                           # Interactive: select org → account → agent
aui import-agent <agent-id>               # Import by network ID
aui import-agent --version <id>           # Import a specific version
aui import-agent --scope-level category   # Import at category scope
aui import-agent --dir ./my-folder        # Output to a specific directory
aui import-agent --with-kb-files          # Also download original KB binaries (skipped by default)
aui import-agent --skills claude,cursor   # Generate AI coding skills
aui import-agent --no-skills             # Skip skill generation
aui import-agent --include-evaluate       # Include test_questions schema
```

> [!IMPORTANT]
> **`aui import-agent` defaults to the *active* version.** With no `--version` (or `--tag`), you silently get whatever is **live** in the backend — not the version you think you're editing. The version that's active can change out from under you (someone else activates a new one, a rollback happens, etc.).
>
> **Always pass `--version <id>` (or `--tag <vX.Y>`) to pin exactly what you import**, and then **fingerprint-check the result** before you start editing — confirm you got the right version by spot-checking something cheap and deterministic, e.g. the parameter count, the number of tools/rules, or the version tag printed in the import summary. If the fingerprint doesn't match what you expect, you imported the wrong version — re-import with the correct `--version`.

```bash
aui pull                                  # Pull latest into existing project
aui pull --force                          # Skip overwrite confirmation
aui pull --scope-level <level>            # Pull at a specific scope level
```

### Push

Push is only allowed to draft versions. If no draft exists, the CLI will reject the push and guide you to create one first.

```bash
aui push                                  # Push changes into the current draft version
aui push --dry-run                        # Preview without pushing
aui push --scope-level category           # Push at a specific scope level
aui push --version-id <id>               # Push into a specific draft (must be a draft)
aui push --force                          # Push even with validation errors
aui push --skip-validation                # Skip validation step
aui push --api-key <key>                 # Use a specific API key
```

If push fails partially, re-run `aui push` to retry the failed changes.

### Version Management

```bash
aui version                               # Interactive version menu
aui version list                          # List all versions
aui version list --json                   # Machine-readable: full (untruncated) IDs + stats

# Create — single step, NO prompts (always bumps version number: v1, v2, v3, ...)
aui version create                                        # Auto: picks source by agent mode
aui version create --source agent-scope                   # Override: new version from live scope
aui version create --source version --from <id>           # Override: clone from a specific version
aui version create --agent-id <agent-management-id>       # Target a specific agent explicitly
aui version create --label "Release 2" --tags "prod" --notes "..."   # Optional metadata

# Lifecycle
aui version publish                       # Interactive — select draft to publish
aui version publish <id>                  # Publish a specific draft
aui version activate                      # Interactive — select version to activate
aui version activate <id>                 # Activate a specific version
aui version archive <id>                  # Archive (cannot be re-activated)

# Metadata
aui version get <id>                      # View full version details
aui version update <id> --label "Release 2" --tags "prod,stable" --notes "Bug fixes"
```

> **Which agent does `aui version *` target?** Resolution order: `--agent-id`
> (explicit) → the project's `.auirc` (`agent_management_id`, then `agent_id`)
> → the active session's agent. Inside a project, the CLI resolves the
> **project's own** agent; if its `.auirc` ids don't resolve it now errors
> instead of silently falling back to your session's "current" agent. This is
> the same resolver `aui push` uses, so `version` and `push` always target the
> same agent.
>
> **`version create` is single-step and never prompts.** It inspects the
> agent's storage mode (the same `detectAgentBundleMode` switch `push` / `pull`
> / `import` use — honours `AUI_FORCE_AGENT_MODE`, defaults to records on older
> backends) and creates the draft directly:
>
> | Agent mode | Request body |
> |------------|--------------|
> | bundle (`bundle_mode=true`) | `source: "version"`, `from_version: <active version>` (override with `--from`) |
> | records (`bundle_mode=false` / missing) | `source: "agent-scope"` |
>
> `--source` / `--from` / `--from-template` / `--label` / `--tags` / `--notes`
> all override; with no flags it "just works" for the agent's mode. Because it
> never prompts, it's safe for Claude Code, CI, and `agent-builder-bff`
> sandboxes.
>
> **Non-interactive / automation for other `version` subcommands.** `list`,
> `get`, etc. run without prompts in `--json` mode or when stdin/stdout isn't a
> TTY. When several agents could match and none is selected, pass `--agent-id`
> rather than relying on the picker. For programmatic consumers, always read
> IDs and stats from `--json` — the human table abbreviates IDs to fit the
> terminal.

### Knowledge Bases & Documents

```bash
# RAG management
aui rag                                   # Interactive KB menu
aui rag --list                            # List all knowledge bases
aui rag --export                          # Export KBs to knowledge-hubs/
aui rag --import                          # Import KBs from knowledge-hubs/

# Document upload
aui document report.pdf data.csv --kb "Policies"   # Upload files
aui document --url "https://docs.example.com" --kb "Docs"  # Scrape URLs
aui document status                                  # Recent upload status
aui document status --hours 24 --kb "Policies"       # Filtered status
```

### Development Tools

```bash
aui validate                              # Validate all .aui.json files
aui validate ./tools/                     # Validate specific directory
aui validate --strict                     # Treat warnings as errors
aui diff                                  # Changes since last import/push
aui diff ./folder-a ./folder-b            # Compare two directories
aui status                                # Session, agent, and project info
aui revert                                # Discard local changes
```

### Integrations

```bash
aui integration                   # Interactive menu — Create or Discover
aui integration create            # Guided flow — org, account, agent, Manual or Native MCP
aui integration discover          # Guided MCP tool discovery
aui integration toolkits          # List native (Composio) toolkits  (non-interactive, --json)
aui integration tools --slugs ... # Fetch Composio tool descriptors by slug  (non-interactive, --json)
aui integration test --params ... # Live-call an endpoint, return raw + parsed response  (always JSON)
```

**Discovery (fully non-interactive, `--json`):**

```bash
aui integration toolkits --all --json                       # every native toolkit
aui integration toolkits --search notion --json             # filter the directory
aui integration tools --slugs GMAIL_SEND_EMAIL,GMAIL_CREATE_EMAIL_DRAFT --json
aui integration discover --url <mcp-url> --json             # tools from a manual MCP server
```

**Non-interactive — Manual MCP:**

```bash
aui integration create --name "My MCP" --url <url> --all-tools
aui integration create --name "My MCP" --url <url> --tools tool1,tool2
aui integration create --name "My MCP" --url <url> --all-tools --auth-type token --auth-token <token>
aui integration discover --url <url>
aui integration discover --url <url> --auth-type token --auth-token <token>
```

**Non-interactive — Native MCP:**

```bash
aui integration create --toolkit notion --name "Notion" --all-tools
aui integration create --toolkit github --name "GitHub" --tools GITHUB_CREATE_ISSUE,GITHUB_GET_ISSUE
```

**Shared flags (both Manual & Native):**

| Flag | Description |
|------|-------------|
| `--organization-id <id>` | Skip org selection |
| `--account-id <id>` | Skip account selection |
| `--network-id <id>` | Skip agent selection |
| `--version-id <id>` | Agent version ID |
| `--config-method <manual\|native>` | Force config method |
| `--json` | Machine-readable JSON output |

**Test an integration endpoint (`aui integration test`):**

Live-call an integration endpoint and get back the **raw** response
(`test_data`), what the `response_parser` extracts (`parsed_test_response`),
and — on the default path — `mapped_entities` (how the response maps onto
the agent's entities). The programmatic replacement for hand-running `curl`.
Always emits a JSON envelope and is fully non-interactive.

`--raw` vs. the default differ only in what is **sent**:

- **`--raw`** → calls the endpoint **without** `bundle_mapping` (plain
  integration test; no `mapped_entities`).
- **default** → also sends `bundle_mapping` (`response_mapping` +
  `parameters` + `scope_entities`), so the endpoint **also returns
  `mapped_entities`**. This is the path the LLM uses while building an agent.

```bash
# Default — full simulation incl. entity mapping
aui integration test --params '{
  "url": "https://www.themealdb.com/api/json/v1/1/search.php",
  "method": "GET",
  "query_params": { "s": "pasta" },
  "bundle_mapping": {
    "response_mapping": { "entities": [ { "code": "Meal", "identifier": "meal-id", "paths": ["meals"], "mappings": [ { "key": "idMeal", "param": "meal-id" }, { "key": "strMeal", "param": "meal-name" } ] } ] },
    "parameters": [ { "code": "meal-id", "type": "string" }, { "code": "meal-name", "type": "string" } ],
    "scope_entities": [ { "name": "Meal", "identifier": "meal-id", "reference": "meal-name", "parameters": ["meal-id","meal-name"] } ]
  }
}'

# Raw — no bundle_mapping / mapped_entities
aui integration test --raw --url https://www.themealdb.com/api/json/v1/1/search.php --query-params '{"s":"pasta"}'
```

| Flag | Description |
|------|-------------|
| `--params <json>` | Full request body (see fields below) |
| `--params-file <path>` | Read the request body JSON from a file |
| `--url <url>` | Endpoint URL (overrides `params.url`) |
| `--method <method>` | HTTP method (default `GET`) |
| `--request-body <json>` | Request body JSON |
| `--query-params <json>` | Query params JSON |
| `--headers <json>` | Extra request headers JSON |
| `--auth-type <type>` | `BEARER_TOKEN`, `API_KEY`, `BASIC`, `NONE` |
| `--auth-token <token>` | Auth token used with `--auth-type` |
| `--response-parser <js>` | JS snippet run against `response` |
| `--bundle-mapping <json>` | Full `bundle_mapping` (`response_mapping`, `parameters`, `scope_entities`) |
| `--response-mapping <json>` | `bundle_mapping.response_mapping` (from `integrations.aui.json` → `settings.response_mapping`) |
| `--parameters <json>` | `bundle_mapping.parameters` (from `parameters.aui.json` → `parameters`) |
| `--scope-entities <json>` | `bundle_mapping.scope_entities` (from `entities.aui.json` → `entities`) |
| `--raw` | Plain call **without** `bundle_mapping` (no `mapped_entities`) |

> **`authentication` is a discriminated union** keyed on `type`
> (`BEARER_TOKEN`, `API_KEY`, `BASIC`, …). An empty `{}` or one without a
> `type` is treated as "no auth" and dropped automatically (it would
> otherwise 422), so you can paste an integration config verbatim.

Output: `{ "success": true, "data": { url, method, raw, bundle_mapping_sent, test_data, parsed_test_response, mapped_entities } }`.

### Chat & Testing

```bash
aui serve                                 # Web chat playground (localhost:3141)
aui serve --port 8080                     # Custom port
```

### Runtime Messaging — Apollo

Drive an agent at runtime through the Apollo messaging API. These four
commands are **fully non-interactive**, support `--json`, and work for
**any agent** (bundle-mode or records-mode). The target agent is resolved
from `--agent-id` or `.auirc.agent_management_id`, and authentication uses
your normal CLI session (`Authorization: Bearer` — the gateway forwards
Apollo's service auth for you).

```bash
# Start a conversation thread (alias: create-task)
aui apollo create-thread                                 # uses .auirc agent + logged-in user
aui apollo create-thread --agent-id <id> --user-id <id> --task-origin-type web-widget

# Send a message. By default it validates + forwards your local .aui.json
# edits, so the reply reflects them; the returned `id` IS the interaction id.
aui apollo send-message --task-id <id> --text "Hello"                       # trace_info included by default
aui apollo send-message --task-id <id> --text "Hello" --no-bundle           # use the agent's stored/active config instead
aui apollo send-message --task-id <id> --text "Hello" --no-include-trace    # skip trace_info (avoids the extra IA call)

# Regenerate a thread from an interaction and replay a message (bundle + trace on by default)
aui apollo rerun --task-id <id> --interaction-id <iid> --text "Edited"
aui apollo rerun --task-id <id> --interaction-id <iid> --text "Edited" --no-bundle           # use stored/active config
aui apollo rerun --task-id <id> --interaction-id <iid> --text "Edited" --no-include-trace    # skip trace_info
aui apollo rerun --task-id <id> --interaction-id <iid> --text "Edited" --version-id <vid>

# Inspect the agent's reasoning (trace)
aui apollo trace --task-id <id>                          # all interaction traces
aui apollo trace --task-id <id> --interaction-id <iid>   # a single interaction's trace
```

**Flags by command**

| Command | Required | Optional |
|---|---|---|
| `create-thread` (alias `create-task`) | — | `--agent-id`, `--user-id`, `--task-origin-type`, `--json` |
| `send-message` | `--task-id`, `--text` | `--no-bundle`, `--no-include-trace`, `--agent-id`, `--path`, `--json` |
| `rerun` | `--task-id`, `--interaction-id`, `--text` | `--no-bundle`, `--no-include-trace`, `--version-id`, `--agent-id`, `--path`, `--json` |
| `trace` | `--task-id` | `--interaction-id`, `--agent-id`, `--json` |

> **Bundle on by default:** both `send-message` and `rerun` validate + forward
> your local agent files by default (so the reply reflects your edits). Pass
> `--no-bundle` to use the agent's stored/active config instead. Run these
> inside an imported agent folder (or pass `--path <dir>`). `--with-bundle` is
> still accepted as a deprecated no-op.

> **Interaction IDs:** the `id` returned by `aui apollo send-message` is the
> interaction id — pass it to `rerun --interaction-id` and `trace
> --interaction-id`.

> **Validate-before-send:** by default `send-message` / `rerun` run the remote
> validator on your local files first and abort if they're invalid — a broken
> config never reaches the runtime. Run `aui validate` to see specific errors.

### Configuration & Utilities

```bash
aui account                               # Manage accounts (list, create, switch)
aui env                                   # Show current environment
aui env staging                           # Switch environment
aui pull-schema                           # Fetch domain schemas from backend
aui add-integration                       # Add API / RAG / MCP integration (legacy)
aui integration create                    # Create MCP integration (Manual or Native)
aui upgrade                               # Update to latest version
```

### Command Aliases

| Alias | Equivalent |
|-------|------------|
| `aui import` | `aui import-agent` |
| `aui accounts` | `aui account` |
| `aui agents` | `aui agent` |
| `aui ls` | `aui list-agents` |
| `aui versions` | `aui version` |
| `aui integrations` | `aui integration` |

---

## Workflows

### Create and Deploy a New Agent

```bash
# Step 1: Create the agent. This also auto-imports it into ./support-agent
# and drops you into that folder via an interactive subshell — no separate
# `aui import-agent` needed. (Use --dir to choose a different folder.)
aui agents --create --name "Support Agent" --account-id <id>

# Step 2: Edit configuration in your editor (you're already in the folder)
# → Edit agent.aui.json, tools/*.aui.json, parameters.aui.json, etc.

# Step 3: Validate and push
aui validate
aui push

# Step 4: Publish and activate
aui version publish
aui version activate
```

> Prefer the classic two-step flow? It still works: create with `--json`
> (which skips the auto-import/subshell), then run `aui import-agent` yourself.

**Creation modes:**

```bash
# Default — creates the agent + a v1.0 draft version (ready to import & edit).
# A draft is always created; there is no flag to skip it.
aui agents --create --name "Support Agent" --account-id <id>

# Agent + v1.0 + publish + activate — fully deployed in one step (CI/CD)
aui agents --create --name "Support Agent" --account-id <id> --full
```

### Edit → Push → Deploy Cycle

```bash
# 1. Create a draft version first
aui version create                # Creates draft v2

# 2. Import the draft as local files
aui import-agent --version <draft-id>
cd ./my-agent

# 3. Make changes to any .aui.json file...

# 4. Validate and push
aui diff                          # See what changed
aui validate                      # Validate against schemas
aui push                          # Push changes into the draft

# 5. If push fails partially, re-run to retry
aui push                          # Retries only failed changes

# 6. Publish and go live
aui version publish               # Lock the draft
aui version activate              # Make it live
```

### Version Branching

```bash
# Clone from an existing version (→ v3)
aui version create --source version --from <v2-id>

# New version from live scope (→ v3)
aui version create --source agent-scope

# Import a specific version for editing
aui import-agent --version <version-id>
```

---

## Project Structure

After `aui import-agent`, your project folder contains:

```
my-agent/
│
├── agent.aui.json                 # Agent identity and behavior
├── parameters.aui.json            # Parameters (input/output data)
├── entities.aui.json              # Entity groups
├── integrations.aui.json          # API / RAG / MCP connections
├── rules.aui.json                 # Global behavioral rules
├── widgets.aui.json               # Card templates (JSX + field mappings)
│
├── tools/                         # One file per agent tool/capability
│   ├── product_search.aui.json
│   ├── generative_ai.aui.json
│   └── ...
│
├── knowledge-hubs/                # Knowledge base data
│   ├── policies/
│   │   ├── kb.json                #   KB metadata
│   │   └── company-policies.pdf   #   Downloaded files
│   └── ...
│
├── schemas/                       # Domain schemas (auto-fetched)
│   ├── agent.dschema.json
│   ├── tools.dschema.json
│   ├── parameters.dschema.json
│   ├── entities.dschema.json
│   ├── integrations.dschema.json
│   ├── rules.dschema.json
│   ├── widgets.dschema.json
│   └── knowledge-bases.dschema.json
│
├── memory/                        # Push logs (auto-generated)
├── .auirc                         # Project config (agent ID, version, env)
├── .vscode/settings.json          # Schema autocomplete for VS Code / Cursor
├── .gitignore
│
├── GUIDE.md                       # Getting started guide
├── AGENTS.md                      # Agent documentation
│
├── .cursor/skills/                # Cursor skills per config type
├── .claude/skills/                # Claude Code skills per config type
└── .opencode/skills/              # OpenCode skills per config type
```

---

## Configuration File Reference

### agent.aui.json

The agent's identity and top-level behavior:

```json
{
  "general_settings": {
    "name": "Support Agent",
    "objective": "Help customers find products and resolve issues",
    "persona_guidelines": "You are a friendly and knowledgeable support agent...",
    "tone_of_voice": "Professional but approachable",
    "guardrails": "Never share internal pricing. Always verify identity...",
    "brevity": "concise",
    "context": "This agent serves an e-commerce platform..."
  }
}
```

### parameters.aui.json

Parameters the agent collects from users or outputs:

```json
{
  "parameters": [
    {
      "code": "product-type",
      "description": "The type of product the customer is looking for",
      "type": "string",
      "usage": "ALL"
    },
    {
      "code": "budget-range",
      "description": "Customer's budget",
      "type": "enum",
      "usage": "INPUT",
      "values": ["under-50", "50-100", "100-200", "200-plus"]
    }
  ]
}
```

### tools/*.aui.json

Each tool defines a capability with triggers, parameters, integrations, and rules:

```json
{
  "tool": {
    "name": "Product Search",
    "code": "PRODUCT_SEARCH",
    "goal": "Help the user find products that match their preferences",
    "when_to_use": "When the user asks to browse, search, or find products",
    "status": true,
    "response_type": "TEXT_CARDS",
    "config": {
      "params": {
        "required": [["product-type"]],
        "optional": ["budget-range", "color", "size"]
      }
    },
    "integrations": [
      { "code": "product-api", "is_main": true }
    ],
    "card_template_code": "product-card"
  }
}
```

### widgets.aui.json

Card templates with JSX and field mappings:

```json
{
  "widgets": [
    {
      "name": "product-card",
      "jsx_template": "<Card><Image src={image} /><Text value={title} /></Card>",
      "fields": [
        { "name": "image", "param": "product-image" },
        { "name": "title", "param": "product-name" }
      ],
      "tool_name": "PRODUCT_SEARCH"
    }
  ]
}
```

---

## Version Management

### How Versioning Works

Pushing is only allowed to **draft versions**. The CLI will never auto-create drafts during push — you must create one explicitly first.

1. **Create a draft version** using `aui version create`
2. **Import** the draft to get local files: `aui import-agent --version <draft-id>`
3. **Edit** the local `.aui.json` files
4. **Push** changes into the draft (the CLI validates the target is a draft)
5. **Publish** to lock the draft permanently
6. **Activate** to make it the live configuration

```bash
aui version create        # Create draft v2 (always bumps version number)
aui import-agent --version <draft-id>  # Get the draft as local files
# Edit files...
aui push                  # Pushes into the draft (rejects if not a draft)
aui version publish       # Locks v2
aui version activate      # v2 is now live
```

### Push Flow (detailed)

When you run `aui push`, the following happens:

1. **Draft validation** — The CLI checks that the target version is a draft. If the version in `.auirc` or `--version-id` is not a draft (e.g. published, archived), push is rejected with a descriptive error and next steps.

2. **Entity push** (Step A) — The CLI pushes individual entity changes (parameters, tools, integrations, etc.) to the agent-settings API. Each task is tracked with success/failure, and the flow continues even when some entities fail.

3. **Snapshot push** (Step B — last step) — After entity push completes, the CLI uploads the local file state as a snapshot to the server. This **always runs** regardless of entity-push outcomes, because **files are the source of truth** — the snapshot preserves your local state even if some DB updates failed. Version tag is bumped automatically on the server when the snapshot succeeds (e.g. `v3.2 → v3.3`).

4. **Baseline update** — Local git baseline is committed only if the snapshot succeeded. Within that, only files whose entity-push succeeded are added to the baseline.

#### Why snapshot-last?

The snapshot is meant to reflect what's actually been applied to the agent. Putting it after the entity push means:

- **Snapshot ≈ DB state** — the IA/AI tooling can rely on the snapshot files as the source of truth without ever hitting the entity DB
- **Auto-bump represents real updates** — `v{N}.X` only increments when a push attempt actually completed
- **File-level rejections are caught locally** by `aui validate` (schema + cross-ref checks) before push, so server-side snapshot validation rarely fails
- **Partial DB failures are tolerable** — the snapshot still uploads, preserving file history. Re-running `aui push` retries the failed entities (PATCHes are idempotent)

#### Failure scenarios

| What failed | What happens | Next step |
|-------------|--------------|-----------|
| Entity push partial | Snapshot still uploads (captures file state). Baseline committed only for succeeded files. | Re-run `aui push` to retry failed entity updates. |
| Snapshot fails after entity push succeeded | Baseline is **not** updated. Entity changes already in DB. | Re-run `aui push`. Entities will re-PATCH (idempotent), then snapshot retries. |
| Both fail | Baseline unchanged. | Fix issues from error output, re-run `aui push`. |

If push partially fails, it's the user's responsibility to re-run `aui push` to retry. The CLI shows descriptive errors with "What to do next" guidance for every failure mode.

### Version Numbering

Versions use simple incrementing numbers: v1, v2, v3, etc. There are no revision/minor numbers.

- Use `--source version --from <id>` to clone from an existing version
- Use `--source agent-scope` for a new version from the current live scope


---

## Knowledge Bases

### Upload Documents

```bash
# Upload files
aui document report.pdf handbook.docx --kb "Company Policies"

# Scrape web pages
aui document --url "https://docs.example.com/faq" --kb "FAQ"
```

### Check Upload Status

```bash
aui document status                        # Last 6 hours
aui document status --hours 24             # Last 24 hours
aui document status --kb "Company Policies"  # Filter by KB
```

### Export & Import

```bash
aui rag --export    # Save all KB metadata and files to knowledge-hubs/
aui rag --import    # Restore KBs from knowledge-hubs/
```

---

## CI/CD & Automation

Every command supports non-interactive flags for pipeline integration.

### Environment Variables for CI

```bash
export AUI_AUTH_TOKEN="<jwt-token>"
export AUI_ENVIRONMENT="production"
export AUI_ACCOUNT_ID="<account-id>"
export AUI_ORGANIZATION_ID="<org-id>"
```

### Example Pipeline

```bash
# Login with token
aui login --token "$AUI_AUTH_TOKEN" --environment production

# Import, validate, push
aui import-agent <agent-id> --dir ./agent-config
cd ./agent-config
aui validate --strict
aui push

# Publish and activate
aui version publish
aui version activate
```

### All Environment Variables

| Variable | Description |
|----------|-------------|
| `AUI_AUTH_TOKEN` | Auth token (skip interactive login) |
| `AUI_API_URL` | Override API base URL |
| `AUI_ENVIRONMENT` | `staging`, `custom`, or `production` |
| `AUI_ACCOUNT_ID` | Account ID |
| `AUI_ORGANIZATION_ID` | Organization ID |
| `AUI_KBM_API_KEY` | RAG API key |
| `AUI_AGENT_TOOLS_API_KEY` | Agent Settings API key |
| `AUI_API_WORKFLOW_KEY` | API Workflow key |
| `AUI_DEBUG` | Enable verbose debug logging (`AUI_DEBUG=1`) |

---

## Configuration

### Global Config Files

| File | Purpose |
|------|---------|
| `~/.aui/session.json` | Auth token, org, account, agent, environment |
| `~/.aui/environment` | Selected environment |
| `~/.aui/kbm-key` | RAG API key |
| `~/.aui/agent-settings-key` | Agent Settings API key (fallback) |
| `~/.aui/api-workflow-key` | API Workflow key |

### Project Config (.auirc)

Created during import, stored in the project root:

```json
{
  "agent_code": "support-agent",
  "agent_id": "69cd0a61b6924d36aafaf3f6",
  "environment": "custom",
  "account_id": "69c919bcb506d3e323e0397e",
  "organization_id": "68c004560ed54fdf78c551d1",
  "network_category_id": "69b2e9385d33a2096c543294",
  "version_id": "69cd0ca8168d739104520c60",
  "version_label": "v1.2"
}
```

### Environments

```bash
aui env                   # Show current
aui env staging           # Switch to staging
aui env custom            # Switch to custom (v3 endpoints)
aui env production        # Switch to production
aui login --environment staging  # Set during login
```

---

## Troubleshooting

### Enable Debug Logging

```bash
AUI_DEBUG=1 aui push
AUI_DEBUG=1 aui import-agent <id>
```

Debug mode logs every API request URL, response status, and body.

### Common Issues

| Issue | Solution |
|-------|---------|
| `Not logged in` | Run `aui login` |
| `Missing network_category_id` | Re-import the agent: `aui import-agent` |
| `Version not found` | Run `aui version list` to see available versions |
| `Version not found` (id looks truncated) | The human `version list` table abbreviates IDs. Scrape IDs from `aui version list --json` |
| `Could not resolve the agent for this project (.auirc)` | Pass `aui version … --agent-id <agent-management-id>`, or re-run `aui import` / `aui pull` to refresh `.auirc` |
| `version create` made a draft on the wrong agent | Fixed — `version` now targets the project's `.auirc` agent (or `--agent-id`), not the session's "current" agent |
| `422` with no detail | The CLI now surfaces the API's validation detail in the error message. Re-run; for full bodies use `AUI_DEBUG=1` |
| `422 on push` | Check `aui validate --strict` for schema errors. Review `.aui/push-logs/` for API details |
| `No changes detected` | The push baseline matches your files. Make an edit and try again |
| Agent settings 401/403 | Provide an API key: `aui push --api-key <key>` |
| README not showing on npm | Ensure `README.md` is at the package root before `npm publish` |

### Push Logs

Every push saves detailed API call logs:

```
.aui/push-logs/
├── POST-tool-product_search.txt
├── PATCH-param-budget-range.txt
└── ...
```

### Push Memory

Push results are saved as markdown for reference:

```
memory/
└── push-2026-04-01T12-16-41-772Z.md
```

---

## Local Development

```bash
git clone <repo-url>
cd aui-agent-builder
npm install
npm run build
npm link              # Makes `aui` available globally from source
```

```bash
npm run watch         # Recompile on file changes
npm test              # Run tests
```

---

## Updating

```bash
aui upgrade                          # Auto-detect npm or Homebrew
npm install -g aui-agent-builder     # Manual npm
brew update ; brew upgrade aui-io/homebrew-tap/aui    # Manual Homebrew
```

The CLI checks for updates every 24 hours and shows a notification banner when a new version is available.

---

## Architecture & Developer Context

This section provides context for developers (and AI assistants) working on the CLI codebase.

### Project Structure (source)

```
aui-agent-builder/
├── bin/aui.js                    # Executable shim → dist/index.js
├── src/
│   ├── index.ts                  # CLI entry — Commander program, all command wiring
│   ├── telemetry.ts              # OpenTelemetry tracing (Logfire)
│   ├── commands/                 # One file per command
│   │   ├── push.tsx              # Push flow (snapshot → entity push → bump)
│   │   ├── version.tsx           # Version lifecycle (create, publish, activate, archive)
│   │   ├── agents.tsx            # Agent management (create, list, switch, import)
│   │   ├── import-agent.tsx      # Import agent as local .aui.json files
│   │   ├── pull-agent.tsx        # Pull latest from backend
│   │   ├── login.tsx             # Authentication flow
│   │   └── ...                   # Other commands
│   ├── api-client/
│   │   ├── index.ts              # AUIClient — all HTTP calls to backend
│   │   ├── kb-view-client.ts     # Knowledge base API client
│   │   └── rag-client.ts         # RAG API client
│   ├── config/
│   │   └── index.ts              # Config resolution (env → .auirc → session → defaults)
│   ├── errors/
│   │   └── index.ts              # Structured error types (AuthError, ConfigError, etc.)
│   ├── services/                 # Business logic services
│   ├── types/                    # TypeScript interfaces for local agent files
│   ├── ui/                       # Ink components and views
│   │   ├── components/           # Reusable UI atoms (Spinner, StatusLine, etc.)
│   │   ├── views/                # Command-specific views (PushView, etc.)
│   │   └── theme.ts              # Colors, icons, labels
│   └── utils/                    # Git, JSON output, schema improvements
└── package.json
```

### Key Patterns

- **Commander** for CLI argument parsing, **Ink + React** for terminal UI
- **AUIClient** in `api-client/index.ts` is the single HTTP layer; all API calls go through it
- Two API surfaces: **Agent Management** (versions lifecycle) and **Agent Settings** (entity CRUD for push)
- **Config resolution**: `getConfig()` merges env vars → `.auirc` → `~/.aui/session.json` → defaults
- **Git baseline**: Push uses an internal git repo to track diffs between pushes

### Push Flow (current implementation)

1. Validate auth and project config
2. Read local `.aui.json` files
3. Git diff to detect changes since last push
4. **Draft validation**: Verify the target version is a draft (reject otherwise)
5. **Entity push**: PATCH/POST/DELETE individual entities (parameters, tools, integrations, rules, etc.) — track per-task success, continue on failures
6. **Snapshot push** (last step): Multipart POST of all local files to `/v1/agents/{agentId}/versions/{versionId}/snapshot`
   - Uses JWT auth (Bearer token)
   - Runs regardless of entity-push outcomes (files = source of truth, DB = best effort)
   - Version tag is bumped automatically on snapshot success (no separate bump endpoint)
   - Snapshot tags follow the pattern `v{N}.0`, `v{N}.1`, `v{N}.2`, ... where `N` is the version number; the first push to a version creates `.0`
   - Implemented in: `pushSnapshot()` in `src/commands/push.tsx` + `client.agentManagement.pushSnapshot()` in `src/api-client/index.ts`
7. **Baseline update**: Git baseline is committed only when the snapshot succeeded. Within that, only files whose entity-push succeeded are added.

### Snapshot Endpoints

- **POST** `/v1/agents/{agentId}/versions/{versionId}/snapshot` — Upload local files as multipart form data. Version tag bumps automatically on success.
- **GET** `/v1/agents/{agentId}/versions/{versionId}/snapshot?version_tag=v1.0&expires_in=15` — Retrieve a specific snapshot's manifest + signed download URLs (15-minute expiry).

### Snapshot Browsing (CLI)

| Command | Purpose |
|---------|---------|
| `aui version snapshot` | Interactive menu (list / get / diff) |
| `aui version snapshot list` | List all snapshots for the current version |
| `aui version snapshot get <tag>` | Show snapshot manifest + signed URLs |
| `aui version snapshot diff <a> <b>` | File-level diff (SHA-256 + size) |
| `aui version snapshot diff <a> <b> --full` | Field-level JSON diff (downloads files) |

All snapshot commands support `--agent-id`, `--version-id`, and `--json` for scripting.

### Version Numbering

Versions use simple incrementing numbers (v1, v2, v3). No revision/minor numbers.
The `bump_mode` parameter in `CreateDraftRequest` is always set to `"version_number"`.

---

## License

Proprietary — Copyright (c) 2026 AUI. All rights reserved. See [LICENSE](./LICENSE).
