minimal agent cli memoria.tools
memoria STREAMING.md
7.6 kB 112 lines
Markdown

Streaming Architecture #

Status #

This document specifies the production streaming path for the TUI. The implementation supports one active OpenRouter or Codex SSE request, including sequential tool rounds.

Goals #

  • Keep terminal input, animation, network I/O, and cancellation responsive while a response is active.
  • Process response bytes as they arrive instead of waiting for the complete HTTP body.
  • Keep the complete assistant response in application state so it can be redrawn.
  • Prevent HTTP and provider code from writing to the terminal directly.
  • Give provider adapters a stable, provider-neutral event boundary.
  • Keep application state and terminal rendering on one thread. Run blocking tools on one sequential worker.

Non-Goals For The First Increment #

  • Parallel requests or conversations.

Layers #

Application #

The application owns input, conversation state, cancellation UX, and rendering. Network, provider, and tool-completion events enter the application through owned queues; only the main loop mutates the model, session, or terminal.

Provider Adapter #

The provider adapters serialize requests and convert provider SSE payloads into normalized events. Provider-specific completion markers and JSON structures do not leak into the application.

Initial normalized events are:

  • Text_Delta
  • Reasoning_Start
  • Reasoning_Delta
  • Reasoning_End
  • Tool_Calls
  • Usage
  • Continuation
  • Finished
  • Failed
  • Cancelled

Visible reasoning uses a provider-neutral lifecycle and remains separate from opaque provider continuation state. OpenRouter tool-call deltas are accumulated by call index before a normalized owned Tool_Calls event enters the application.

SSE #

The HTTP package's SSE parser accepts arbitrary byte chunks and emits complete events. Callback data is borrowed and valid only during the callback. The parser handles LF, CRLF, comments, and multiline data fields.

HTTP Transport #

http.SSE_Stream owns a libcurl multi handle and at most one easy handle, including copied request data, response limits, error bodies, and cleanup. network_pump advances it through http.sse_pump, while network_poll delegates combined curl and stdin polling to http.sse_poll_descriptor.

Main Loop #

Each loop iteration:

  1. Calls network_pump to advance immediately available work.
  2. Drains provider events through update.
  3. Renders model changes.
  4. Calls curl_multi_poll, including stdin as an extra descriptor and using the next animation deadline as its timeout.
  5. Reads a terminal message when stdin is ready.
  6. Repeats.

Curl write callbacks only parse and append owned events. They never render or invoke application update logic recursively.

When a provider requests tools, the application records and renders the calls, clones them into a single sequential worker, and returns to this loop. While the worker owns a batch, the main loop polls stdin directly instead of touching provider state. Completed outputs cross back as owned values and are recorded in the session before the next provider request starts.

Ownership #

  • Request URL, headers, and JSON body remain alive until the easy handle completes or is cancelled.
  • SSE callback slices are borrowed.
  • Event text is cloned before it is queued.
  • Reasoning block IDs, text, and continuation payloads are cloned before they are queued.
  • Tool call IDs, names, and accumulated argument JSON are cloned before they are queued.
  • The application response buffer owns all accepted text until model destruction.
  • Cancelling removes and cleans up the easy handle, then queues Cancelled.

Configuration #

Provider and model settings use this precedence:

  1. Built-in openrouter and openrouter/auto defaults.
  2. $XDG_CONFIG_HOME/memoria/config.json, or ~/.config/memoria/config.json.
  3. memoria.json in the startup working directory.
  4. OPENROUTER_MODEL as a deprecated model override.
  5. MEMORIA_PROVIDER and MEMORIA_MODEL.

The supported providers are openrouter and codex. Invalid files and unsupported providers fail before raw terminal mode and network initialization. Configuration files reject unknown fields, including credentials. /models fetches the active provider's catalog and persists a selection to the user configuration.

OpenRouter credentials resolve from OPENROUTER_API_KEY first, then $XDG_CONFIG_HOME/memoria/auth.json or ~/.config/memoria/auth.json. Codex uses refreshable OpenAI OAuth credentials in the same store. The credential store must be owned by the current user, be a regular non-symlink file, remain below 16 KiB, and grant no group or other permissions. Invalid existing stores and missing credentials fail before terminal and network initialization.

Errors And Limits #

  • Non-2xx response bodies are collected up to a fixed limit and surfaced as failures.
  • SSE line, event, and accumulated response sizes are bounded.
  • Invalid JSON and incomplete streams fail the request.
  • Rate limits, retryable server responses, and transient transport failures retry up to five total attempts with exponential jittered backoff. Provider Retry-After-Ms and Retry-After hints take precedence.
  • Streaming requests allow 60 seconds for the first response body byte and 90 seconds between later body chunks. Both timeout classes use the same bounded retry policy.
  • No retry occurs after any text, visible reasoning, or opaque reasoning state has been emitted.
  • Escape and Ctrl-C cancellation also cancel a pending retry delay; Ctrl-C exits only while idle.
  • Provider output is treated as text and must not be interpreted as terminal escape sequences.
  • Tool-call rounds are unlimited by default. The third consecutive call with an identical tool name and argument JSON is rejected before any call in that batch executes.
  • Markdown parser state survives provider delta boundaries. Prose uses the default terminal color, single-marker emphasis uses italics, double-marker emphasis uses bold, inline code uses bold orange and fenced code uses light blue without rendering delimiters, thematic breaks span the usable width, and all six heading levels have distinct bold terminal styles. Pipe-led Markdown tables wait for a complete header and delimiter, then buffer rows until the table ends and render a Unicode box table with separators between rows and centered bold-orange headers. Columns use the longest cell in each column, capped by the terminal width; longer cells wrap when needed. Table lines are bounded by the Markdown tail limit, and tables exceeding the 64 KiB buffer switch to row-by-row streaming at widths measured from the buffered rows.
  • list_directory, read_file, and write_file are confined to the startup working directory; absolute paths, parent traversal, symlinks, oversized files, and excessive listings are rejected or bounded. write_file creates or truncates UTF-8 files but does not create parent directories.
  • bash runs on the tool worker from the startup working directory with detached stdin, merged stdout and stderr, a 64 KiB output cap, and a maximum 120-second timeout. It is not a sandbox. Cancellation terminates the child process and escalates to a kill after a short grace period.

Planned Follow-Ups #

  1. Upgrade rune-width wrapping to full grapheme-cluster handling for complex emoji sequences.
  2. Move conversation and tool-round orchestration into a provider-neutral agent runner.
  3. Add an OpenAI Responses API provider separate from the Codex backend.
  4. Support multiple easy handles only when the application has a concrete concurrency use case.