threecode/display

Search:
Group by:

Transcript formatting: markdown, receipts, tool banners, and session replay.

This module formats append-only scrollback content. It may write ordinary transcript text, usually while api.writeTranscriptWithFatPrompt has temporarily captured stdout or while terminal locking is already active, but it does not own volatile cursor movement or prompt repainting.

  • Markdown rendering: headers, fences, tables, bold/italic/code pass through printLine which calls applyInlineMd and wraps at terminal width. Tables buffer rows and render aligned box-drawing via renderMdTable.
  • Token receipt: the dim receipt in scroll history after each turn (renderTokenLine). Live token-bar policy lives in fatprompt.nim.
  • Tool banners: per-kind glyph and path header for each tool call result.
  • Session replay: replaySession reprints a loaded session in the same visual style as a live session, reusing the same render helpers.

The three-tier colour palette (bold cyan for hints, plain cyan for notes, grey-244 for subtle FYI output) avoids SGR dim and fgWhite which render below readable contrast on light terminal backgrounds.

Types

MarkdownState = ref object
  firstEmit*: bool
  tableBuf*: seq[string]
  codeBuf*: seq[string]
  inCode*: bool
Per-line markdown rendering state. Shared between the streaming path (api.nim feeds chunks line by line as they arrive over SSE) and the replay path (display.nim feeds the stored full content). Both call handleMdLine per line and finishMd at end so the visible output is byte-identical regardless of who fed the lines. ref so nested closures inside the handlers can mutate it.

Vars

Consts

AssistantTextStyle = "\e[97m"
SessionListCap = 20
Newest sessions shown by printSessionList / -l / :sessions. Paths arrive newest-first from listSessionPaths, so the cap is a simple slice. Listing is directory-scoped by design; the full set lives under sessionDir() for anyone who needs it.

Procs

proc assistantTextBytes(bytes: string): string {....raises: [], tags: [],
    forbids: [].}
proc cmdError(body: string) {....raises: [IOError], tags: [WriteIOEffect],
                              forbids: [].}
Actionable error from a system command — non-bold magenta, no indent, blank lines above and below.
proc cmdResponse(body: string) {....raises: [IOError], tags: [WriteIOEffect],
                                 forbids: [].}
System-command response. One blank line above and below, no indentation, default terminal color (matching LLM output). Distinguishes system feedback from model replies.
proc contextLabel(promptTokens, window: int): string {....raises: [], tags: [],
    forbids: [].}
"○ 12%" / "◔ 25%" / … / "● 92%". Empty when there's no useful number (no window). Previously also omitted when there were no tokens yet, which hid the context indicator at startup. We now always show a bullet with a percentage, defaulting to 0% when promptTokens is zero.
proc finishMd(s: MarkdownState; outFile: File): bool {.discardable,
    ...raises: [IOError], tags: [WriteIOEffect, ReadEnvEffect], forbids: [].}
Flush any pending code block or table buffer at end of content. Returns true if anything was written.
proc handleMdLine(s: MarkdownState; l: string; outFile: File): bool {.
    discardable, ...raises: [IOError], tags: [WriteIOEffect, ReadEnvEffect],
    forbids: [].}
Route one input line through markdown handlers (headers, fences, tables, paragraphs). Returns true if anything was written to outFile this call (table rows and code-block bodies buffer silently until flushed). State accumulates across calls.
proc initMarkdownState(firstEmit = true): MarkdownState {....raises: [], tags: [],
    forbids: [].}
proc installEditorTweaks() {....raises: [KeyError], tags: [], forbids: [].}
proc isSkillRead(act: Action): bool {....raises: [],
                                      tags: [ReadEnvEffect, ReadIOEffect],
                                      forbids: [].}
True when the action is a cat/head/sed-style read of a skill file (any path under a registered skills dir). The main loop suppresses banner + body output for these and prints its own dim "loaded skill: <name>" marker so the user sees a single, styled signal rather than a tool transcript.
proc listTools(toolLog: seq[ToolRecord]) {....raises: [IOError],
    tags: [WriteIOEffect], forbids: [].}
