# Source Map

A practical map for finding the real implementation behind CLI commands, API routes, TUI views, mobile flows, providers, plugins, and storage.

## Overview

The main runtime lives in `packages/nikcli/src`. The repo is a Bun monorepo, so related packages also matter: `packages/sdk/js` for generated client types, `packages/plugin` for plugin contracts, `packages/mobile` for the Expo app, `packages/web` for this docs site, `packages/llm` for route-based LLM providers, and `packages/remote` for remote execution support.

This map is meant for tracing behavior from a symptom to the source. Start at the command or route entry, then follow service imports into the domain module.

## Top-level entry

`packages/nikcli/src/index.ts` registers every CLI command with yargs, initializes global directories, initializes logging, sets `AGENT=1` and `NIKCLI=1`, and catches fatal errors for user-facing formatting.

Terminal

bash 

```
bun run --cwd packages/nikcli --conditions=browser src/index.ts --help
bun run --cwd packages/nikcli --conditions=browser src/index.ts serve --help
bun run --cwd packages/nikcli --conditions=browser src/index.ts mcp --help
```

$ shell · paste into your terminal

| Need | Start here | Then inspect |
| --- | --- | --- |
| Command registration | `src/index.ts` | `src/cli/cmd/*.ts` |
| Global paths | `src/@nikcli-ai/util/global` | `NIKCLI_DATA_DIR`, XDG/AppData rules. |
| Logging | `@nikcli-ai/util/log` | `--print-logs`, `--log-level`. |
| Error formatting | `src/cli/error.ts` | Command-specific thrown errors. |

## Runtime domains

Entry

### CLI and TUI

`src/cli/cmd` contains commands. `src/cli/cmd/tui` contains the OpenTUI/Solid renderer, worker RPC, routes, dialogs, plugins, and contexts.

HTTP

### Server

`src/server/server.ts` owns middleware and route mounting. `src/server/httpapi` owns classic routes. `src/server/httpapi` owns typed route groups.

Agent

### Sessions

`src/session` owns session lifecycle, prompt execution, LLM normalization, messages, status, revert, compaction, todo, and stats.

Tools

### Extensions

`src/plugin`, `src/mcp`, `src/connectors`, `src/skill`, and `src/tool` expose extra capabilities to agents.

## CLI command map

Every public command is imported and registered in `src/index.ts`.

| Command | File | Domain |
| --- | --- | --- |
| Default TUI | `cli/cmd/tui/thread.ts` | Worker RPC, SDK fetch, OpenTUI app. |
| `run` | `cli/cmd/run.ts` | Headless prompt execution. |
| `serve` | `cli/cmd/serve.ts` | General HTTP API server. |
| `mobile` | `cli/cmd/mobile.ts` | Mobile host, pairing, token list/revoke. |
| `remote` | `cli/cmd/remote.ts` | Terminal remote plus optional mobile host. |
| `mcp` | `cli/cmd/mcp.ts` | MCP config, OAuth, list, debug, logout. |
| `connectors` | `cli/cmd/connectors.ts` | External service config and credentials. |
| `plugin` / `plug` | `cli/cmd/plug.ts` | Plugin install, manifest read, config patch. |
| `models` | `cli/cmd/models.ts` | Provider/model catalog. |
| `debug` | `cli/cmd/debug` | Config, LSP, skill, snapshot, search, file utilities. |
| `routine` | `cli/cmd/routine.ts` | Routine CRUD, run, pause, resume. |
| `account` | `cli/cmd/account.ts` | Local account management. |

## Server map

Server behavior starts in `src/server/server.ts`. The exact route order matters: share routes, user auth middleware, server auth, CORS, `/global`, workspace context, `/doc`, typed bridge, then classic route groups.

| Feature | Classic route | Typed route where present |
| --- | --- | --- |
| Session | `server/httpapi/session.ts` | `server/httpapi/session.ts` |
| File | `server/httpapi/file.ts` | `server/httpapi/file.ts` |
| Provider | `server/httpapi/provider.ts` | `server/httpapi/provider.ts` |
| MCP | `server/httpapi/mcp.ts` | `server/httpapi/mcp.ts` |
| Config | `server/httpapi/config.ts` | `server/httpapi/config.ts` |
| Workspace | `server/httpapi/workspace.ts` | `server/httpapi/workspace.ts` |
| Question | `server/httpapi/question.ts` | `server/httpapi/question.ts` |
| Permission | `server/httpapi/permission.ts` | `server/httpapi/permission.ts` |
| Mobile | `server/httpapi/mobile.ts` | Classic only. |
| Analytics | `server/httpapi/analytics.ts` | Classic only. |

## Session and LLM map

