Skip to content

Architecture

ka is a workspace of small crates with a strictly one-way dependency direction: ka-harness → ka-term / ka-protocol / ka-dialect / ka-strand → ka-engine. The engine never imports a surface.

ka-harness ──► ka-term (ratatui TUI)
│ ► ka-protocol (Command / Event enums)
│ ► ka-dialect (catalog + 3 wires + discovery)
│ ► ka-strand (append-only sessions)
└────────────► ka-engine (engine: turn machine, Hands, gate, digests)
ka-index (SQLite FTS, optional) ka-sandbox (landlock, seatbelt, loopback net proxy)
ka-passport (Claude Pro/Max OAuth, optional behind the `passport` cargo feature)

The binary crate is published as ka-harness (renamed from ka-agent in v0.3.0; the old name is reserved for Ka Agent, a planned separate product: an optional persistent companion with long-term memory, messaging channels, and a web UI). Ka Agent will build on ka strictly from the outside, through the shipped surfaces: ka run --print ndjson, ka serve, ka acp, the strand format, or the binary as a subprocess. Embedders can also host the landlock sandbox themselves: the trampoline lives in ka-sandbox::trampoline (TRAMPOLINE_ARG + exec_trampoline), shared with the hidden wrap subcommand; ka-sandbox also carries the loopback network proxy and the macOS seatbelt backend. ka-passport is an optional crate behind the passport cargo feature: Claude Pro/Max subscription OAuth via a TokenSource trait. Resident-agent concerns (channels, schedulers, plugin runtimes, memory beyond strands) never enter these crates, and CI gates the binary’s dependency graph (cargo xtask deps) to keep it that way. Decision record: research/ka-harness/agent-boundary.md.

Two queues connect any surface to the engine, both plain serde enums, both NDJSON-shaped:

  • Command (surface → engine): Prompt, Steer (mid-turn steering; wire tag interject), Queue (held until the turn settles; wire tag defer), Abort, SetModel, SetEffort, SetMode, AlwaysAllow, Resume, Compact, Answer…
  • Event (engine → surface): TurnStarted (with a context meter), Delta (text, thought, or tool call), CallStarted / CallFinished, Ask, TurnFinished (stop kind, usage, cost, cache-hit), DigestStarted / DigestFinished, ModeChanged, Error…

Because the protocol is NDJSON-first, ka run --print ndjson is literally the engine’s Event side serialized. The TUI, the HTTP server, and the ACP adapter are all just different consumers of the same stream.

The Event enum has no catch-all variant, so an older consumer fails loudly on a newer event type instead of mis-parsing it. ka attach therefore skips SSE frames whose type it does not recognize when observing a newer ka serve; malformed JSON still surfaces as an error.

Every prompt runs through four states:

  1. Receiving: the prompt lands, guards and trust are checked.
  2. Speaking: the active Speaker streams the model’s response. Steers are checked between deltas; Esc aborts, keeping the partial transcript.
  3. Acting: tool calls whose clearance is granted run in parallel (FuturesUnordered), with results re-ordered to call order and per-tool timeouts. Exec-tier calls wait for your approval when in ask mode. A steer typed while a batch runs rides the history at the batch boundary as an [operator, while you were working] user message with a steer delivered ack. Filesystem work (read/grep/glob and the per-turn git snapshot) runs on blocking threads, and grep scans large candidate sets on parallel workers with byte-identical output, so a big repo walk never stalls streaming, redraws, or interrupts.
  4. Settling: post-turn maintenance. Ledger sync, digest threshold checks, queue drain, harness checks, strand flush. Steers that never reached a batch boundary settle into queued follow-on turns on the same strand instead of being dropped (attach clears them; a steer is strand-scoped).

Speaking and Acting alternate until the model stops calling tools or the step cap (max_steps, default 20) forces a text reply.

The engine crate knows nothing about terminals, TOML files, or any vendor’s HTTP quirks:

  • Speaker is the provider trait (“the model speaks through it”). The three implementations (Anthropic messages, OpenAI chat, OpenAI Responses) live in ka-dialect, vendored on reqwest + rustls with hand-rolled SSE. No SDK crates.
  • Hands is the tool registry trait (“the engine acts through them”). Every tool is a struct behind the same seam, which is where MCP servers, pathfinder, and delegate plug in.
  • A strand is the state: replaying its records to the tip reproduces everything: model, effort, mode, queued items. No other persistence exists in core.

Context pressure is handled by a ladder, cheapest first:

  1. Caps + spill: oversized tool output is parked on disk and referenced as spill://<id> (default 32 KB tail / 8 KB head) before the model ever sees it.
  2. Prune: blank tool results older than the protected window are elided with markers.
  3. Digest: a same-model summary that never cuts between a tool call and its result; triggers at a reserve threshold.
  4. Idle compaction: with [context] idle_minutes and idle_compact_pct set (off by default; /autocompact N|off live), idle sessions compact down to the configured percentage of context. See the config reference.
  5. Promotion: on overflow, ka can re-dispatch to a bigger-context sibling model ([context] promote, on by default).
  • Footprint contract in CI: binary size, cold-start, and idle RSS asserted against committed baselines.json; the size gate currently sits at 7.92 MB against the 10 MB contract (the opt-in code cargo feature adds ~1.2 MB when enabled).
  • Session bench (v0.6.0): a deterministic mock-provider benchmark drives the real binary through a pty (TUI) and headless, gating per-release against baselines.json: interactive CPU, peak memory, flatness of per-prompt CPU across a 75-prompt session, idle CPU (livelock guard), and tty writes per streamed answer (syscall-storm guard). CI runs the quick set (version p50 + RSS); the full gate runs on the release machine. The metric set and methodology live in bench/README.md.
  • Test suite: roughly 1,433 tests run in CI via cargo test --workspace --all-features.
  • Wire fixtures: recorded SSE transcripts per wire (including malformed chunks and partial-JSON repair cases) replayed in CI; never a live key.
  • Property tests: strand replay determinism, ledger refusal on stale writes, bash decomposition tables, hardstop matrix including wrapper obfuscation.

Read the original design document in the repository: research/ka-harness/architecture.md.