# Ailin CLI

Agentic, multi-model coding assistant that pairs with the Ailin API to reason about your codebase, run automated workflows, and manage enterprise governance from the terminal.

---

## Overview

Ailin CLI brings the same orchestration platform that powers the Ailin desktop experience to any repository. The tool combines deep code understanding, configurable automation loops, and enterprise controls so that developers can:

- Chat with an AI pair-programmer that understands the local repository.
- Automate tests, refactors, and release workflows through watch/TDD loops.
- Inspect usage quotas, billing, and feature flags for regulated environments.
- Extend behavior with custom plugins, tools, and themes.

The CLI talks to the `Ailin API` backend and mirrors its authentication, RBAC, telemetry, and observability stack.

---

## Requirements

- Node.js `>= 18.0.0`
- pnpm `>= 8.0.0`
- Access to an Ailin API deployment (self-hosted or cloud)
- Git (recommended for checkpoint and diff features)
- Whenever a prebuilt `tree-sitter` binding is not available for the current platform/Node.js ABI the installer will compile one locally. Windows users on Node.js 22+ must have the **Visual Studio Build Tools 2022** workload “Desktop development with C++” + the latest Windows SDK installed. On macOS, install the Xcode Command Line Tools (`xcode-select --install`). See `docs/PREBUILDS.md` for the prebuild publishing pipeline.

Optional runtime integrations:

- Stripe account (enterprise billing flows)
- Redis/Postgres when using the Ailin API locally (see `api/README.md`)
- Graphviz (to render exported DOT dependency graphs)

---

## Installation

```powershell
cd C:\GitHub\ailin.one\ailin-dev\cli
pnpm install
pnpm build
```

During development you can run:

```powershell
pnpm dev              # starts the CLI in watch mode
pnpm dev:mock         # runs the CLI against the local mock server
pnpm mock:server      # mock API only
```

The published package exposes the `ailin` binary. For local mono-repo usage you can execute with `pnpm exec tsx src/index.ts`.

---

## First-Time Setup

1. **Run the setup wizard**
   ```powershell
   ailin setup
   ```
   The wizard collects API credentials, organization metadata, preferred models, and UI defaults. Secrets are stored through the secure storage layer (`keytar` on supported platforms).

2. **Use environment variables (optional)**
   - `AILIN_API_URL`, `AILIN_API_KEY`, `AILIN_ORG_ID`
   - `AILIN_USER_EMAIL` when using email-code login
   - `AILIN_DEFAULT_MODEL`, `AILIN_FALLBACK_MODEL`
   - `AILIN_TUI_MODE` for the preferred TUI mode

3. **Check validation**
   ```powershell
   ailin config list
   ailin config get api
   ```
   The CLI validates configuration on every run and explains missing requirements (API key, organization ID, etc.).

Configuration is persisted to `%USERPROFILE%\.ailin\config.json`. Sensitive values (`api.key`, `api.authToken`, `api.refreshToken`) are persisted via secure storage and omitted from disk.

---

## Key Features

- **Interactive chat & one-shot prompts** – Default entry point (`ailin` or `ailin chat`) launches an intelligent TUI that renders diffs, code blocks, and tool usage with streaming responses.
- **Advanced/Basic TUI modes** – `--tui-mode advanced` (default) offers Ink-based rendering with tool call visualization; `--tui-mode basic` falls back to Inquirer prompts for maximum compatibility.
- **Workflow automation** – `ailin watch`, `ailin tdd`, alias macros, and advanced watch comments (`@ailin?` / `@ailin!`) enable continuous AI-driven operations.
- **Deep code understanding** – Tree-sitter powered parsing, AST analysis, symbol extraction, dependency graphs, and impact analysis exposed through the `@ailinone/cli/codebase` module.
- **Session management** – Persist, inspect, export, and delete conversation sessions from the terminal.
- **Checkpointing** – Capture/restore file + conversation state snapshots to experiment safely.
- **Plugin system** – Load TypeScript/JavaScript plugins that register tools, subscribe to hooks, or add custom CLI commands.
- **Enterprise controls** – Inspect quotas, billing details, feature flags, users, and teams directly from the CLI with RBAC-aware APIs.
- **Telemetry & metrics** – Emit and inspect OpenTelemetry traces/logs/metrics; view local performance metrics via `ailin metrics`.
- **Localization** – Built-in translations for multiple locales (English, Spanish, Portuguese, French, German, Italian, Dutch, Japanese, Korean, Chinese, Arabic, Hebrew, Russian).

---

