Skip to content

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:

ComponentResponsibility
ChatReplOwns the JLine Terminal / LineReader, KompileTui layout, input line routing (submitInteractiveLine), status bar, activity panel, and lifecycle hooks.
ChatCommandRouterParses and dispatches all / slash commands (stateless commands immediately; exclusive modal/network commands deferred until turn release).
ChatMessageHandlerOwns 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 + MessageQueueDisk-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.
AgenticChatLoopMulti-round model + tool-calling loop with Enforcer pre-tool gates, Judge post-turn audits, automatic context compaction, and backgroundable tool phases.
SessionLifecycleManager & AuxiliaryChatReplSession 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 inside AgenticChatLoop.
  • Server mode (connected to kompile-app via 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:

  1. 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–24h window).
  2. Runtime selection (Standard Chat): Kompile local model (local-runtime), external OpenAI-compatible local endpoint (Ollama/vLLM/LM Studio), direct cloud/OAuth provider, or installed kompile-chat service.
  3. 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.json when offline) and selects model + reasoning effort.
  4. 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:

  1. Recall & orient: Injects <memory_context> and <kompile_reminders>, with deeper lookup via memory, code_search/code_graph, grep_batch, glob, lsp, and read_batch (Enforcer redirects raw cat/grep/find/sed).
  2. Plan & track: Maintains a live todowrite checklist rendered in the Activity Pane (/todos) and Web /processes tab, and evaluates parallel fan-out.
  3. Delegate & coordinate: Calls resolve_model before task/multi_task/quorum_task (honoring /subagent-config ban and explicit credentials), coordinates on .kompile/coordination/ via edit_coordinator (file locks, monitor_edit, FIFO named locks, preflight_activity / wait_for_activity RAM/GPU lanes, durable mail with CoordinationMessageMandate), and enforces the mandatory subagent progress exit gate.
  4. Edit safely: Enforces read-before-edit on edit/edit_batch/edit_patch/write, blocks forbidden git/config operations, and logs every edit into diff_index.
  5. Verify, build & recover: Validates touched files with fail-closed lsp action=check, compiles/tests through build or monitored process action=launch (host-side timeout_minutes, process_notify, no shell sleep/wait loops), and triggers request-boundary ModelFailoverController retries on quota/outage failures.
  6. Judge, compact & persist: Runs configured Judge audits, triggers /auto-compact near context ceilings, records progress reports 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:

  1. 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.
  2. Pending permission prompt — If a tool requested interactive confirmation (PermissionService), the line answers that approval prompt.
  3. Pending interactive question — If a local QuestionTool, a tool-host wake.question, or a served OpenCode agent question is awaiting user input, the line routes straight back as the answer.
  4. 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.
  5. 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 streaming printAbove behind 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.).
  6. 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 to Main and dispatches the message there instead of dropping it).
  7. Main dispatch — Leading / commands go to ChatCommandRouter (rendered via tui.runCommandOutput), and ordinary text is recorded in the transcript scroll region and handed to ChatMessageHandler.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 KompileTui and emitted through JLine's printAbove path (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 ms timer and route strictly to the selected subagent's activity view — never polluting Main.

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 JLine readLine.
  • 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, and FAILED. 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 in EDITING state until the edit completes or is cancelled (cancelEdit).
  • Safe chaining & rollback: /queue-send-all starts 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, requeueFirst restores the claimed item to index 0 with its original ID and order intact.
  • Persistence & Web Harness parity: Every mutation writes atomically to ~/.kompile/queues/queue-<sessionId>.json so queued items survive /restart and 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 after MessageQueue.ensureSaved() confirms the queue file is written to disk.
CommandAction
Type + Enter while busyAppend follow-up to the session queue
↑ on blank promptPull the latest queued item back into the input buffer for inline editing
/queue <text>Enqueue a message without sending immediately
/queuesList 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-clearRemove one queued item or empty the queue
/queue-send [id] / /queue-send-allSend the next item (or specific ID), or chain-drain the whole queue when idle
/queue-status / /auto-dequeueShow 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 turnDispatchLock before publishing cancellation (cancel(false) when interrupt=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 /continue budget 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 (AgentBroadcastManager delivering wake.* for released edit locks, granted named locks, freed RAM/GPU lanes, and peer mail)

Every wake enters ChatMessageHandler.handleExternalMessage(event):

  1. Crash-safe persistence first: Before returning true to the caller (which allows the bridge to acknowledge the mailbox message), the handler mirrors the event into <transcript>.pending-events.json beside the session transcript.
  2. 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).
  3. Resume replay with staleness protection: If the chat restarts (/restart), is interrupted, or crashes before a turn logs the event, startAcceptingExternalMessages() reloads .pending-events.json on 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 to SessionRestartLauncher to resume cleanly.

Released under the Apache-2.0 License.