| Need | File | What to look for |
| --- | --- | --- |
| Create/list/update/remove | `session/index.ts` | `Session.Service` methods and storage keys. |
| Prompt execution | `session/prompt.ts` | Tool setup, system prompt assembly, request loop. |
| LLM provider hot path | `session/llm.ts` | Message normalization, headers, provider transforms, tool conversion. |
| Native provider runtime | `session/llm/native-runtime.ts` | `@nikcli-ai/llm` route-based streaming for supported providers. |
| Messages and parts | `session/message-v2.ts` | Message/part persistence and retrieval. |
| Status | `session/status.ts` | Busy, retry, idle state. |
| Diff and revert | `session/summary.ts`, `session/revert.ts` | File diff summaries and revert/unrevert actions. |
| Stats | `session/stats.ts` | Token/cost/session aggregate data. |

## Storage and config map

Config and storage are separate. Config is resolved from well-known remote config, global files, custom file env, project files, inline env content, and config directories. Storage is durable JSON under `Global.Path.data/storage` plus SQLite/Drizzle databases under `Global.Path.data`.

| Need | File | Notes |
| --- | --- | --- |
| Global paths | `@nikcli-ai/util/global` | XDG/AppData resolution, `NIKCLI_DATA_DIR`, cache version. |
| Config loading | `config/config.ts` | Merge order, plugin/command/agent loading, legacy tools migration. |
| Config paths | `config/paths.ts` | Project file discovery, directory list, JSONC substitution. |
| TUI config | `config/tui.ts`, `config/tui-schema.ts` | Keybinds, scroll, mouse, layout config. |
| JSON store | `database/database.ts` | Read/write/update/list/transaction, locks, cache, migrations. |
| SQLite | `database/database.ts` | Drizzle client, WAL, migrations, PRAGMAs. |

## Extension map

| Extension type | Source | Runtime hook |
| --- | --- | --- |
| Server plugin | `plugin/index.ts` | Internal plugins, configured plugins, built-ins, auth hooks, tool hooks, event hooks. |
| TUI plugin | `packages/tui/src/plugin` | Command, route, dialog, sidebar, and keybind registration. |
| MCP | `mcp/index.ts` | Local stdio and remote HTTP/SSE clients converted into agent tools. |
| Connectors | `connectors/index.ts`, `connectors/registry.ts` | External service status, health checks, dynamic tools, prompts. |
| Skills | `skill/skill.ts` | Skill discovery from config directories and external skill folders. |
| Built-in tools | `tool/registry.ts` | Model and flag gated tool set for sessions. |

## TUI map

The TUI starts in `cli/cmd/tui/thread.ts`, creates a worker from `cli/cmd/tui/worker.ts`, then renders `packages/tui/src/app.tsx`. With no network options it uses direct RPC fetch and event source. With host/port options it starts a real HTTP server and talks through the SDK.

| Area | Files |
| --- | --- |
| Route state | `packages/tui/src/context/route.tsx` |
| Session route | `packages/tui/src/routes/session/index.tsx` |
| Workspace route | `packages/tui/src/routes/workspace`, `routes/changes`, `routes/tree`, `routes/git-graph`, `routes/github` |
| Command palette | `packages/tui/src/component/dialog-command.tsx` |
| Remote control | `server/httpapi/tui.ts`, `packages/tui/src/event.ts` |
| Plugin runtime | `packages/tui/src/plugin/runtime.ts`, `plugin/api.tsx` |

## Mobile map

The Expo app lives in `packages/mobile`, while the host API lives in `packages/nikcli/src/server/httpapi/mobile.ts` and helpers under `packages/nikcli/src/mobile`.

| Need | Host source | App source |
| --- | --- | --- |
| Pairing tokens | `src/mobile/auth.ts`, `routes/mobile.ts` | `packages/mobile/app/connect.tsx` |
| Session streaming | `routes/mobile.ts` | `packages/mobile/hooks/use-session-stream.ts` |
| GitHub repos | `src/mobile/github-repo.ts` | `packages/mobile/app/(app)/repos` |
| Routines | `src/mobile/routine.ts` | `packages/mobile/app/(app)/routines` |
| Terminal | `routes/mobile.ts`, `src/pty` | `packages/mobile/app/(app)/terminal` |
| Settings | `routes/mobile.ts`, config/provider/MCP/connectors services | `packages/mobile/app/(app)/settings` |

## Generated and package map

| Package | Purpose | When to inspect |
| --- | --- | --- |
| `packages/sdk/js` | Generated JavaScript SDK for server APIs. | After endpoint contract changes or SDK type failures. |
| `packages/plugin` | Plugin API package and TUI plugin contracts. | When implementing or debugging plugin manifest targets. |
| `packages/llm` | Route-based LLM provider package used by native runtime. | When provider streaming behavior differs from AI SDK path. |
| `packages/mobile` | Expo mobile application. | When a host route is correct but app behavior differs. |
| `packages/web` | Astro docs and dashboard pages. | When editing docs, dashboard, or public web pages. |
| `packages/remote` | Remote execution support. | When terminal remote or cloud relay behavior changes. |
| `packages/inference` | Inference provider/gateway package. | When nikcli-inference provider catalog or routing changes. |
| `packages/http-recorder` | HTTP recording utilities. | When fixture or provider request recording changes. |