proc printActionResult(act: Action; res: string; code: int; idx: int; diff = "") {.
    ...raises: [IOError], tags: [ReadEnvEffect, WriteIOEffect], forbids: [].}
proc printCompactHeadTail(res: string; idx: int; head = CompactHead;
                          tail = CompactTail) {....raises: [IOError],
    tags: [ReadEnvEffect, WriteIOEffect], forbids: [].}
Head/tail truncation for non-bash tool kinds that don't have the streaming-terminal semantics (read, web search, web fetch). Keeps the first head and last tail lines with an "N lines hidden" marker in the middle. Bash uses printBashScroll instead.
proc printDiff(diff: string) {....raises: [IOError],
                               tags: [ReadEnvEffect, WriteIOEffect], forbids: [].}
proc printKnownGood() {....raises: [], tags: [], forbids: [].}
List every (provider, variant) combo in KnownGoodCombos along with its model + version tags. Powers --good / 3code good so a user can survey the curated catalog without configuring anything.
proc printSessionList(paths: seq[string]; currentPath: string; showCwd: bool) {.
    ...raises: [KeyError, IOError],
    tags: [ReadIOEffect, ReadEnvEffect, WriteIOEffect], forbids: [].}
proc printSkillLoaded(act: Action) {....raises: [IOError], tags: [ReadEnvEffect,
    ReadIOEffect, WriteIOEffect], forbids: [].}
proc printToolResult(kind: ActionKind; res: string; code: int; idx: int;
                     diff = "") {....raises: [IOError],
                                  tags: [ReadEnvEffect, WriteIOEffect],
                                  forbids: [].}
Body of a tool turn. bash uses the scroll-area shape via printBashScroll (streaming-style: marker + tail), read/web use the head/tail compact via printCompactHeadTail; write shows the new file contents through the same head/tail path as read. patch prints the headline only on success, or the first error line on failure. A non-empty diff is colourised after the body (for patch). Banner is drawn separately by renderToolBanner.
proc renderAssistantContent(content: string; outFile: File = stdout) {.
    ...raises: [IOError],
    tags: [WriteIOEffect, ReadEnvEffect, ReadIOEffect, WriteDirEffect],
    forbids: [].}
Bullet â—Ź ` + bright-white content with full markdown structure (headers, fences, tables, inline bold and backtick-code). Used by replay and by the live path when content was buffered (rare: streaming bypasses this and feeds the same handlers chunk by chunk). `outFile lets tests capture output to a temp file; default is stdout.
proc renderHelp() {....raises: [IOError], tags: [WriteIOEffect], forbids: [].}
:help body in default terminal color. 3code highlighted bright bold cyan; :command tokens highlighted bright white.
proc renderTokenLine(usage: Usage; window: int; elapsedS = -1) {.
    ...raises: [IOError], tags: [WriteIOEffect], forbids: [].}
"○N% ↑Nk ↻Nk ↓Nk Ts": context glyph, fresh, cached, generated, optional duration. Two-space separation, no padding inside slots. Empty when usage has no totals. Live passes seconds; replay passes
-1 to omit the duration.
proc renderToolBanner(banner: string; kind: ActionKind; code: int; elapsedS = -1) {.
    ...raises: [IOError], tags: [WriteIOEffect], forbids: [].}
Final tool banner. Icons render in default text color regardless of exit code. Optional (Ns) suffix when elapsedS >= 1 (live); replay passes -1 to omit it.
proc renderToolPending(banner: string; kind: ActionKind) {....raises: [IOError],
    tags: [WriteIOEffect], forbids: [].}
Pre-execution banner: grey bullet + grey banner. Live only; the live caller overwrites this line with renderToolBanner once the action returns. Replay skips this and goes straight to the result form.
proc replaySessionTail(messages: JsonNode; toolLog: seq[ToolRecord];
                       window: int; family: string): Usage {....raises: [IOError], tags: [
    RootEffect, WriteIOEffect, ReadEnvEffect, ReadIOEffect, WriteDirEffect],
    forbids: [].}
