How the Chat REPL Works
kompile chat is not a blocking readLine → HTTP request → print loop. It runs an asynchronous, event-driven terminal REPL that keeps your prompt responsive while tokens stream, tools execute, subagents report progress, background builds finish, and peer agents send messages over the coordination bus.
Component architecture
ChatRepl is intentionally kept as a thin interactive shell that wires together six focused subsystems:
| Component | Responsibility |
|---|---|
ChatRepl | Owns the JLine Terminal / LineReader, KompileTui layout, input line routing (submitInteractiveLine), status bar, activity panel, and lifecycle hooks. |
ChatCommandRouter | Parses and dispatches all / slash commands (stateless commands immediately; exclusive modal/network commands deferred until turn release). |
ChatMessageHandler | Owns turn execution under a single turnDispatchLock: async interactive turns, synchronous headless/crawl turns, external wake injection, .pending-events.json, judge/supervisor interrupting feedback, quota auto-continue, and model failover. |
MessageQueueManager + MessageQueue | Disk-backed FIFO queue for user messages and bridged peer mail that arrive while the LLM is busy, with inline Up-to-edit, reordering, and auto-dequeue. |
AgenticChatLoop | Multi-round model + tool-calling loop with Enforcer pre-tool gates, Judge post-turn audits, automatic context compaction, and backgroundable tool phases. |
SessionLifecycleManager & AuxiliaryChatRepl | Session restore/resume, local-vs-server mode switching, and side-channel auxiliary/judge chats that can steer the main session. |
Two operational modes run through the same REPL shell:
- Local mode (default
cli-harness) — direct LLM API streaming (DirectLlmClient) with local tool execution insideAgenticChatLoop. - Server mode (connected to
kompile-appvia MCP SSE) — inline RAG chat, server-side agent streaming, and MCP tool execution.
SetupWizard & session bootstrap
When kompile chat starts without an existing config (or with --setup), SetupWizard runs a mode-first numbered wizard so users never see irrelevant API-key prompts when launching a passthrough CLI or resuming a session:
- Mode selection: Standard Chat, Passthrough (
claude,codex,agy,opencode, etc. — either Kompile-managed with MCP/memory/guardrails injected, or direct native terminal), Workflow team, Resume (kompile resume), or Resume All (30m–24hwindow). - Runtime selection (Standard Chat): Kompile local model (
local-runtime), external OpenAI-compatible local endpoint (Ollama/vLLM/LM Studio), direct cloud/OAuth provider, or installedkompile-chatservice. - Auth & live model discovery: OAuth, API key, or named stored credential; queries the provider's live model catalog (falling back to
~/.kompile/cache/model-catalogs.jsonwhen offline) and selects model + reasoning effort. - Scoped persistence: Saves to session, project
<repo>/.kompile/, or global~/.kompile/config/, optionally as a named project profile.
Before the first model call, session bootstrap merges layered configs (chat-ui-config.json, subagent-config.json, enforcer-config.json, SessionModelLadder), mounts built-in and .mcp.json tools, loads AGENTS.md / .kompile/rules/ / skills / code-index state, prepares <memory_context> (standing rules, relevant memories, warn-only incidents) and <kompile_reminders>, binds AgentBroadcastManager to <repo>/.kompile/coordination/, drains any .pending-events.json wakes, and brings up KompileTui (TopBar, managed transcript, optional ChatSidebar, input pane, activity pane, StatusBar) or --web-controls - SSE streaming.
Inside the six-stage agent execution loop (AgenticChatLoop)
Inside a standard agentic turn, the harness structures tool execution across six stages:
- Recall & orient: Injects
<memory_context>and<kompile_reminders>, with deeper lookup viamemory,code_search/code_graph,grep_batch,glob,lsp, andread_batch(Enforcer redirects rawcat/grep/find/sed). - Plan & track: Maintains a live
todowritechecklist rendered in the Activity Pane (/todos) and Web/processestab, and evaluates parallel fan-out. - Delegate & coordinate: Calls
resolve_modelbeforetask/multi_task/quorum_task(honoring/subagent-config banand explicit credentials), coordinates on.kompile/coordination/viaedit_coordinator(file locks,monitor_edit, FIFO named locks,preflight_activity/wait_for_activityRAM/GPU lanes, durable mail withCoordinationMessageMandate), and enforces the mandatory subagentprogressexit gate. - Edit safely: Enforces read-before-edit on
edit/edit_batch/edit_patch/write, blocks forbidden git/config operations, and logs every edit intodiff_index. - Verify, build & recover: Validates touched files with fail-closed
lsp action=check, compiles/tests throughbuildor monitoredprocess action=launch(host-sidetimeout_minutes,process_notify, no shellsleep/wait loops), and triggers request-boundaryModelFailoverControllerretries on quota/outage failures. - Judge, compact & persist: Runs configured Judge audits, triggers
/auto-compactnear context ceilings, recordsprogressreports and durable memories, and persists transcripts under~/.kompile/conversations/.
How every input line is routed (submitInteractiveLine)
When you press Enter, ChatRepl.submitInteractiveLine evaluates the line in strict deterministic order so interactive prompts, queue edits, and modals never collide with streaming turns:
- Active queued-message edit — If you pressed
Up(or/queue-edit) to edit a queued message, the entire line (even if it starts with/) updates that existing queue item instead of dispatching a duplicate. - Pending permission prompt — If a tool requested interactive confirmation (
PermissionService), the line answers that approval prompt. - Pending interactive question — If a local
QuestionTool, a tool-hostwake.question, or a served OpenCode agent question is awaiting user input, the line routes straight back as the answer. - Deferred interactive command on blank Enter — If a modal/network slash command was deferred while a turn was running and the turn has now released, pressing Enter on a blank line opens that command on the main JLine reader thread.
- Mid-turn deferral of exclusive slash commands — While a turn owns the model (
isTurnOwnerActive()), slash commands that open nested JLine modals, wait on network logins, or rebuild session history are never run on the reader thread (which would wedge streamingprintAbovebehind JLine's reader lock):- Deferred until turn release:
/auth,/provider,/setup,/model,/thinking,/install,/resume. - Executed immediately mid-turn: stateless inspection and queue commands (
/help,/queue,/queues,/jobs,/cost,/usage,/status,/ui, etc.).
- Deferred until turn release:
- Subagent activity view routing — If the Activity Panel is focused on a live subagent and the input is not a
/command, the line is sent directly as a follow-up to that subagent (if the subagent has already ended, the REPL returns cleanly toMainand dispatches the message there instead of dropping it). - Main dispatch — Leading
/commands go toChatCommandRouter(rendered viatui.runCommandOutput), and ordinary text is recorded in the transcript scroll region and handed toChatMessageHandler.handleChatMessage.
Terminal rendering without corrupting your typing
Inside KompileTui, the terminal is split into a scrollable transcript region, a reserved activity/inspector panel, a live status bar, and the JLine input editor at the bottom:
- Thread-safe output above the prompt: Background streaming tokens, tool logs, and notices are recorded into
KompileTuiand emitted through JLine'sprintAbovepath (ChatCompleter), so async output never overwrites text you are actively typing. - No scroll-region corruption from autocomplete: Slash-command completion candidates render inside the reserved activity panel rather than below the JLine prompt row, preventing tab-completion from scrolling the transcript.
- Debounced subagent & activity refreshes: Subagent output chunks and metadata coalesce on a
50 mstimer and route strictly to the selected subagent's activity view — never pollutingMain.
Turn ownership, queueing, and steering
All turn transitions are serialized under ChatMessageHandler.turnDispatchLock:
Interactive async turns vs. synchronous headless turns
- Interactive sessions dispatch each accepted turn on a dedicated worker thread (
standard-chat-dispatch) while the main thread immediately returns to JLinereadLine. - Headless / crawl sessions (
--prompt,--force-agentic) run synchronously on the calling thread (synchronousTurnLock) so one-shot callers do not exit or tear down the transcript before the requested turn finishes.
Chat Queue (MessageQueue & MessageQueueManager)
When a turn is active and you submit another prompt — or when you stage follow-ups explicitly with /queue <text>, or when actionable peer mail arrives via AgentBroadcastManager — items enter the session's thread-safe, disk-backed FIFO queue (~/.kompile/queues/queue-<sessionId>.json):
- Per-message identity & status lifecycle: Each queued item receives an 8-character ID and tracks status across
PENDING,EDITING,SENDING_NOW, andFAILED. Duplicate identical payloads are silently deduplicated on enqueue and on edit. - Edit lease safety (
EDITING): Pressing↑on a blank prompt acquires a single active edit lease (beginEdit) on the latest queued item without removing it from the visible queue. Both auto-dequeue (dequeue) and manual/queue-send(takeForSend) refuse to claim any item currently inEDITINGstate until the edit completes or is cancelled (cancelEdit). - Safe chaining & rollback:
/queue-send-allstarts a bounded queue chain (startQueueChain) and dispatches only the head item — subsequent items drain sequentially as each async turn finishes, never launching overlapping turns. If dispatch cannot start or rolls back,requeueFirstrestores the claimed item to index0with its original ID and order intact. - Persistence & Web Harness parity: Every mutation writes atomically to
~/.kompile/queues/queue-<sessionId>.jsonso queued items survive/restartand crashes. The Web Harness (WebCommandResolver) reads and mutates the exact same per-session queue file for/queue,/queues,/queue-edit,/queue-move,/queue-remove,/queue-clear, and/queue-status, and the live CLI session drains it automatically. - Peer-mail durability: Bridged peer messages from
.kompile/coordination/are acknowledged on the coordination bus only afterMessageQueue.ensureSaved()confirms the queue file is written to disk.
| Command | Action |
|---|---|
Type + Enter while busy | Append follow-up to the session queue |
↑ on blank prompt | Pull the latest queued item back into the input buffer for inline editing |
/queue <text> | Enqueue a message without sending immediately |
/queues | List all queued items with 1-based position and 8-char ID |
/queue-edit <id> <text> | Replace a queued item's text without changing its queue position |
/queue-move <id> <n> | Reorder a queued item to 1-based position n |
/queue-remove <id> / /queue-clear | Remove one queued item or empty the queue |
/queue-send [id] / /queue-send-all | Send the next item (or specific ID), or chain-drain the whole queue when idle |
/queue-status / /auto-dequeue | Show queue depth/status or toggle automatic draining between turns |
Backgrounding a running turn (Ctrl+B)
Pressing Ctrl+B during a backgroundable phase releases the prompt into a direct input lane for the active turn without transferring ownership away from it. New lines can feed the running task directly, and completion wakes automatically release blocking waits so you do not have to press Ctrl+B manually just to receive a background build or subagent completion.
Interrupting feedback (handleUserFeedback)
Judge policy violations, supervisor feedback, and side-channel AuxiliaryChatRepl control messages enter through handleUserFeedback(message, interrupt):
- If a turn is currently running, the feedback is enqueued under
turnDispatchLockbefore publishing cancellation (cancel(false)wheninterrupt=true), guaranteeing the replacement turn can never be accidentally cancelled by the previous turn's abort signal. - User-submitted input or feedback immediately disarms any pending quota auto-continue timer and re-arms the
/continuebudget so the human always stays in control.
External events, wakes, and crash-safe .pending-events.json
kompile chat acts as a reactive wake target for asynchronous work across both the local JVM and external MCP tool hosts:
- Local process exit monitors (
process action=launch monitor=true) - Subagent completions & idle watchdog alerts (
SubagentIdleWatchdog) - Edit-coordinator wakes (
AgentBroadcastManagerdeliveringwake.*for released edit locks, granted named locks, freed RAM/GPU lanes, and peer mail)
Every wake enters ChatMessageHandler.handleExternalMessage(event):
- Crash-safe persistence first: Before returning
trueto the caller (which allows the bridge to acknowledge the mailbox message), the handler mirrors the event into<transcript>.pending-events.jsonbeside the session transcript. - Busy-turn injection vs. idle wake:
- If the session is idle, the handler batches any held events and immediately dispatches a wake turn.
- If a turn is running, the handler either injects the event at the next tool/model boundary or holds it for turn completion (automatically releasing blocking waits).
- Resume replay with staleness protection: If the chat restarts (
/restart), is interrupted, or crashes before a turn logs the event,startAcceptingExternalMessages()reloads.pending-events.jsonon the next launch and delivers the remaining events. Any event that waited longer than 1 minute (LATE_EVENT_AGE) is prefixed with a[Late delivery: this event arrived at ..., Xm ago. Check the current state before acting on it.]header so the model verifies current state instead of acting on stale assumptions.
Continuity, failover, and restart lifecycle
Built directly into the REPL turn loop are safeguards for long-running sessions:
- Per-session model failover (
SessionModelLadder): Loaded fresh per turn so wizard edits take effect immediately without restarting; transient provider errors or quota limits fail over down the configured ladder. - Usage-limit auto-continue (
UsageLimitAutoContinue): Watches provider rate-limit reset windows (e.g., 5-hour quota resets) and resumes automatically once the window opens — unless the user types first, which immediately disarms it. - Seamless
/restart: Marks the session as restarting (noteSessionRestarting()) so cancelling the in-flight turn does not look like a user Escape, preserves the transcript and.pending-events.json, and hands off toSessionRestartLauncherto resume cleanly.
Related docs
- Edit Coordinator & Message Bus — the file-based coordination bus, durable mailboxes,
HostWakeOutbox, andAgentBroadcastManagerthat feed the REPL - Monitors & Process/Subagent Browser — automatic completion monitors,
process_notify,monitor_edit, and the interactive Process & Subagent Browser (↓/Enter/Delete) below the prompt - CLI Harness (TUI & Config) — visual layout, keybindings, mouse controls, and layered configuration
- How a Kompile Session Works — user-facing walkthrough from
kompile chatto tool turns - The Web Harness — browser UI over the same session/turn model with bounded SSE reconnect
- The Enforcer & The Judge — pre-tool gates and post-turn audit feedback wired into the REPL