## How to trace a feature

1.  Find the entry: command in `src/index.ts`, route in `server.ts`, or UI route in `tui/context/route.tsx`.
2.  Read the domain service imported by that entry. Route files usually call services from `session`, `provider`, `config`, `mcp`, `connectors`, or `workspace`.
3.  Check config and flags. Many features are enabled by config fields plus environment flags from `@nikcli-ai/util/flag`.
4.  Check storage. Durable behavior usually writes through `Storage.Service` or a SQLite helper.
5.  For client behavior, trace generated SDK types in `packages/sdk/js/src/httpapi/generated` and UI code in `packages/mobile` or TUI route files.

Terminal

bash 

```
rg -n "route-or-command-name" packages/nikcli/src
rg -n "operationId|HttpApiEndpoint|get\\(|post\\(" packages/nikcli/src/server
rg -n "Config\\.Service|Provider\\.Service|Session\\.Service" packages/nikcli/src
```

$ shell · paste into your terminal

## Directory table

| Directory | Purpose |
| --- | --- |
| `account` | Local user account records and auth helpers. |
| `acp` | Agent Client Protocol integration. |
| `agent` | Agent definitions, prompts, generated agent metadata, and selection. |
| `analytics` | Usage and session analytics aggregation. |
| `auth` | Provider and external auth storage used outside connector-specific auth. |
| `background` | Background task runner and status. |
| `brain` | Brain scheduler, consolidation, and long-term context features. |
| `bus` | Event bus definitions used by server, TUI, sessions, MCP, and permissions. |
| `chatbot` | Slack, Discord, Teams, Google Chat, Linear, and GitHub bot adapters. |
| `cli` | Yargs command definitions, OpenTUI app, local UI, network helpers. |
| `command` | Command templates, generated commands, and prompt commands. |
| `config` | Config schema, path discovery, JSONC parsing, migrations, TUI config. |
| `connectors` | External service connector status, credentials, tools, and operations. |
| `delegation` | Background delegation manager and parent/worker ownership. |
| `env` | Environment read/write helpers for provider code. |
| `file` | File listing, search, content, status, and time helpers. |
| `filesystem` | Effect filesystem helpers and compatibility wrappers. |
| `flag` | Environment flag parsing and dynamic flag getters. |
| `format` | Formatter detection and execution. |
| `git` | Git helpers and command wrappers. |
| `global` | Global data/cache/config/state/log/bin/repo paths and initialization. |
| `ide` | IDE detection and extension install helpers. |
| `image` | Image generation provider and model selection. |
| `installation` | Version, channel, update, and install/runtime metadata. |
| `locale` | Language, region, timezone, currency, and locale resolution. |
| `lsp` | Language server registry, lazy clients, diagnostics, symbols, references. |
| `mcp` | Model Context Protocol clients, OAuth, tools, prompts, resources. |
| `mobile` | Mobile auth, routines, Expo helpers, GitHub repo import, project detection. |
| `monitor` | Long-lived process monitoring and cancellation. |
| `permission` | Permission rules, pending requests, persisted always approvals. |
| `plugin` | Server plugins, auth plugins, installer, package manifest detection. |
| `project` | Project detection, instance context, VCS metadata. |
| `provider` | Provider catalog, auth, AI SDK adapters, model cache, transformations. |
| `pty` | Pseudo-terminal sessions and websocket I/O. |
| `question` | Interactive question prompts and replies. |
| `sandbox` | Sandbox and external directory checks for tool execution. |
| `scheduler` | Scheduled routine helpers. |
| `server` | Hono app, route groups, typed HttpApi bridge, proxying, mDNS. |
| `session` | Session records, messages, prompt execution, summaries, revert, stats. |
| `share` | Public share creation and public data retrieval. |
| `skill` | Skill discovery, loading, and prompt material. |
| `snapshot` | Snapshot and diff tracking for file changes. |
| `storage` | JSON storage service, locks, migrations, SQLite/Drizzle helpers. |
| `tool` | Built-in tool registry, definitions, prompts, and execution wrappers. |
| `util` | Shared utilities such as logs, queues, locks, wildcard, timeout, process helpers. |
| `workspace` | Workspace records, adaptors, remote/local targets, session proxy. |
| `worktree` | Git worktree creation, reset, and removal helpers. |

---

Source: https://nikcli-ai.dev/docs/source-map