Replay the whole conversation into scrollback so a resumed session drops the user back into the full prior context, reachable by scrolling up. The session file is already bounded by compaction to roughly one context window, so replaying it in full stays manageable. Renders via the same helpers the live path uses; usage is read from each assistant message's inline usage field (legacy sessions saved before the inline format simply skip the token line). The last assistant's inline receipt is suppressed and its usage is returned instead — the caller paints the live token bar with it, so the resumed shape matches the post-endTurn typing-ready state.
proc showProfile(p: Profile) {....raises: [IOError], tags: [WriteIOEffect],
                               forbids: [].}
proc showTool(arg: string; toolLog: seq[ToolRecord]) {.
    ...raises: [IOError, IOError], tags: [WriteIOEffect, ReadEnvEffect],
    forbids: [].}
proc skillNameFromAct(act: Action): string {....raises: [],
    tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
Best-effort extraction of the skill name from a skill-read action. Returns the basename without the .md suffix, or "" if we can't tell. The bash form scans for the first registered skills-dir prefix in the command body, then takes the path that follows.
proc subtleWrite(outFile: File; body: string) {....raises: [IOError],
    tags: [WriteIOEffect], forbids: [].}
FYI tier — grey 244, readable on both backgrounds. Replaces styledWrite(styleDim, ..., resetStyle) which is invisible on white terminals.
proc subtleWriteLn(outFile: File; body: string) {....raises: [IOError],
    tags: [WriteIOEffect], forbids: [].}
proc tokenLineBytes(usage: Usage; window: int; elapsedS = -1): string {.
    ...raises: [], tags: [], forbids: [].}
Pure-byte form of the token receipt row used by the replay path (saved sessions). The live path uses emitUserSubmit / commitTranscriptBytes, which paint the receipt in place of the previous turn's bar. Returns "" when there's no usage.
proc tokenLineLabel(usage: Usage; window: int; elapsedS = -1): string {.
    ...raises: [], tags: [], forbids: [].}
Pure label string for the bar / receipt: "○N% ↑input ↻cached ↓completion Ts" (no styling, no leading spaces — caller wraps it in cyan-bright for the bar or dim for the receipt). Empty when there's no usage to report.
proc toolBannerBytes(banner: string; kind: ActionKind; code: int; elapsedS = -1): string {.
    ...raises: [], tags: [], forbids: [].}
proc toolIcon(kind: ActionKind): string {....raises: [], tags: [], forbids: [].}
proc toolResultBytes(kind: ActionKind; res: string; code: int; idx: int;
                     diff = ""): string {....raises: [], tags: [ReadEnvEffect],
    forbids: [].}
proc toolTranscriptBytes(act: Action; res: string; code: int; idx: int;
                         diff = ""; elapsedS = -1): string {....raises: [],
    tags: [ReadEnvEffect], forbids: [].}
proc toolTranscriptBytes(banner: string; kind: ActionKind; res: string;
                         code: int; idx: int; diff = ""; elapsedS = -1): string {.
    ...raises: [], tags: [ReadEnvEffect], forbids: [].}
proc welcome(p: Profile): minline.LineEditor {....raises: [IOError, KeyError], tags: [
    WriteIOEffect, ReadDirEffect, ReadIOEffect, ReadEnvEffect, WriteDirEffect],
    forbids: [].}
proc writeAssistantBullet(outFile: File = stdout) {....raises: [IOError],
    tags: [WriteIOEffect], forbids: [].}

Templates

template err(args: varargs[untyped])
template errLn(args: varargs[untyped])
template hint(args: varargs[untyped])
template hintLn(args: varargs[untyped])
template note(args: varargs[untyped])
template noteLn(args: varargs[untyped])
template warn(args: varargs[untyped])
template warnLn(args: varargs[untyped])