## Usage Guide

### Default entry point

- `ailin` – Launch advanced TUI chat or execute a one-shot prompt when arguments are provided.
  ```powershell
  ailin                                   # interactive chat
  ailin "Refactor the payment service"   # one-shot prompt
  ailin -m anthropic-claude-3-5-sonnet "Summarize src/index.ts"
  ailin --diff "Create a new CLI command"  # dry-run mode
  ailin --clipboard "Explain the last commit"  # copy last code block
  ```

- `ailin chat --tui-mode basic` – Force the lightweight interface (useful in constrained terminals or CI).

### Setup and configuration

- `ailin setup` – Re-run the onboarding wizard.
- `ailin config list` – Dump merged configuration.
- `ailin config get <path>` – Retrieve nested config values (e.g., `ailin config get models`).
- `ailin config set <path> <value>` – Persist overrides (`value` accepts JSON strings).

### Session management

- `ailin sessions --list` – Show stored sessions, highlight the active conversation.
- `ailin sessions --show <id>` – Display metadata, message count, timestamps.
- `ailin sessions --delete <id>` / `--clear` – Clean up sessions.
- `ailin sessions --export <id> [path]` – Export JSON for audits or handovers.

### Agent workflows

- `ailin watch` – Watch files, run shell commands, or route changes through the AI agent.
  - `--pattern` / `--ignore` accept glob patterns.
  - `--command` executes on change.
  - `--ai` transforms change events into AI prompts.
  - `--advanced` enables smart comment triggers. Comments such as `// @ailin? Summarize this file` or `// @ailin! add tests` can auto-trigger prompts; disable execution with `--no-auto-execute`.

- `ailin tdd` – Continuous test-driven loop.
  - Watches source files, runs the provided test command, and optionally lets the agent auto-fix failing tests.
  - `--test-command` defines the script (default `npm test`), `--no-auto-fix` disables automated remediation.

- `ailin alias` – Manage prompt macros.
  - `ailin alias set hotfix "Write a hotfix plan for {{module}}" -d "Incident runbook"`
  - `ailin alias run hotfix -v module=payment-service`
  - Supports usage statistics and templated variables.

- `ailin checkpoint` – Snapshot and restore project state.
  - `create`, `list`, `show`, `restore [--dry-run]`, `delete`
  - Stores file hashes, conversation metadata, and tool invocation context.

### Plugins and extensibility

- `ailin plugins list` – Enumerate detected plugins (active/inactive).
- `ailin plugins enable ./plugins/my-plugin.js`
- `ailin plugins disable my-plugin`

Plugins can register new CLI commands, tools, or hook listeners. See `docs/PLUGIN_SYSTEM.md` and `examples/example-plugin.ts` for complete walkthroughs.

### Models and themes

- `ailin models list` / `ailin models info <modelId>` – Inspect synchronized model catalog (provider, context window, pricing, capabilities).
- `ailin theme list | set <name> | current | save <name> <path>` – Switch or store custom themes for the TUI.

### Diagnostics and updates

- `ailin debug-last-error` – Print the most recent command failure and request an AI explanation.
- `ailin metrics` – View local performance metrics; supports filtering, exporting (`--export metrics.json`), Prometheus format, operation stats, and clearing.
- `ailin update` – Check the npm registry for new CLI versions.
- `ailin version` – Display current CLI version banner.

### Enterprise management

All enterprise commands require appropriate roles (as defined by the backend RBAC policies).

- `ailin enterprise users` – Launch interactive user management (IdP-backed permission system).
- `ailin enterprise teams` – Manage teams and organizational structure.

**Quotas**
```powershell
ailin enterprise quotas --list
ailin enterprise quotas --usage
ailin enterprise quotas --set @configs/quota.json
ailin enterprise quotas --check @payloads/operation.json
ailin enterprise quotas --reset --period month
```

**Billing & invoicing**
```powershell
ailin enterprise billing --config-get
ailin enterprise billing --plans --plans-refresh
ailin enterprise billing --invoices
ailin enterprise billing --invoice-create @invoice.json
ailin enterprise billing --payment-methods
ailin enterprise billing --payment-method-attach pm_123
```

**Feature flags**
```powershell
ailin enterprise features --list
ailin enterprise features --enable codegen_v2
ailin enterprise features --disable beta_ui
```

### Telemetry

The CLI ships with an OpenTelemetry SDK (`core/telemetry`) that can export traces, metrics, and logs via OTLP HTTP/GRPC. Configure using:

- `AILIN_OTEL_ENABLED`, `AILIN_OTEL_EXPORTER`, etc. (see `docs/PERFORMANCE_CONFIGURATION.md`)
- Rate limiter namespaces ensure telemetry floods are contained.

---

## Code Understanding APIs

The package exports analysis utilities for integrating Ailin’s code intelligence into other tooling:

- `CodebaseAnalyzer` – Analyze files, a whole repository, compute statistics, detect circular dependencies, derive impacted files.
- `CodeParser` – Tree-sitter based parsing with language autodetection.
- `ASTAnalyzer` – Traverse ASTs to extract functions, classes, imports/exports.
- `SymbolExtractor` – Index and query symbols across the codebase.
- `DependencyGraphBuilder` – Build graph structures, export DOT/JSON.

Example (TypeScript):
```typescript
import { CodebaseAnalyzer } from '@ailinone/cli/codebase';

const analyzer = new CodebaseAnalyzer();
await analyzer.analyzeCodebase('./src', {
  include: ['**/*.ts', '**/*.tsx'],
  exclude: ['**/node_modules/**', '**/.git/**'],
});

const functions = analyzer.findSymbolsByType('function');
console.log(`Functions found: ${functions.length}`);
```

Supported languages include TypeScript, JavaScript, Python, Go, Rust, Java, C, C++, with optional grammars for many others via optional dependencies.

---

## Configuration Reference

Configuration keys follow the structure defined in `src/config/config-manager.ts`. Highlights:

- `api` – Backend URL, credentials, organization ID, login mode, queue timeouts, negotiated feature flags.
- `models` – Default/fallback IDs, per-capability preferences, usage limits, temperature.
- `tools.approvals` – Approval policy (`auto`, `ask`, `deny`) for file operations, shell commands, git commands.
- `codebase` – Indexing behavior, ignore patterns, size limits, project identifiers.
- `security` – Sandbox limits, allowed/blocked executables, command rate limits.
- `plugins` – Enabled plugin entries and directory.
- `permissions` – RBAC defaults and custom role bindings.
- `ui` – TUI mode, colors, theme overrides.
- `performance.rateLimiter` – Global and namespace throttling values.

Use `ailin config set permissions.defaultRole "reviewer"` to adjust defaults or modify `%USERPROFILE%\.ailin\config.json` directly.

---

## Testing

```powershell
pnpm test                 # unit + integration
pnpm test:watch           # watch mode
pnpm test:coverage        # coverage report
pnpm test:e2e             # CLI end-to-end suite
pnpm validation-tests     # see validation-tests/ README for advanced scenarios
```

Mocked runs can use the bundled server (`pnpm dev:mock`). Integration suites expect access to the real API unless otherwise configured.

---

## Advanced Documentation

- `docs/CODE_UNDERSTANDING.md` – In-depth explanation of the parser and symbol engine.
- `docs/TUI_MODE_GUIDE.md` – UI customization and fallbacks.
- `docs/PERFORMANCE_CONFIGURATION.md` – Rate limiting, telemetry tuning, resource monitoring.
- `docs/LANGUAGE_STRATEGY_GUIDE.md` – Multi-language prompts and translation strategy.
- `docs/PLUGIN_SYSTEM.md` – Writing, packaging, and publishing plugins.
- `docs/PREBUILDS.md` – Generating and shipping native bindings.
- `docs/BUNDLING.md` – Single-file distribution strategy and bundling pipeline.
- `docs/TUI_MODE_GUIDE.md`, `docs/DESIGN_SYSTEM.md` – Terminal UI components and theming.
- `examples/` – Sample prompts, plugin templates, TUI demos.

---

## Troubleshooting

- **Authentication required** – Ensure `AILIN_API_KEY` or email-based login is configured. `ailin setup` can refresh tokens.
- **Version mismatch** – The CLI negotiates minimum/maximum compatible versions with the server. Upgrade if prompted (`ailin update`).
- **Plugin errors** – The CLI logs warnings during startup. Use `ailin plugins list --all` to investigate inactive plugins.
- **Advanced TUI issues** – Set `AILIN_TUI_MODE=basic` or run `ailin chat --tui-mode basic`.
- **Sandbox denials** – Adjust `security.sandboxAllowedExecutables` via config/environment.
- **Rate limits** – Modify `performance.rateLimiter` or specific namespace limits in config.

For deeper operational guidance consult `api/docs/OPERATIONS_RUNBOOK.md` and the observability/disaster recovery guides in the API project.

---

## License

Distributed under the ISC license. See `LICENSE` for details.


